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": "# times - times loop for your coffee.\n#\n# Author: Veselin Todorov <hi@vesln.com>\n# Licensed under the MIT License.\n", "end": 65, "score": 0.9998746514320374, "start": 50, "tag": "NAME", "value": "Veselin Todorov" }, { "context": "oop for your coffee.\n#\n# Author: V...
test/time.test.coffee
vesln/times
1
# times - times loop for your coffee. # # Author: Veselin Todorov <hi@vesln.com> # Licensed under the MIT License. require 'should' times = require '../src/times' describe 'time', -> it 'should have version', -> times.version.should.be.ok it 'should extend Number', -> 1.times.should.be.ok it 'should call a cb x times', -> x = 0; times 5, -> x++ x.should.eql 5 y = 0; 5.times -> y++ y.should.eql 5 it 'should return an x length array of return values', -> arr = 5.times (i) -> i arr.should.eql [1,2,3,4,5] it 'should return an x length array of any other type', -> ['string', 0, [], {}, null, undefined, true, false].forEach (el) -> arr = 3.times el arr.should.eql [el, el, el]
214568
# times - times loop for your coffee. # # Author: <NAME> <<EMAIL>> # Licensed under the MIT License. require 'should' times = require '../src/times' describe 'time', -> it 'should have version', -> times.version.should.be.ok it 'should extend Number', -> 1.times.should.be.ok it 'should call a cb x times', -> x = 0; times 5, -> x++ x.should.eql 5 y = 0; 5.times -> y++ y.should.eql 5 it 'should return an x length array of return values', -> arr = 5.times (i) -> i arr.should.eql [1,2,3,4,5] it 'should return an x length array of any other type', -> ['string', 0, [], {}, null, undefined, true, false].forEach (el) -> arr = 3.times el arr.should.eql [el, el, el]
true
# times - times loop for your coffee. # # Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Licensed under the MIT License. require 'should' times = require '../src/times' describe 'time', -> it 'should have version', -> times.version.should.be.ok it 'should extend Number', -> 1.times.should.be.ok it 'should call a cb x times', -> x = 0; times 5, -> x++ x.should.eql 5 y = 0; 5.times -> y++ y.should.eql 5 it 'should return an x length array of return values', -> arr = 5.times (i) -> i arr.should.eql [1,2,3,4,5] it 'should return an x length array of any other type', -> ['string', 0, [], {}, null, undefined, true, false].forEach (el) -> arr = 3.times el arr.should.eql [el, el, el]
[ { "context": "'use strict'\n#\n# Ethan Mick\n# 2015\n#\nos = require 'os'\nWorker = require './wo", "end": 27, "score": 0.9994738101959229, "start": 17, "tag": "NAME", "value": "Ethan Mick" } ]
lib/work_queue.coffee
ethanmick/coffee-mule
0
'use strict' # # Ethan Mick # 2015 # os = require 'os' Worker = require './worker' log = require './log' class WorkQueue constructor: (@script, @options = {})-> @workers = [] @queue = [] cpus = os.cpus().length @options.numWorkers ?= cpus @options.maxWorkers ?= cpus * 2 i = 0 log.debug "Starting #{@options.numWorkers} workers.." @fork() while i++ < @options.numWorkers fork: -> worker = new Worker(@script) worker.on 'ready', @_run.bind(this) worker.process.on 'exit', (code, signal)=> if code isnt 0 # Code will be non-zero if process dies suddenly log.warn "Worker process #{worker.pid} died. Respawning..." for w, i in @workers if w is undefined or w.pid is worker.pid @workers.splice(i, 1) # Remove dead worker from pool. @fork() @workers.push(worker) enqueue: (task, timeout, callback)-> if not callback callback = timeout timeout = null @queue.push(task: task, callback: callback, timeout: timeout) process.nextTick(@_run.bind(this)) _run: (worker)-> log.debug 'RUNNING', @queue return if @queue.length is 0 unless worker # Find the first available worker. for w in @workers if w.status is Worker.READY worker = w break return @fork() if not worker and @options.autoexpand and @workers.length < @options.maxWorkers return unless worker queued = @queue.shift() callback = null if queued.timeout log.debug 'timeout', queued.timeout timeoutId = null callback = -> clearTimeout(timeoutId) queued.callback.apply(this, arguments) timeoutId = setTimeout => worker.process.kill('SIGINT') callback.call(this, @options.timeoutResult or {}) , queued.timeout else callback = queued.callback worker.send(queued.task, callback) module.exports = WorkQueue
111422
'use strict' # # <NAME> # 2015 # os = require 'os' Worker = require './worker' log = require './log' class WorkQueue constructor: (@script, @options = {})-> @workers = [] @queue = [] cpus = os.cpus().length @options.numWorkers ?= cpus @options.maxWorkers ?= cpus * 2 i = 0 log.debug "Starting #{@options.numWorkers} workers.." @fork() while i++ < @options.numWorkers fork: -> worker = new Worker(@script) worker.on 'ready', @_run.bind(this) worker.process.on 'exit', (code, signal)=> if code isnt 0 # Code will be non-zero if process dies suddenly log.warn "Worker process #{worker.pid} died. Respawning..." for w, i in @workers if w is undefined or w.pid is worker.pid @workers.splice(i, 1) # Remove dead worker from pool. @fork() @workers.push(worker) enqueue: (task, timeout, callback)-> if not callback callback = timeout timeout = null @queue.push(task: task, callback: callback, timeout: timeout) process.nextTick(@_run.bind(this)) _run: (worker)-> log.debug 'RUNNING', @queue return if @queue.length is 0 unless worker # Find the first available worker. for w in @workers if w.status is Worker.READY worker = w break return @fork() if not worker and @options.autoexpand and @workers.length < @options.maxWorkers return unless worker queued = @queue.shift() callback = null if queued.timeout log.debug 'timeout', queued.timeout timeoutId = null callback = -> clearTimeout(timeoutId) queued.callback.apply(this, arguments) timeoutId = setTimeout => worker.process.kill('SIGINT') callback.call(this, @options.timeoutResult or {}) , queued.timeout else callback = queued.callback worker.send(queued.task, callback) module.exports = WorkQueue
true
'use strict' # # PI:NAME:<NAME>END_PI # 2015 # os = require 'os' Worker = require './worker' log = require './log' class WorkQueue constructor: (@script, @options = {})-> @workers = [] @queue = [] cpus = os.cpus().length @options.numWorkers ?= cpus @options.maxWorkers ?= cpus * 2 i = 0 log.debug "Starting #{@options.numWorkers} workers.." @fork() while i++ < @options.numWorkers fork: -> worker = new Worker(@script) worker.on 'ready', @_run.bind(this) worker.process.on 'exit', (code, signal)=> if code isnt 0 # Code will be non-zero if process dies suddenly log.warn "Worker process #{worker.pid} died. Respawning..." for w, i in @workers if w is undefined or w.pid is worker.pid @workers.splice(i, 1) # Remove dead worker from pool. @fork() @workers.push(worker) enqueue: (task, timeout, callback)-> if not callback callback = timeout timeout = null @queue.push(task: task, callback: callback, timeout: timeout) process.nextTick(@_run.bind(this)) _run: (worker)-> log.debug 'RUNNING', @queue return if @queue.length is 0 unless worker # Find the first available worker. for w in @workers if w.status is Worker.READY worker = w break return @fork() if not worker and @options.autoexpand and @workers.length < @options.maxWorkers return unless worker queued = @queue.shift() callback = null if queued.timeout log.debug 'timeout', queued.timeout timeoutId = null callback = -> clearTimeout(timeoutId) queued.callback.apply(this, arguments) timeoutId = setTimeout => worker.process.kill('SIGINT') callback.call(this, @options.timeoutResult or {}) , queued.timeout else callback = queued.callback worker.send(queued.task, callback) module.exports = WorkQueue
[ { "context": "erms of the MIT license.\nCopyright 2012 - 2015 (c) Markus Kohlhase <mail@markus-kohlhase.de>\n###\n\nxmpp = require \"no", "end": 109, "score": 0.9999015927314758, "start": 94, "tag": "NAME", "value": "Markus Kohlhase" }, { "context": "cense.\nCopyright 2012 - 2015 (c)...
node_modules/node-xmpp-serviceadmin/src/ServiceAdmin.coffee
DSSDevelopment/xenomia-launcher
0
### This program is distributed under the terms of the MIT license. Copyright 2012 - 2015 (c) Markus Kohlhase <mail@markus-kohlhase.de> ### xmpp = require "node-xmpp-core" NS = "http://jabber.org/protocol/admin" CMD_NS = "http://jabber.org/protocol/commands" JID = "accountjid" JIDS = "accountjids" EMAIL = "email" NAME = "given_name" SURNAME = "surname" PASS = "password" PASS_VERY = "password-verify" class ServiceAdmin constructor: (@jid, @comp, @service) -> runOneStageCmd: (cmd, fields, next=->) -> id = "exec#{(new Date).getTime()}" comp = @comp handler = (stanza) -> if stanza.is('iq') and stanza.attrs?.id is id if stanza.attrs.type is 'error' comp.removeListener "stanza", handler next new Error "could not execute command" else if stanza.attrs.type is 'result' switch (c = stanza.getChild "command").attrs?.status when "executing" ServiceAdmin.switchAddr stanza ServiceAdmin.fillForm stanza, fields comp.send stanza when 'completed' comp.removeListener "stanza", handler if (n = c.getChild "note")?.attrs?.type is "error" next new Error n.children?[0] else next undefined, c @comp.on 'stanza', handler cmdIq = ServiceAdmin.createCmdIq @jid, @service, id, cmd @comp.send cmdIq @createCmdIq: (from, to, id, cmd) -> iq = new xmpp.Stanza.Iq { type:'set', from, to, id } iq.c "command", xmlns: CMD_NS node: "#{NS}##{cmd}" action:'execute' iq @switchAddr: (stanza) -> me = stanza.attrs.to stanza.attrs.to = stanza.attrs.from stanza.attrs.from = me @fillForm: (stanza, fields) -> stanza.attrs.type = "set" c = stanza.getChild "command" delete c.attrs.status x = c.getChild "x" x.attrs.type = "submit" for xF in x.getChildren "field" if (val = fields[xF.attrs.var])? xF.remove("value") if xF.getChild("value")? if val instanceof Array xF.c("value").t(v).up() for v in val else xF.c("value").t val.toString() @getJID: (jid) -> if jid instanceof Array (ServiceAdmin.getJID x for x in jid) else if jid instanceof xmpp.JID jid else jid = new xmpp.JID(jid).bare().toString() addUser: (jid, pw, prop={}, next) -> data = {} data[JID] = ServiceAdmin.getJID jid data[PASS] = pw data[PASS_VERY] = pw data[EMAIL] = prop.email if prop.email data[NAME] = prop.name if prop.name data[SURNAME] = prop.surname if prop.surname @runOneStageCmd "add-user", data, next deleteUser: (jid, next) -> data = {} data[JIDS] = ServiceAdmin.getJID jid @runOneStageCmd "delete-user", data, next disableUser: (jid, next) -> data = {} data[JIDS] = ServiceAdmin.getJID jid @runOneStageCmd "disable-user", data, next changeUserPassword: (jid, pw, next) -> data = {} data[JID] = ServiceAdmin.getJID jid data[PASS] = pw @runOneStageCmd "change-user-password", data, next getUserPassword: (jid, next) -> data = {} data[JID] = ServiceAdmin.getJID jid @runOneStageCmd "get-user-password", data, (err, c) -> return next err if err next undefined, c.getChildByAttr("var", "password", null, true)?. getChild("value")?. getText() endUserSession: (jids, next) -> data = {} data[JIDS] = ServiceAdmin.getJID jids @runOneStageCmd "end-user-session", data, next module.exports = ServiceAdmin
122863
### This program is distributed under the terms of the MIT license. Copyright 2012 - 2015 (c) <NAME> <<EMAIL>> ### xmpp = require "node-xmpp-core" NS = "http://jabber.org/protocol/admin" CMD_NS = "http://jabber.org/protocol/commands" JID = "accountjid" JIDS = "accountjids" EMAIL = "email" NAME = "given_name" SURNAME = "surname" PASS = "<PASSWORD>" PASS_VERY = "<PASSWORD>" class ServiceAdmin constructor: (@jid, @comp, @service) -> runOneStageCmd: (cmd, fields, next=->) -> id = "exec#{(new Date).getTime()}" comp = @comp handler = (stanza) -> if stanza.is('iq') and stanza.attrs?.id is id if stanza.attrs.type is 'error' comp.removeListener "stanza", handler next new Error "could not execute command" else if stanza.attrs.type is 'result' switch (c = stanza.getChild "command").attrs?.status when "executing" ServiceAdmin.switchAddr stanza ServiceAdmin.fillForm stanza, fields comp.send stanza when 'completed' comp.removeListener "stanza", handler if (n = c.getChild "note")?.attrs?.type is "error" next new Error n.children?[0] else next undefined, c @comp.on 'stanza', handler cmdIq = ServiceAdmin.createCmdIq @jid, @service, id, cmd @comp.send cmdIq @createCmdIq: (from, to, id, cmd) -> iq = new xmpp.Stanza.Iq { type:'set', from, to, id } iq.c "command", xmlns: CMD_NS node: "#{NS}##{cmd}" action:'execute' iq @switchAddr: (stanza) -> me = stanza.attrs.to stanza.attrs.to = stanza.attrs.from stanza.attrs.from = me @fillForm: (stanza, fields) -> stanza.attrs.type = "set" c = stanza.getChild "command" delete c.attrs.status x = c.getChild "x" x.attrs.type = "submit" for xF in x.getChildren "field" if (val = fields[xF.attrs.var])? xF.remove("value") if xF.getChild("value")? if val instanceof Array xF.c("value").t(v).up() for v in val else xF.c("value").t val.toString() @getJID: (jid) -> if jid instanceof Array (ServiceAdmin.getJID x for x in jid) else if jid instanceof xmpp.JID jid else jid = new xmpp.JID(jid).bare().toString() addUser: (jid, pw, prop={}, next) -> data = {} data[JID] = ServiceAdmin.getJID jid data[PASS] = <PASSWORD> data[PASS_VERY] = pw data[EMAIL] = prop.email if prop.email data[NAME] = prop.name if prop.name data[SURNAME] = prop.surname if prop.surname @runOneStageCmd "add-user", data, next deleteUser: (jid, next) -> data = {} data[JIDS] = ServiceAdmin.getJID jid @runOneStageCmd "delete-user", data, next disableUser: (jid, next) -> data = {} data[JIDS] = ServiceAdmin.getJID jid @runOneStageCmd "disable-user", data, next changeUserPassword: (jid, pw, next) -> data = {} data[JID] = ServiceAdmin.getJID jid data[PASS] = <PASSWORD> @runOneStageCmd "change-user-password", data, next getUserPassword: (jid, next) -> data = {} data[JID] = ServiceAdmin.getJID jid @runOneStageCmd "get-user-password", data, (err, c) -> return next err if err next undefined, c.getChildByAttr("var", "password", null, true)?. getChild("value")?. getText() endUserSession: (jids, next) -> data = {} data[JIDS] = ServiceAdmin.getJID jids @runOneStageCmd "end-user-session", data, next module.exports = ServiceAdmin
true
### This program is distributed under the terms of the MIT license. Copyright 2012 - 2015 (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### xmpp = require "node-xmpp-core" NS = "http://jabber.org/protocol/admin" CMD_NS = "http://jabber.org/protocol/commands" JID = "accountjid" JIDS = "accountjids" EMAIL = "email" NAME = "given_name" SURNAME = "surname" PASS = "PI:PASSWORD:<PASSWORD>END_PI" PASS_VERY = "PI:PASSWORD:<PASSWORD>END_PI" class ServiceAdmin constructor: (@jid, @comp, @service) -> runOneStageCmd: (cmd, fields, next=->) -> id = "exec#{(new Date).getTime()}" comp = @comp handler = (stanza) -> if stanza.is('iq') and stanza.attrs?.id is id if stanza.attrs.type is 'error' comp.removeListener "stanza", handler next new Error "could not execute command" else if stanza.attrs.type is 'result' switch (c = stanza.getChild "command").attrs?.status when "executing" ServiceAdmin.switchAddr stanza ServiceAdmin.fillForm stanza, fields comp.send stanza when 'completed' comp.removeListener "stanza", handler if (n = c.getChild "note")?.attrs?.type is "error" next new Error n.children?[0] else next undefined, c @comp.on 'stanza', handler cmdIq = ServiceAdmin.createCmdIq @jid, @service, id, cmd @comp.send cmdIq @createCmdIq: (from, to, id, cmd) -> iq = new xmpp.Stanza.Iq { type:'set', from, to, id } iq.c "command", xmlns: CMD_NS node: "#{NS}##{cmd}" action:'execute' iq @switchAddr: (stanza) -> me = stanza.attrs.to stanza.attrs.to = stanza.attrs.from stanza.attrs.from = me @fillForm: (stanza, fields) -> stanza.attrs.type = "set" c = stanza.getChild "command" delete c.attrs.status x = c.getChild "x" x.attrs.type = "submit" for xF in x.getChildren "field" if (val = fields[xF.attrs.var])? xF.remove("value") if xF.getChild("value")? if val instanceof Array xF.c("value").t(v).up() for v in val else xF.c("value").t val.toString() @getJID: (jid) -> if jid instanceof Array (ServiceAdmin.getJID x for x in jid) else if jid instanceof xmpp.JID jid else jid = new xmpp.JID(jid).bare().toString() addUser: (jid, pw, prop={}, next) -> data = {} data[JID] = ServiceAdmin.getJID jid data[PASS] = PI:PASSWORD:<PASSWORD>END_PI data[PASS_VERY] = pw data[EMAIL] = prop.email if prop.email data[NAME] = prop.name if prop.name data[SURNAME] = prop.surname if prop.surname @runOneStageCmd "add-user", data, next deleteUser: (jid, next) -> data = {} data[JIDS] = ServiceAdmin.getJID jid @runOneStageCmd "delete-user", data, next disableUser: (jid, next) -> data = {} data[JIDS] = ServiceAdmin.getJID jid @runOneStageCmd "disable-user", data, next changeUserPassword: (jid, pw, next) -> data = {} data[JID] = ServiceAdmin.getJID jid data[PASS] = PI:PASSWORD:<PASSWORD>END_PI @runOneStageCmd "change-user-password", data, next getUserPassword: (jid, next) -> data = {} data[JID] = ServiceAdmin.getJID jid @runOneStageCmd "get-user-password", data, (err, c) -> return next err if err next undefined, c.getChildByAttr("var", "password", null, true)?. getChild("value")?. getText() endUserSession: (jids, next) -> data = {} data[JIDS] = ServiceAdmin.getJID jids @runOneStageCmd "end-user-session", data, next module.exports = ServiceAdmin
[ { "context": "v class=\"form-group\">\n <label for=\"username\">Username</label>\n <input type=\"te", "end": 943, "score": 0.9972410202026367, "start": 935, "tag": "USERNAME", "value": "username" }, { "context": "orm-group\">\n <label for=...
ModelCatalogueCorePlugin/grails-app/assets/javascripts/modelcatalogue/core/ui/bs/modalPromptLogin.coffee
OxBRCInformatics/NHICModelCatalogue
1
angular.module('mc.core.ui.bs.modalPromptLogin', ['mc.util.messages', 'ngCookies']).config ['messagesProvider', (messagesProvider)-> factory = [ '$modal', 'messages', 'security', ($modal, messages, security) -> -> dialog = $modal.open { windowClass: 'login-modal-prompt' template: ''' <div class="modal-header"> <h4>Login</h4> </div> <div class="modal-body"> <messages-panel messages="messages"></messages-panel> <div ng-if="providers &amp;&amp; contextPath"> <a ng-repeat="provider in providers" ng-click="loginExternal(provider)" class="btn btn-primary btn-block"><span class="fa fa-fw" ng-class="'fa-' + provider"></span> Login with {{names.getNaturalName(provider)}}</a> <hr/> </div> <form role="form" ng-submit="login()"> <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" placeholder="Username" ng-model="user.username"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="password" placeholder="Password" ng-model="user.password"> </div> <div class="checkbox"> <label> <input type="checkbox" ng-model="user.rememberMe"> Remember Me </label> </div> <button type="submit" class="hide" ng-click="login()"></button> </form> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success" ng-click="login()" ng-disabled="!user.username || !user.password"><span class="glyphicon glyphicon-ok"></span> Login</button> <button class="btn btn-warning" ng-click="$dismiss()">Cancel</button> </div> ''' controller: ['$scope', '$cookies', 'messages', 'security', '$modalInstance', 'names', '$window', '$interval', '$rootScope', ($scope, $cookies, messages, security, $modalInstance, names, $window, $interval, $rootScope) -> $scope.user = {rememberMe: $cookies.mc_remember_me == "true"} $scope.messages = messages.createNewMessages() $scope.providers = security.oauthProviders $scope.names = names $scope.contextPath = security.contextPath $scope.forgotPasswordLink = "#{security.contextPath}/register/forgotPassword" $scope.canResetPassword = security.canResetPassword $scope.login = -> security.login($scope.user.username, $scope.user.password, $scope.user.rememberMe).then (success)-> if success.data.error $scope.messages.clearAllMessages() # removes all current displayed error messages $scope.messages.error success.data.error else if success.data.errors $scope.messages.clearAllMessages() # removes all current displayed error messages for error in success.data.errors $scope.messages.error error else $cookies.mc_remember_me = $scope.user.rememberMe $modalInstance.close success $scope.loginExternal = (provider) -> url = security.contextPath + '/oauth/' + provider + '/authenticate' externalLoginWindow = $window.open(url, 'mc_external_login', 'menubar=no,status=no,titlebar=no,toolbar=no') helperPromise = null closeWindowWhenLoggedIn = -> if externalLoginWindow.closed $modalInstance.dismiss() $interval.cancel(helperPromise) $modalInstance.dismiss() return try # mute cross origin errors when redirected login page if $window.location.host is externalLoginWindow.location.host and (externalLoginWindow.location.pathname == security.contextPath or externalLoginWindow.location.pathname == "#{security.contextPath}/") $interval.cancel(helperPromise) externalLoginWindow.close() security.requireUser().then (success)-> $rootScope.$broadcast 'userLoggedIn', success $modalInstance.close success helperPromise = $interval closeWindowWhenLoggedIn, 100 ] } dialog.result ] messagesProvider.setPromptFactory 'login', factory ]
203052
angular.module('mc.core.ui.bs.modalPromptLogin', ['mc.util.messages', 'ngCookies']).config ['messagesProvider', (messagesProvider)-> factory = [ '$modal', 'messages', 'security', ($modal, messages, security) -> -> dialog = $modal.open { windowClass: 'login-modal-prompt' template: ''' <div class="modal-header"> <h4>Login</h4> </div> <div class="modal-body"> <messages-panel messages="messages"></messages-panel> <div ng-if="providers &amp;&amp; contextPath"> <a ng-repeat="provider in providers" ng-click="loginExternal(provider)" class="btn btn-primary btn-block"><span class="fa fa-fw" ng-class="'fa-' + provider"></span> Login with {{names.getNaturalName(provider)}}</a> <hr/> </div> <form role="form" ng-submit="login()"> <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" placeholder="Username" ng-model="user.username"> </div> <div class="form-group"> <label for="<PASSWORD>"><PASSWORD></label> <input type="<PASSWORD>" class="form-control" id="password" placeholder="<PASSWORD>" ng-model="user.password"> </div> <div class="checkbox"> <label> <input type="checkbox" ng-model="user.rememberMe"> Remember Me </label> </div> <button type="submit" class="hide" ng-click="login()"></button> </form> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success" ng-click="login()" ng-disabled="!user.username || !user.password"><span class="glyphicon glyphicon-ok"></span> Login</button> <button class="btn btn-warning" ng-click="$dismiss()">Cancel</button> </div> ''' controller: ['$scope', '$cookies', 'messages', 'security', '$modalInstance', 'names', '$window', '$interval', '$rootScope', ($scope, $cookies, messages, security, $modalInstance, names, $window, $interval, $rootScope) -> $scope.user = {rememberMe: $cookies.mc_remember_me == "true"} $scope.messages = messages.createNewMessages() $scope.providers = security.oauthProviders $scope.names = names $scope.contextPath = security.contextPath $scope.forgotPasswordLink = "#{security.contextPath}/register/forgotPassword" $scope.canResetPassword = security.canResetPassword $scope.login = -> security.login($scope.user.username, $scope.user.password, $scope.user.rememberMe).then (success)-> if success.data.error $scope.messages.clearAllMessages() # removes all current displayed error messages $scope.messages.error success.data.error else if success.data.errors $scope.messages.clearAllMessages() # removes all current displayed error messages for error in success.data.errors $scope.messages.error error else $cookies.mc_remember_me = $scope.user.rememberMe $modalInstance.close success $scope.loginExternal = (provider) -> url = security.contextPath + '/oauth/' + provider + '/authenticate' externalLoginWindow = $window.open(url, 'mc_external_login', 'menubar=no,status=no,titlebar=no,toolbar=no') helperPromise = null closeWindowWhenLoggedIn = -> if externalLoginWindow.closed $modalInstance.dismiss() $interval.cancel(helperPromise) $modalInstance.dismiss() return try # mute cross origin errors when redirected login page if $window.location.host is externalLoginWindow.location.host and (externalLoginWindow.location.pathname == security.contextPath or externalLoginWindow.location.pathname == "#{security.contextPath}/") $interval.cancel(helperPromise) externalLoginWindow.close() security.requireUser().then (success)-> $rootScope.$broadcast 'userLoggedIn', success $modalInstance.close success helperPromise = $interval closeWindowWhenLoggedIn, 100 ] } dialog.result ] messagesProvider.setPromptFactory 'login', factory ]
true
angular.module('mc.core.ui.bs.modalPromptLogin', ['mc.util.messages', 'ngCookies']).config ['messagesProvider', (messagesProvider)-> factory = [ '$modal', 'messages', 'security', ($modal, messages, security) -> -> dialog = $modal.open { windowClass: 'login-modal-prompt' template: ''' <div class="modal-header"> <h4>Login</h4> </div> <div class="modal-body"> <messages-panel messages="messages"></messages-panel> <div ng-if="providers &amp;&amp; contextPath"> <a ng-repeat="provider in providers" ng-click="loginExternal(provider)" class="btn btn-primary btn-block"><span class="fa fa-fw" ng-class="'fa-' + provider"></span> Login with {{names.getNaturalName(provider)}}</a> <hr/> </div> <form role="form" ng-submit="login()"> <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" placeholder="Username" ng-model="user.username"> </div> <div class="form-group"> <label for="PI:PASSWORD:<PASSWORD>END_PI">PI:PASSWORD:<PASSWORD>END_PI</label> <input type="PI:PASSWORD:<PASSWORD>END_PI" class="form-control" id="password" placeholder="PI:PASSWORD:<PASSWORD>END_PI" ng-model="user.password"> </div> <div class="checkbox"> <label> <input type="checkbox" ng-model="user.rememberMe"> Remember Me </label> </div> <button type="submit" class="hide" ng-click="login()"></button> </form> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success" ng-click="login()" ng-disabled="!user.username || !user.password"><span class="glyphicon glyphicon-ok"></span> Login</button> <button class="btn btn-warning" ng-click="$dismiss()">Cancel</button> </div> ''' controller: ['$scope', '$cookies', 'messages', 'security', '$modalInstance', 'names', '$window', '$interval', '$rootScope', ($scope, $cookies, messages, security, $modalInstance, names, $window, $interval, $rootScope) -> $scope.user = {rememberMe: $cookies.mc_remember_me == "true"} $scope.messages = messages.createNewMessages() $scope.providers = security.oauthProviders $scope.names = names $scope.contextPath = security.contextPath $scope.forgotPasswordLink = "#{security.contextPath}/register/forgotPassword" $scope.canResetPassword = security.canResetPassword $scope.login = -> security.login($scope.user.username, $scope.user.password, $scope.user.rememberMe).then (success)-> if success.data.error $scope.messages.clearAllMessages() # removes all current displayed error messages $scope.messages.error success.data.error else if success.data.errors $scope.messages.clearAllMessages() # removes all current displayed error messages for error in success.data.errors $scope.messages.error error else $cookies.mc_remember_me = $scope.user.rememberMe $modalInstance.close success $scope.loginExternal = (provider) -> url = security.contextPath + '/oauth/' + provider + '/authenticate' externalLoginWindow = $window.open(url, 'mc_external_login', 'menubar=no,status=no,titlebar=no,toolbar=no') helperPromise = null closeWindowWhenLoggedIn = -> if externalLoginWindow.closed $modalInstance.dismiss() $interval.cancel(helperPromise) $modalInstance.dismiss() return try # mute cross origin errors when redirected login page if $window.location.host is externalLoginWindow.location.host and (externalLoginWindow.location.pathname == security.contextPath or externalLoginWindow.location.pathname == "#{security.contextPath}/") $interval.cancel(helperPromise) externalLoginWindow.close() security.requireUser().then (success)-> $rootScope.$broadcast 'userLoggedIn', success $modalInstance.close success helperPromise = $interval closeWindowWhenLoggedIn, 100 ] } dialog.result ] messagesProvider.setPromptFactory 'login', factory ]
[ { "context": "###\n mixin-js.js 0.1.5\n (c) 2011, 2012 Kevin Malakoff - http://kmalakoff.github.com/mixin/\n License: M", "end": 55, "score": 0.9997409582138062, "start": 41, "tag": "NAME", "value": "Kevin Malakoff" }, { "context": "js 0.1.5\n (c) 2011, 2012 Kevin Malakoff - http...
src/mixin-core.coffee
kmalakoff/mixin
14
### mixin-js.js 0.1.5 (c) 2011, 2012 Kevin Malakoff - http://kmalakoff.github.com/mixin/ License: MIT (http://www.opensource.org/licenses/mit-license.php) Note: some code from Underscore.js is embedded in this file to remove dependencies on the full library. Please see the following for details on Underscore.js and its licensing: https://github.com/documentcloud/underscore https://github.com/documentcloud/underscore/blob/master/LICENSE ### # export or create Mixin namespace Mixin = @Mixin = if (typeof(exports) != 'undefined') then exports else {} Mixin.Core||Mixin.Core={} Mixin.VERSION = '0.1.5' #Mixin.DEBUG=true # define DEBUG before this file to enable rigorous checks #################################################### # Remove dependency on underscore, but inline minimally needed #################################################### # import Underscore (or Lo-Dash with precedence) _ = @_ if not _ and (typeof(require) isnt 'undefined') try _ = require('lodash') catch e then (try _ = require('underscore') catch e then {}) _ = _._ if _ and (_.hasOwnProperty('_')) # LEGACY _ = {} unless _ Mixin._ = _ # publish if needed and not including the full underscore library (_.isArray = (obj) -> return Object.prototype.toString.call(obj) == '[object Array]') unless _.isArray (_.isString = (obj) -> return !!(obj == '' || (obj && obj.charCodeAt && obj.substr))) unless _.isString (_.isFunction = (obj) -> return !!(obj && obj.constructor && obj.call && obj.apply)) unless _.isFunction (_.isEmpty = (obj) -> return (obj.length==0) if (_.isArray(obj) || _.isString(obj)); return false for key, value of obj; return true) unless _.isEmpty (_.classOf = (obj) -> return undefined if not (obj instanceof Object); return obj.prototype.constructor.name if (obj.prototype and obj.prototype.constructor and obj.prototype.constructor.name); return obj.constructor.name if (obj.constructor and obj.constructor.name); return undefined) unless _.classOf (_.size = (obj) -> i=0; i++ for key of obj; return i) unless _.size (_.find = (obj, iter) -> (return item if iter(item)) for item in obj; return null) unless _.find (_.remove = (array, item) -> index = array.indexOf(item); return if index<0; array.splice(index, 1); return item) unless _.remove (_.keypathExists = (object, keypath) -> return !!_.keypathValueOwner(object, keypath)) unless _.keypathExists (_.keypathValueOwner = (object, keypath) -> (components = if _.isString(keypath) then keypath.split('.') else keypath); ((if(i==components.length-1) then (if object.hasOwnProperty(key) then return object else return) else (return unless object.hasOwnProperty(key); object = object[key])) for key, i in components); return) unless _.keypathValueOwner (_.keypath = (object, keypath, value) -> components = keypath.split('.'); object = _.keypathValueOwner(object, components); return unless object; if(arguments.length==3) then (object[components[components.length-1]] = value; return value) else return object[components[components.length-1]]) unless _.keypath #################################################### # Validation Helpers to check parameters and throw Errors if invalid. # Use these when Mixin.DEBUG mode is true. #################################################### class Mixin.Core._Validate @mixinInfo: (mixin_info, overwrite, mixin_and_function) -> throw new Error("#{mixin_and_function}: mixin_info missing") if not mixin_info _Validate.string(mixin_info.mixin_name, mixin_and_function, 'mixin_name') throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' already registered") if not overwrite and Mixin.Core._Manager.available_mixins.hasOwnProperty(mixin_info.mixin_name) throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' missing mixin_object") if not mixin_info.mixin_object throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' mixin_object is invalid") if not (mixin_info.mixin_object instanceof Object) throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' initialize function is invalid") if mixin_info.initialize and not _.isFunction(mixin_info.initialize) throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' destroy function is invalid") if mixin_info.destroy and not _.isFunction(mixin_info.destroy) @instanceAndMixinName: (mix_target, mixin_name, mixin_and_function) -> throw new Error("#{mixin_and_function}: mix_target missing") if not mix_target _Validate.string(mixin_name, mixin_and_function, 'mixin_name') _Validate.instanceOrArray(mix_target, mixin_and_function, 'mix_target', mixin_name) @classConstructorAndMixinName: (constructor, mixin_name, mixin_and_function) -> throw new Error("#{mixin_and_function}: class constructor missing") if not constructor _Validate.string(mixin_name, mixin_and_function, 'mixin_name') throw new Error("#{mixin_and_function}: class constructor invalid for '#{mixin_name}'") if not _.isFunction(constructor) @exists: (parameter, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if parameter == undefined @object: (obj, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if obj == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if (typeof(obj)!='object') or _.isArray(obj) @uint: (uint, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if uint == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if not (typeof(uint) != 'number') or (uint<0) or (Math.floor(uint)!=uint) @string: (string, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if string == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if not _.isString(string) @stringArrayOrNestedStringArray: (array, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if array == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if not _.isArray(array) (throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if _.isArray(item) and (not item.length or not _.isString(item[0])) or not _.isString(item)) for item in string_or_array return @callback: (callback, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if callback == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if not _.isFunction(callback) @instance: (obj, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if obj == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if (typeof(obj)!='object' or _.isArray(obj)) or not _.isFunction(obj.constructor) or (obj.constructor.name=='Object') @instanceOrArray: (obj, mixin_and_function, parameter_name, mixin_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if obj == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if (typeof(obj)!='object') or not _.isFunction(obj.constructor) or (obj.constructor.name=='Object') or _.isArray(obj) @instanceWithMixin: (obj, mixin_name, mixin_and_function, parameter_name) -> _Validate.instance(obj, mixin_and_function, parameter_name) throw new Error("#{mixin_and_function}: #{parameter_name} missing mixin '#{mixin_name}' on #{_.classOf(obj)}") if not Mixin.hasMixin(obj, mixin_name) @noKey: (obj, key, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{key} already exists for #{parameter_name}") if obj.hasOwnProperty(key) @hasKey: (obj, key, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{key} does not exist for #{parameter_name}") if not obj.hasOwnProperty(key) #################################################### # Stored in the Mixin.Core._ClassRecord in the constructors of the mixed in classes #################################################### class Mixin.Core._InstanceRecord constructor: (@mix_target) -> @initialized_mixins = {} # stores hash of data per mixin destroy: -> throw new Error('Mixin: non-empty instance record being destroyed') if not _.isEmpty(@initialized_mixins) @mix_target = null hasMixin: (mixin_name, mark_as_mixed) -> has_mixin = @initialized_mixins.hasOwnProperty(mixin_name) return has_mixin if has_mixin or not mark_as_mixed @initialized_mixins[mixin_name] = {is_destroyed: false} return true collectMixins: (mixins) -> mixins.push(key) for key, mixin_info of @initialized_mixins return initializeMixin: (mixin_info, args) -> # initialize @initialized_mixins[mixin_info.mixin_name] = {is_destroyed: false, destroy: mixin_info.destroy} mixin_info.initialize.apply(@mix_target, args) if mixin_info.initialize destroyMixin: (mixin_name) -> if mixin_name return false if not @initialized_mixins.hasOwnProperty(mixin_name) return @_destroyMixinInfo(mixin_name) else mixin_existed = false (mixin_existed=true; @_destroyMixinInfo(key)) for key, value of @initialized_mixins return mixin_existed _destroyMixinInfo: (mixin_name) -> mixin_info = @initialized_mixins[mixin_name] return true if (mixin_info.is_destroyed) # already destroyed (for example, both manual and event-based auto destroy) mixin_info.is_destroyed = true # call mixin destroy function (mixin_info.destroy.apply(@mix_target); mixin_info.destroy = null) if mixin_info.destroy # cleanup any stored data and instance data Mixin.Core._Manager._destroyInstanceData(@mix_target, mixin_name) delete @initialized_mixins[mixin_name] return true #################################################### # Stored in the constructors of the mixed in classes #################################################### class Mixin.Core._ClassRecord constructor: (@constructor) -> @mixins = {} @instance_records = [] # mixin_info # force - in other words, over-write existing functions and properties (if they exist) mixIntoClass: (mix_target, mixin_info) -> return if @mixins.hasOwnProperty(mixin_info.mixin_name) # already mixed into the class @mixins[mixin_info.mixin_name] = mixin_info # check for property clashes before mixing in if not mixin_info.force (throw new Error("Mixin: property '#{key}' clashes with existing property on '#{_.classOf(mix_target)}") if (key of mix_target)) for key, value of mixin_info.mixin_object # now, add the mixin methods and possibly data (mix_target.constructor.prototype extends mixin_info.mixin_object) classHasMixin: (mixin_name) -> return @mixins.hasOwnProperty(mixin_name) instanceHasMixin: (mix_target, mixin_name, mark_as_mixed) -> instance_record = @_getInstanceRecord(mix_target) # You're telling me if mark_as_mixed @mixins[mixin_name] = Mixin.Core._Manager._getMixinInfo(mixin_name) if not @mixins.hasOwnProperty(mixin_name) (instance_record = new Mixin.Core._InstanceRecord(mix_target); @instance_records.push(instance_record)) if not instance_record return instance_record.hasMixin(mixin_name, mark_as_mixed) # I'm telling you else return if instance_record then instance_record.hasMixin(mixin_name) else false collectMixinsForInstance: (mixins, mix_target) -> instance_record = @_getInstanceRecord(mix_target) return if not instance_record instance_record.collectMixins(mixins) initializeInstance: (mix_target, mixin_info, args) -> instance_record = @_getInstanceRecord(mix_target) (instance_record.initializeMixin(mixin_info, args); return) if instance_record instance_record = new Mixin.Core._InstanceRecord(mix_target); @instance_records.push(instance_record) instance_record.initializeMixin(mixin_info, args) destroyInstance: (mix_target, mixin_name) -> return false if mixin_name and not @mixins.hasOwnProperty(mixin_name) mixin_existed = false i=@instance_records.length-1 while (i>=0) instance_record = @instance_records[i] if (instance_record.mix_target==mix_target) and instance_record.destroyMixin(mixin_name) mixin_existed = true (instance_record.destroy(); @instance_records.splice(i, 1)) if _.isEmpty(instance_record.initialized_mixins) return true if mixin_name i-- return mixin_existed _getInstanceRecord: (mix_target) -> (return instance_record if (instance_record.mix_target == mix_target)) for instance_record in @instance_records return undefined #################################################### # mixin_info: # mixin_name # initialize # destroy # force # suppress_destroy_event # mixin_object class Mixin.Core._Manager @available_mixins = {} #################################################### # Mixin Management Methods #################################################### # mixin_info properties # mixin_name - string (required) # mixin_object - object with properties to mixin (required) # initialize - function called on each instance when Mixin.in is called # destroy - function called on each instance when Mixin.out is called # Note: initialize and destroy are called with the mixin bound to 'this'. @registerMixin: (mixin_info, overwrite) -> Mixin.Core._Validate.mixinInfo(mixin_info, overwrite, 'Mixin.registerMixin') if Mixin.DEBUG _Manager.available_mixins[mixin_info.mixin_name] = mixin_info return true @isAvailable: (mixin_name) -> return _Manager.available_mixins.hasOwnProperty(mixin_name) @_getMixinInfo: (mixin_name) -> return _Manager.available_mixins[mixin_name] #################################################### # Mix Target Methods #################################################### # accepts: # in(mix_target, 'SomeMixin') # in(mix_target, 'SomeMixin', 'AnotherMixin', etc) # in(mix_target, 'SomeMixin', ['AMixinWithParameters', param1, param2, etc], etc) @mixin: (mix_target) -> _doMixin = (mix_target, mixin_name, params) => if Mixin.DEBUG Mixin.Core._Validate.instanceAndMixinName(mix_target, mixin_name, 'Mixin.mixin', 'mix_target') throw new Error("Mixin.mixin: '#{mixin_name}' not found") if not @isAvailable(mixin_name) mixin_info = _Manager.available_mixins[mixin_name] throw new Error("Mixin.mixin: '#{mixin_name}' not found") if not mixin_info # already mixed in return if @hasMixin(mix_target, mixin_info.mixin_name) # already initialized # initialize instance (if needed) class_record = _Manager._findOrCreateClassRecord(mix_target, mixin_info) class_record.mixIntoClass(mix_target, mixin_info) class_record.initializeInstance(mix_target, mixin_info, Array.prototype.slice.call(arguments, 2)) # check for infering parameters args = Array.prototype.slice.call(arguments, 1) throw new Error("Mixin: mixin_name missing") if not args.length if (args.length>1) check_arg = args[1] # the next parameter after the first mixin is not a mixin if not ((_.isString(check_arg) and _Manager.isAvailable(check_arg)) or (_.isArray(check_arg) and (check_arg.length>=1) and _.isString(check_arg[0]) and _Manager.isAvailable(check_arg[0]))) _doMixin.apply(this, arguments) return mix_target (if _.isArray(parameter) then _doMixin.apply(this, [mix_target].concat(parameter)) else _doMixin(mix_target, parameter)) for parameter in args return mix_target @mixout: (mix_target, mixin_name_or_names) -> if Mixin.DEBUG Mixin.Core._Validate.instance(mix_target, 'Mixin.mixout', 'mix_target') _doMixout = (mix_target, mixin_name) => if Mixin.DEBUG Mixin.Core._Validate.string(mixin_name, 'Mixin.mixout', 'mixin_name') if mix_target.constructor._mixin_class_records (return mix_target if class_record.destroyInstance(mix_target, mixin_name)) for class_record in mix_target.constructor._mixin_class_records return mix_target # process one or an array if arguments.length>1 _doMixout(mix_target, parameter) for parameter in Array.prototype.slice.call(arguments, 1) # clear all mixins else if mix_target.constructor._mixin_class_records (return mix_target if class_record.destroyInstance(mix_target)) for class_record in mix_target.constructor._mixin_class_records return mix_target @hasMixin: (mix_target, mixin_name, mark_as_mixed) -> # You're telling me if mark_as_mixed return true if _Manager.hasMixin(mix_target, mixin_name) # already mixed in mixin_info = _Manager.available_mixins[mixin_name] return false if not mixin_info class_record = _Manager._findOrCreateClassRecord(mix_target, mixin_info) class_record.instanceHasMixin(mix_target, mixin_name, mark_as_mixed) # I'm telling you else Mixin.Core._Validate.instanceAndMixinName(mix_target, mixin_name, 'Mixin.hasMixin', 'mix_target') if Mixin.DEBUG return true if _Manager.hasInstanceData(mix_target, mixin_name) # shortcut class_record = _Manager._findClassRecord(mix_target, mixin_name) return false if not class_record return class_record.instanceHasMixin(mix_target, mixin_name) @mixins: (mix_target) -> Mixin.Core._Validate.instance(mix_target, mixins, 'Mixin.mixins', 'mix_target') if Mixin.DEBUG mixins = [] if mix_target.constructor._mixin_class_records class_record.collectMixinsForInstance(mixins, mix_target) for class_record in mix_target.constructor._mixin_class_records return mixins @_getClassRecords: (mix_target) -> class_records = [] constructor = mix_target.constructor while (constructor) if constructor._mixin_class_records (class_records.push(class_record) if (mix_target instanceof class_record.constructor)) for class_record in constructor._mixin_class_records constructor = if (constructor.__super__ and (constructor.__super__.constructor!=constructor)) then constructor.__super__.constructor else undefined return class_records @_findClassRecord: (mix_target, mixin_name) -> class_records = @_getClassRecords(mix_target) (return class_record if class_record.classHasMixin(mixin_name)) for class_record in class_records return undefined @_findOrCreateClassRecord: (mix_target, mixin_info) -> # look for an existing class record class_record = _Manager._findClassRecord(mix_target, mixin_info.mixin_name) return class_record if class_record # not already mixed at this level class_record = _.find(mix_target.constructor._mixin_class_records, (test)-> return test.constructor==mix_target.constructor) if (mix_target.constructor._mixin_class_records) if not class_record class_record = new Mixin.Core._ClassRecord(mix_target.constructor) if mix_target.constructor._mixin_class_records was_added = false # put it before its super class i=0; l=mix_target.constructor._mixin_class_records.length while (i<l) other_class_record = mix_target.constructor._mixin_class_records[i] if (mix_target instanceof other_class_record.constructor) mix_target.constructor._mixin_class_records.splice(i, 0, class_record); was_added = true break; i++ mix_target.constructor._mixin_class_records.push(class_record) if not was_added else mix_target.constructor._mixin_class_records = [class_record] Mixin._statistics.addClassRecord(class_record) if Mixin._statistics return class_record #################################################### # Mix Target Instance Data Methods #################################################### @hasInstanceData: (mix_target, mixin_name) -> Mixin.Core._Validate.instanceAndMixinName(mix_target, mixin_name, 'Mixin.hasInstanceData', 'mix_target') if Mixin.DEBUG return !!(mix_target._mixin_data and mix_target._mixin_data.hasOwnProperty(mixin_name)) @instanceData: (mix_target, mixin_name, data) -> if Mixin.DEBUG Mixin.Core._Validate.instanceAndMixinName(mix_target, mixin_name, 'Mixin.instanceData', 'mix_target') if (data==undefined) throw new Error("Mixin.instanceData: no instance data on '#{_.classOf(mix_target)}'") if not ('_mixin_data' of mix_target) throw new Error("Mixin.instanceData: mixin '#{mixin_name}' instance data not found on '#{_.classOf(mix_target)}'") if not mix_target._mixin_data.hasOwnProperty(mixin_name) else throw new Error("Mixin.instanceData: mixin '#{mixin_name}' not mixed into '#{_.classOf(mix_target)}'") if not _Manager.hasMixin(mix_target, mixin_name) # set if not (data==undefined) mix_target._mixin_data = {} if not mix_target._mixin_data mix_target._mixin_data[mixin_name] = data return mix_target._mixin_data[mixin_name] @_destroyInstanceData: (mix_target, mixin_name) -> return undefined if not mix_target._mixin_data data = mix_target._mixin_data[mixin_name] delete mix_target._mixin_data[mixin_name] delete mix_target['_mixin_data'] if _.isEmpty(mix_target._mixin_data) # create the manager and expose public interface in Mixin namespace Mixin.registerMixin = Mixin.Core._Manager.registerMixin Mixin.isAvailable = Mixin.Core._Manager.isAvailable Mixin.mixin = Mixin.in = Mixin.Core._Manager.mixin Mixin.mixout = Mixin.out = Mixin.Core._Manager.mixout Mixin.hasMixin = Mixin.exists = Mixin.Core._Manager.hasMixin Mixin.mixins = Mixin.Core._Manager.mixins Mixin.hasInstanceData = Mixin.hasID = Mixin.Core._Manager.hasInstanceData Mixin.instanceData = Mixin.iD = Mixin.Core._Manager.instanceData exports.Mixin = Mixin if (typeof(exports) != 'undefined')
152076
### mixin-js.js 0.1.5 (c) 2011, 2012 <NAME> - http://kmalakoff.github.com/mixin/ License: MIT (http://www.opensource.org/licenses/mit-license.php) Note: some code from Underscore.js is embedded in this file to remove dependencies on the full library. Please see the following for details on Underscore.js and its licensing: https://github.com/documentcloud/underscore https://github.com/documentcloud/underscore/blob/master/LICENSE ### # export or create Mixin namespace Mixin = @Mixin = if (typeof(exports) != 'undefined') then exports else {} Mixin.Core||Mixin.Core={} Mixin.VERSION = '0.1.5' #Mixin.DEBUG=true # define DEBUG before this file to enable rigorous checks #################################################### # Remove dependency on underscore, but inline minimally needed #################################################### # import Underscore (or Lo-Dash with precedence) _ = @_ if not _ and (typeof(require) isnt 'undefined') try _ = require('lodash') catch e then (try _ = require('underscore') catch e then {}) _ = _._ if _ and (_.hasOwnProperty('_')) # LEGACY _ = {} unless _ Mixin._ = _ # publish if needed and not including the full underscore library (_.isArray = (obj) -> return Object.prototype.toString.call(obj) == '[object Array]') unless _.isArray (_.isString = (obj) -> return !!(obj == '' || (obj && obj.charCodeAt && obj.substr))) unless _.isString (_.isFunction = (obj) -> return !!(obj && obj.constructor && obj.call && obj.apply)) unless _.isFunction (_.isEmpty = (obj) -> return (obj.length==0) if (_.isArray(obj) || _.isString(obj)); return false for key, value of obj; return true) unless _.isEmpty (_.classOf = (obj) -> return undefined if not (obj instanceof Object); return obj.prototype.constructor.name if (obj.prototype and obj.prototype.constructor and obj.prototype.constructor.name); return obj.constructor.name if (obj.constructor and obj.constructor.name); return undefined) unless _.classOf (_.size = (obj) -> i=0; i++ for key of obj; return i) unless _.size (_.find = (obj, iter) -> (return item if iter(item)) for item in obj; return null) unless _.find (_.remove = (array, item) -> index = array.indexOf(item); return if index<0; array.splice(index, 1); return item) unless _.remove (_.keypathExists = (object, keypath) -> return !!_.keypathValueOwner(object, keypath)) unless _.keypathExists (_.keypathValueOwner = (object, keypath) -> (components = if _.isString(keypath) then keypath.split('.') else keypath); ((if(i==components.length-1) then (if object.hasOwnProperty(key) then return object else return) else (return unless object.hasOwnProperty(key); object = object[key])) for key, i in components); return) unless _.keypathValueOwner (_.keypath = (object, keypath, value) -> components = keypath.split('.'); object = _.keypathValueOwner(object, components); return unless object; if(arguments.length==3) then (object[components[components.length-1]] = value; return value) else return object[components[components.length-1]]) unless _.keypath #################################################### # Validation Helpers to check parameters and throw Errors if invalid. # Use these when Mixin.DEBUG mode is true. #################################################### class Mixin.Core._Validate @mixinInfo: (mixin_info, overwrite, mixin_and_function) -> throw new Error("#{mixin_and_function}: mixin_info missing") if not mixin_info _Validate.string(mixin_info.mixin_name, mixin_and_function, 'mixin_name') throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' already registered") if not overwrite and Mixin.Core._Manager.available_mixins.hasOwnProperty(mixin_info.mixin_name) throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' missing mixin_object") if not mixin_info.mixin_object throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' mixin_object is invalid") if not (mixin_info.mixin_object instanceof Object) throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' initialize function is invalid") if mixin_info.initialize and not _.isFunction(mixin_info.initialize) throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' destroy function is invalid") if mixin_info.destroy and not _.isFunction(mixin_info.destroy) @instanceAndMixinName: (mix_target, mixin_name, mixin_and_function) -> throw new Error("#{mixin_and_function}: mix_target missing") if not mix_target _Validate.string(mixin_name, mixin_and_function, 'mixin_name') _Validate.instanceOrArray(mix_target, mixin_and_function, 'mix_target', mixin_name) @classConstructorAndMixinName: (constructor, mixin_name, mixin_and_function) -> throw new Error("#{mixin_and_function}: class constructor missing") if not constructor _Validate.string(mixin_name, mixin_and_function, 'mixin_name') throw new Error("#{mixin_and_function}: class constructor invalid for '#{mixin_name}'") if not _.isFunction(constructor) @exists: (parameter, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if parameter == undefined @object: (obj, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if obj == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if (typeof(obj)!='object') or _.isArray(obj) @uint: (uint, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if uint == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if not (typeof(uint) != 'number') or (uint<0) or (Math.floor(uint)!=uint) @string: (string, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if string == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if not _.isString(string) @stringArrayOrNestedStringArray: (array, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if array == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if not _.isArray(array) (throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if _.isArray(item) and (not item.length or not _.isString(item[0])) or not _.isString(item)) for item in string_or_array return @callback: (callback, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if callback == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if not _.isFunction(callback) @instance: (obj, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if obj == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if (typeof(obj)!='object' or _.isArray(obj)) or not _.isFunction(obj.constructor) or (obj.constructor.name=='Object') @instanceOrArray: (obj, mixin_and_function, parameter_name, mixin_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if obj == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if (typeof(obj)!='object') or not _.isFunction(obj.constructor) or (obj.constructor.name=='Object') or _.isArray(obj) @instanceWithMixin: (obj, mixin_name, mixin_and_function, parameter_name) -> _Validate.instance(obj, mixin_and_function, parameter_name) throw new Error("#{mixin_and_function}: #{parameter_name} missing mixin '#{mixin_name}' on #{_.classOf(obj)}") if not Mixin.hasMixin(obj, mixin_name) @noKey: (obj, key, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{key} already exists for #{parameter_name}") if obj.hasOwnProperty(key) @hasKey: (obj, key, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{key} does not exist for #{parameter_name}") if not obj.hasOwnProperty(key) #################################################### # Stored in the Mixin.Core._ClassRecord in the constructors of the mixed in classes #################################################### class Mixin.Core._InstanceRecord constructor: (@mix_target) -> @initialized_mixins = {} # stores hash of data per mixin destroy: -> throw new Error('Mixin: non-empty instance record being destroyed') if not _.isEmpty(@initialized_mixins) @mix_target = null hasMixin: (mixin_name, mark_as_mixed) -> has_mixin = @initialized_mixins.hasOwnProperty(mixin_name) return has_mixin if has_mixin or not mark_as_mixed @initialized_mixins[mixin_name] = {is_destroyed: false} return true collectMixins: (mixins) -> mixins.push(key) for key, mixin_info of @initialized_mixins return initializeMixin: (mixin_info, args) -> # initialize @initialized_mixins[mixin_info.mixin_name] = {is_destroyed: false, destroy: mixin_info.destroy} mixin_info.initialize.apply(@mix_target, args) if mixin_info.initialize destroyMixin: (mixin_name) -> if mixin_name return false if not @initialized_mixins.hasOwnProperty(mixin_name) return @_destroyMixinInfo(mixin_name) else mixin_existed = false (mixin_existed=true; @_destroyMixinInfo(key)) for key, value of @initialized_mixins return mixin_existed _destroyMixinInfo: (mixin_name) -> mixin_info = @initialized_mixins[mixin_name] return true if (mixin_info.is_destroyed) # already destroyed (for example, both manual and event-based auto destroy) mixin_info.is_destroyed = true # call mixin destroy function (mixin_info.destroy.apply(@mix_target); mixin_info.destroy = null) if mixin_info.destroy # cleanup any stored data and instance data Mixin.Core._Manager._destroyInstanceData(@mix_target, mixin_name) delete @initialized_mixins[mixin_name] return true #################################################### # Stored in the constructors of the mixed in classes #################################################### class Mixin.Core._ClassRecord constructor: (@constructor) -> @mixins = {} @instance_records = [] # mixin_info # force - in other words, over-write existing functions and properties (if they exist) mixIntoClass: (mix_target, mixin_info) -> return if @mixins.hasOwnProperty(mixin_info.mixin_name) # already mixed into the class @mixins[mixin_info.mixin_name] = mixin_info # check for property clashes before mixing in if not mixin_info.force (throw new Error("Mixin: property '#{key}' clashes with existing property on '#{_.classOf(mix_target)}") if (key of mix_target)) for key, value of mixin_info.mixin_object # now, add the mixin methods and possibly data (mix_target.constructor.prototype extends mixin_info.mixin_object) classHasMixin: (mixin_name) -> return @mixins.hasOwnProperty(mixin_name) instanceHasMixin: (mix_target, mixin_name, mark_as_mixed) -> instance_record = @_getInstanceRecord(mix_target) # You're telling me if mark_as_mixed @mixins[mixin_name] = Mixin.Core._Manager._getMixinInfo(mixin_name) if not @mixins.hasOwnProperty(mixin_name) (instance_record = new Mixin.Core._InstanceRecord(mix_target); @instance_records.push(instance_record)) if not instance_record return instance_record.hasMixin(mixin_name, mark_as_mixed) # I'm telling you else return if instance_record then instance_record.hasMixin(mixin_name) else false collectMixinsForInstance: (mixins, mix_target) -> instance_record = @_getInstanceRecord(mix_target) return if not instance_record instance_record.collectMixins(mixins) initializeInstance: (mix_target, mixin_info, args) -> instance_record = @_getInstanceRecord(mix_target) (instance_record.initializeMixin(mixin_info, args); return) if instance_record instance_record = new Mixin.Core._InstanceRecord(mix_target); @instance_records.push(instance_record) instance_record.initializeMixin(mixin_info, args) destroyInstance: (mix_target, mixin_name) -> return false if mixin_name and not @mixins.hasOwnProperty(mixin_name) mixin_existed = false i=@instance_records.length-1 while (i>=0) instance_record = @instance_records[i] if (instance_record.mix_target==mix_target) and instance_record.destroyMixin(mixin_name) mixin_existed = true (instance_record.destroy(); @instance_records.splice(i, 1)) if _.isEmpty(instance_record.initialized_mixins) return true if mixin_name i-- return mixin_existed _getInstanceRecord: (mix_target) -> (return instance_record if (instance_record.mix_target == mix_target)) for instance_record in @instance_records return undefined #################################################### # mixin_info: # mixin_name # initialize # destroy # force # suppress_destroy_event # mixin_object class Mixin.Core._Manager @available_mixins = {} #################################################### # Mixin Management Methods #################################################### # mixin_info properties # mixin_name - string (required) # mixin_object - object with properties to mixin (required) # initialize - function called on each instance when Mixin.in is called # destroy - function called on each instance when Mixin.out is called # Note: initialize and destroy are called with the mixin bound to 'this'. @registerMixin: (mixin_info, overwrite) -> Mixin.Core._Validate.mixinInfo(mixin_info, overwrite, 'Mixin.registerMixin') if Mixin.DEBUG _Manager.available_mixins[mixin_info.mixin_name] = mixin_info return true @isAvailable: (mixin_name) -> return _Manager.available_mixins.hasOwnProperty(mixin_name) @_getMixinInfo: (mixin_name) -> return _Manager.available_mixins[mixin_name] #################################################### # Mix Target Methods #################################################### # accepts: # in(mix_target, 'SomeMixin') # in(mix_target, 'SomeMixin', 'AnotherMixin', etc) # in(mix_target, 'SomeMixin', ['AMixinWithParameters', param1, param2, etc], etc) @mixin: (mix_target) -> _doMixin = (mix_target, mixin_name, params) => if Mixin.DEBUG Mixin.Core._Validate.instanceAndMixinName(mix_target, mixin_name, 'Mixin.mixin', 'mix_target') throw new Error("Mixin.mixin: '#{mixin_name}' not found") if not @isAvailable(mixin_name) mixin_info = _Manager.available_mixins[mixin_name] throw new Error("Mixin.mixin: '#{mixin_name}' not found") if not mixin_info # already mixed in return if @hasMixin(mix_target, mixin_info.mixin_name) # already initialized # initialize instance (if needed) class_record = _Manager._findOrCreateClassRecord(mix_target, mixin_info) class_record.mixIntoClass(mix_target, mixin_info) class_record.initializeInstance(mix_target, mixin_info, Array.prototype.slice.call(arguments, 2)) # check for infering parameters args = Array.prototype.slice.call(arguments, 1) throw new Error("Mixin: mixin_name missing") if not args.length if (args.length>1) check_arg = args[1] # the next parameter after the first mixin is not a mixin if not ((_.isString(check_arg) and _Manager.isAvailable(check_arg)) or (_.isArray(check_arg) and (check_arg.length>=1) and _.isString(check_arg[0]) and _Manager.isAvailable(check_arg[0]))) _doMixin.apply(this, arguments) return mix_target (if _.isArray(parameter) then _doMixin.apply(this, [mix_target].concat(parameter)) else _doMixin(mix_target, parameter)) for parameter in args return mix_target @mixout: (mix_target, mixin_name_or_names) -> if Mixin.DEBUG Mixin.Core._Validate.instance(mix_target, 'Mixin.mixout', 'mix_target') _doMixout = (mix_target, mixin_name) => if Mixin.DEBUG Mixin.Core._Validate.string(mixin_name, 'Mixin.mixout', 'mixin_name') if mix_target.constructor._mixin_class_records (return mix_target if class_record.destroyInstance(mix_target, mixin_name)) for class_record in mix_target.constructor._mixin_class_records return mix_target # process one or an array if arguments.length>1 _doMixout(mix_target, parameter) for parameter in Array.prototype.slice.call(arguments, 1) # clear all mixins else if mix_target.constructor._mixin_class_records (return mix_target if class_record.destroyInstance(mix_target)) for class_record in mix_target.constructor._mixin_class_records return mix_target @hasMixin: (mix_target, mixin_name, mark_as_mixed) -> # You're telling me if mark_as_mixed return true if _Manager.hasMixin(mix_target, mixin_name) # already mixed in mixin_info = _Manager.available_mixins[mixin_name] return false if not mixin_info class_record = _Manager._findOrCreateClassRecord(mix_target, mixin_info) class_record.instanceHasMixin(mix_target, mixin_name, mark_as_mixed) # I'm telling you else Mixin.Core._Validate.instanceAndMixinName(mix_target, mixin_name, 'Mixin.hasMixin', 'mix_target') if Mixin.DEBUG return true if _Manager.hasInstanceData(mix_target, mixin_name) # shortcut class_record = _Manager._findClassRecord(mix_target, mixin_name) return false if not class_record return class_record.instanceHasMixin(mix_target, mixin_name) @mixins: (mix_target) -> Mixin.Core._Validate.instance(mix_target, mixins, 'Mixin.mixins', 'mix_target') if Mixin.DEBUG mixins = [] if mix_target.constructor._mixin_class_records class_record.collectMixinsForInstance(mixins, mix_target) for class_record in mix_target.constructor._mixin_class_records return mixins @_getClassRecords: (mix_target) -> class_records = [] constructor = mix_target.constructor while (constructor) if constructor._mixin_class_records (class_records.push(class_record) if (mix_target instanceof class_record.constructor)) for class_record in constructor._mixin_class_records constructor = if (constructor.__super__ and (constructor.__super__.constructor!=constructor)) then constructor.__super__.constructor else undefined return class_records @_findClassRecord: (mix_target, mixin_name) -> class_records = @_getClassRecords(mix_target) (return class_record if class_record.classHasMixin(mixin_name)) for class_record in class_records return undefined @_findOrCreateClassRecord: (mix_target, mixin_info) -> # look for an existing class record class_record = _Manager._findClassRecord(mix_target, mixin_info.mixin_name) return class_record if class_record # not already mixed at this level class_record = _.find(mix_target.constructor._mixin_class_records, (test)-> return test.constructor==mix_target.constructor) if (mix_target.constructor._mixin_class_records) if not class_record class_record = new Mixin.Core._ClassRecord(mix_target.constructor) if mix_target.constructor._mixin_class_records was_added = false # put it before its super class i=0; l=mix_target.constructor._mixin_class_records.length while (i<l) other_class_record = mix_target.constructor._mixin_class_records[i] if (mix_target instanceof other_class_record.constructor) mix_target.constructor._mixin_class_records.splice(i, 0, class_record); was_added = true break; i++ mix_target.constructor._mixin_class_records.push(class_record) if not was_added else mix_target.constructor._mixin_class_records = [class_record] Mixin._statistics.addClassRecord(class_record) if Mixin._statistics return class_record #################################################### # Mix Target Instance Data Methods #################################################### @hasInstanceData: (mix_target, mixin_name) -> Mixin.Core._Validate.instanceAndMixinName(mix_target, mixin_name, 'Mixin.hasInstanceData', 'mix_target') if Mixin.DEBUG return !!(mix_target._mixin_data and mix_target._mixin_data.hasOwnProperty(mixin_name)) @instanceData: (mix_target, mixin_name, data) -> if Mixin.DEBUG Mixin.Core._Validate.instanceAndMixinName(mix_target, mixin_name, 'Mixin.instanceData', 'mix_target') if (data==undefined) throw new Error("Mixin.instanceData: no instance data on '#{_.classOf(mix_target)}'") if not ('_mixin_data' of mix_target) throw new Error("Mixin.instanceData: mixin '#{mixin_name}' instance data not found on '#{_.classOf(mix_target)}'") if not mix_target._mixin_data.hasOwnProperty(mixin_name) else throw new Error("Mixin.instanceData: mixin '#{mixin_name}' not mixed into '#{_.classOf(mix_target)}'") if not _Manager.hasMixin(mix_target, mixin_name) # set if not (data==undefined) mix_target._mixin_data = {} if not mix_target._mixin_data mix_target._mixin_data[mixin_name] = data return mix_target._mixin_data[mixin_name] @_destroyInstanceData: (mix_target, mixin_name) -> return undefined if not mix_target._mixin_data data = mix_target._mixin_data[mixin_name] delete mix_target._mixin_data[mixin_name] delete mix_target['_mixin_data'] if _.isEmpty(mix_target._mixin_data) # create the manager and expose public interface in Mixin namespace Mixin.registerMixin = Mixin.Core._Manager.registerMixin Mixin.isAvailable = Mixin.Core._Manager.isAvailable Mixin.mixin = Mixin.in = Mixin.Core._Manager.mixin Mixin.mixout = Mixin.out = Mixin.Core._Manager.mixout Mixin.hasMixin = Mixin.exists = Mixin.Core._Manager.hasMixin Mixin.mixins = Mixin.Core._Manager.mixins Mixin.hasInstanceData = Mixin.hasID = Mixin.Core._Manager.hasInstanceData Mixin.instanceData = Mixin.iD = Mixin.Core._Manager.instanceData exports.Mixin = Mixin if (typeof(exports) != 'undefined')
true
### mixin-js.js 0.1.5 (c) 2011, 2012 PI:NAME:<NAME>END_PI - http://kmalakoff.github.com/mixin/ License: MIT (http://www.opensource.org/licenses/mit-license.php) Note: some code from Underscore.js is embedded in this file to remove dependencies on the full library. Please see the following for details on Underscore.js and its licensing: https://github.com/documentcloud/underscore https://github.com/documentcloud/underscore/blob/master/LICENSE ### # export or create Mixin namespace Mixin = @Mixin = if (typeof(exports) != 'undefined') then exports else {} Mixin.Core||Mixin.Core={} Mixin.VERSION = '0.1.5' #Mixin.DEBUG=true # define DEBUG before this file to enable rigorous checks #################################################### # Remove dependency on underscore, but inline minimally needed #################################################### # import Underscore (or Lo-Dash with precedence) _ = @_ if not _ and (typeof(require) isnt 'undefined') try _ = require('lodash') catch e then (try _ = require('underscore') catch e then {}) _ = _._ if _ and (_.hasOwnProperty('_')) # LEGACY _ = {} unless _ Mixin._ = _ # publish if needed and not including the full underscore library (_.isArray = (obj) -> return Object.prototype.toString.call(obj) == '[object Array]') unless _.isArray (_.isString = (obj) -> return !!(obj == '' || (obj && obj.charCodeAt && obj.substr))) unless _.isString (_.isFunction = (obj) -> return !!(obj && obj.constructor && obj.call && obj.apply)) unless _.isFunction (_.isEmpty = (obj) -> return (obj.length==0) if (_.isArray(obj) || _.isString(obj)); return false for key, value of obj; return true) unless _.isEmpty (_.classOf = (obj) -> return undefined if not (obj instanceof Object); return obj.prototype.constructor.name if (obj.prototype and obj.prototype.constructor and obj.prototype.constructor.name); return obj.constructor.name if (obj.constructor and obj.constructor.name); return undefined) unless _.classOf (_.size = (obj) -> i=0; i++ for key of obj; return i) unless _.size (_.find = (obj, iter) -> (return item if iter(item)) for item in obj; return null) unless _.find (_.remove = (array, item) -> index = array.indexOf(item); return if index<0; array.splice(index, 1); return item) unless _.remove (_.keypathExists = (object, keypath) -> return !!_.keypathValueOwner(object, keypath)) unless _.keypathExists (_.keypathValueOwner = (object, keypath) -> (components = if _.isString(keypath) then keypath.split('.') else keypath); ((if(i==components.length-1) then (if object.hasOwnProperty(key) then return object else return) else (return unless object.hasOwnProperty(key); object = object[key])) for key, i in components); return) unless _.keypathValueOwner (_.keypath = (object, keypath, value) -> components = keypath.split('.'); object = _.keypathValueOwner(object, components); return unless object; if(arguments.length==3) then (object[components[components.length-1]] = value; return value) else return object[components[components.length-1]]) unless _.keypath #################################################### # Validation Helpers to check parameters and throw Errors if invalid. # Use these when Mixin.DEBUG mode is true. #################################################### class Mixin.Core._Validate @mixinInfo: (mixin_info, overwrite, mixin_and_function) -> throw new Error("#{mixin_and_function}: mixin_info missing") if not mixin_info _Validate.string(mixin_info.mixin_name, mixin_and_function, 'mixin_name') throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' already registered") if not overwrite and Mixin.Core._Manager.available_mixins.hasOwnProperty(mixin_info.mixin_name) throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' missing mixin_object") if not mixin_info.mixin_object throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' mixin_object is invalid") if not (mixin_info.mixin_object instanceof Object) throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' initialize function is invalid") if mixin_info.initialize and not _.isFunction(mixin_info.initialize) throw new Error("#{mixin_and_function}: mixin_info '#{mixin_info.mixin_name}' destroy function is invalid") if mixin_info.destroy and not _.isFunction(mixin_info.destroy) @instanceAndMixinName: (mix_target, mixin_name, mixin_and_function) -> throw new Error("#{mixin_and_function}: mix_target missing") if not mix_target _Validate.string(mixin_name, mixin_and_function, 'mixin_name') _Validate.instanceOrArray(mix_target, mixin_and_function, 'mix_target', mixin_name) @classConstructorAndMixinName: (constructor, mixin_name, mixin_and_function) -> throw new Error("#{mixin_and_function}: class constructor missing") if not constructor _Validate.string(mixin_name, mixin_and_function, 'mixin_name') throw new Error("#{mixin_and_function}: class constructor invalid for '#{mixin_name}'") if not _.isFunction(constructor) @exists: (parameter, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if parameter == undefined @object: (obj, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if obj == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if (typeof(obj)!='object') or _.isArray(obj) @uint: (uint, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if uint == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if not (typeof(uint) != 'number') or (uint<0) or (Math.floor(uint)!=uint) @string: (string, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if string == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if not _.isString(string) @stringArrayOrNestedStringArray: (array, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if array == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if not _.isArray(array) (throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if _.isArray(item) and (not item.length or not _.isString(item[0])) or not _.isString(item)) for item in string_or_array return @callback: (callback, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if callback == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if not _.isFunction(callback) @instance: (obj, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if obj == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if (typeof(obj)!='object' or _.isArray(obj)) or not _.isFunction(obj.constructor) or (obj.constructor.name=='Object') @instanceOrArray: (obj, mixin_and_function, parameter_name, mixin_name) -> throw new Error("#{mixin_and_function}: #{parameter_name} missing") if obj == undefined throw new Error("#{mixin_and_function}: #{parameter_name} invalid") if (typeof(obj)!='object') or not _.isFunction(obj.constructor) or (obj.constructor.name=='Object') or _.isArray(obj) @instanceWithMixin: (obj, mixin_name, mixin_and_function, parameter_name) -> _Validate.instance(obj, mixin_and_function, parameter_name) throw new Error("#{mixin_and_function}: #{parameter_name} missing mixin '#{mixin_name}' on #{_.classOf(obj)}") if not Mixin.hasMixin(obj, mixin_name) @noKey: (obj, key, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{key} already exists for #{parameter_name}") if obj.hasOwnProperty(key) @hasKey: (obj, key, mixin_and_function, parameter_name) -> throw new Error("#{mixin_and_function}: #{key} does not exist for #{parameter_name}") if not obj.hasOwnProperty(key) #################################################### # Stored in the Mixin.Core._ClassRecord in the constructors of the mixed in classes #################################################### class Mixin.Core._InstanceRecord constructor: (@mix_target) -> @initialized_mixins = {} # stores hash of data per mixin destroy: -> throw new Error('Mixin: non-empty instance record being destroyed') if not _.isEmpty(@initialized_mixins) @mix_target = null hasMixin: (mixin_name, mark_as_mixed) -> has_mixin = @initialized_mixins.hasOwnProperty(mixin_name) return has_mixin if has_mixin or not mark_as_mixed @initialized_mixins[mixin_name] = {is_destroyed: false} return true collectMixins: (mixins) -> mixins.push(key) for key, mixin_info of @initialized_mixins return initializeMixin: (mixin_info, args) -> # initialize @initialized_mixins[mixin_info.mixin_name] = {is_destroyed: false, destroy: mixin_info.destroy} mixin_info.initialize.apply(@mix_target, args) if mixin_info.initialize destroyMixin: (mixin_name) -> if mixin_name return false if not @initialized_mixins.hasOwnProperty(mixin_name) return @_destroyMixinInfo(mixin_name) else mixin_existed = false (mixin_existed=true; @_destroyMixinInfo(key)) for key, value of @initialized_mixins return mixin_existed _destroyMixinInfo: (mixin_name) -> mixin_info = @initialized_mixins[mixin_name] return true if (mixin_info.is_destroyed) # already destroyed (for example, both manual and event-based auto destroy) mixin_info.is_destroyed = true # call mixin destroy function (mixin_info.destroy.apply(@mix_target); mixin_info.destroy = null) if mixin_info.destroy # cleanup any stored data and instance data Mixin.Core._Manager._destroyInstanceData(@mix_target, mixin_name) delete @initialized_mixins[mixin_name] return true #################################################### # Stored in the constructors of the mixed in classes #################################################### class Mixin.Core._ClassRecord constructor: (@constructor) -> @mixins = {} @instance_records = [] # mixin_info # force - in other words, over-write existing functions and properties (if they exist) mixIntoClass: (mix_target, mixin_info) -> return if @mixins.hasOwnProperty(mixin_info.mixin_name) # already mixed into the class @mixins[mixin_info.mixin_name] = mixin_info # check for property clashes before mixing in if not mixin_info.force (throw new Error("Mixin: property '#{key}' clashes with existing property on '#{_.classOf(mix_target)}") if (key of mix_target)) for key, value of mixin_info.mixin_object # now, add the mixin methods and possibly data (mix_target.constructor.prototype extends mixin_info.mixin_object) classHasMixin: (mixin_name) -> return @mixins.hasOwnProperty(mixin_name) instanceHasMixin: (mix_target, mixin_name, mark_as_mixed) -> instance_record = @_getInstanceRecord(mix_target) # You're telling me if mark_as_mixed @mixins[mixin_name] = Mixin.Core._Manager._getMixinInfo(mixin_name) if not @mixins.hasOwnProperty(mixin_name) (instance_record = new Mixin.Core._InstanceRecord(mix_target); @instance_records.push(instance_record)) if not instance_record return instance_record.hasMixin(mixin_name, mark_as_mixed) # I'm telling you else return if instance_record then instance_record.hasMixin(mixin_name) else false collectMixinsForInstance: (mixins, mix_target) -> instance_record = @_getInstanceRecord(mix_target) return if not instance_record instance_record.collectMixins(mixins) initializeInstance: (mix_target, mixin_info, args) -> instance_record = @_getInstanceRecord(mix_target) (instance_record.initializeMixin(mixin_info, args); return) if instance_record instance_record = new Mixin.Core._InstanceRecord(mix_target); @instance_records.push(instance_record) instance_record.initializeMixin(mixin_info, args) destroyInstance: (mix_target, mixin_name) -> return false if mixin_name and not @mixins.hasOwnProperty(mixin_name) mixin_existed = false i=@instance_records.length-1 while (i>=0) instance_record = @instance_records[i] if (instance_record.mix_target==mix_target) and instance_record.destroyMixin(mixin_name) mixin_existed = true (instance_record.destroy(); @instance_records.splice(i, 1)) if _.isEmpty(instance_record.initialized_mixins) return true if mixin_name i-- return mixin_existed _getInstanceRecord: (mix_target) -> (return instance_record if (instance_record.mix_target == mix_target)) for instance_record in @instance_records return undefined #################################################### # mixin_info: # mixin_name # initialize # destroy # force # suppress_destroy_event # mixin_object class Mixin.Core._Manager @available_mixins = {} #################################################### # Mixin Management Methods #################################################### # mixin_info properties # mixin_name - string (required) # mixin_object - object with properties to mixin (required) # initialize - function called on each instance when Mixin.in is called # destroy - function called on each instance when Mixin.out is called # Note: initialize and destroy are called with the mixin bound to 'this'. @registerMixin: (mixin_info, overwrite) -> Mixin.Core._Validate.mixinInfo(mixin_info, overwrite, 'Mixin.registerMixin') if Mixin.DEBUG _Manager.available_mixins[mixin_info.mixin_name] = mixin_info return true @isAvailable: (mixin_name) -> return _Manager.available_mixins.hasOwnProperty(mixin_name) @_getMixinInfo: (mixin_name) -> return _Manager.available_mixins[mixin_name] #################################################### # Mix Target Methods #################################################### # accepts: # in(mix_target, 'SomeMixin') # in(mix_target, 'SomeMixin', 'AnotherMixin', etc) # in(mix_target, 'SomeMixin', ['AMixinWithParameters', param1, param2, etc], etc) @mixin: (mix_target) -> _doMixin = (mix_target, mixin_name, params) => if Mixin.DEBUG Mixin.Core._Validate.instanceAndMixinName(mix_target, mixin_name, 'Mixin.mixin', 'mix_target') throw new Error("Mixin.mixin: '#{mixin_name}' not found") if not @isAvailable(mixin_name) mixin_info = _Manager.available_mixins[mixin_name] throw new Error("Mixin.mixin: '#{mixin_name}' not found") if not mixin_info # already mixed in return if @hasMixin(mix_target, mixin_info.mixin_name) # already initialized # initialize instance (if needed) class_record = _Manager._findOrCreateClassRecord(mix_target, mixin_info) class_record.mixIntoClass(mix_target, mixin_info) class_record.initializeInstance(mix_target, mixin_info, Array.prototype.slice.call(arguments, 2)) # check for infering parameters args = Array.prototype.slice.call(arguments, 1) throw new Error("Mixin: mixin_name missing") if not args.length if (args.length>1) check_arg = args[1] # the next parameter after the first mixin is not a mixin if not ((_.isString(check_arg) and _Manager.isAvailable(check_arg)) or (_.isArray(check_arg) and (check_arg.length>=1) and _.isString(check_arg[0]) and _Manager.isAvailable(check_arg[0]))) _doMixin.apply(this, arguments) return mix_target (if _.isArray(parameter) then _doMixin.apply(this, [mix_target].concat(parameter)) else _doMixin(mix_target, parameter)) for parameter in args return mix_target @mixout: (mix_target, mixin_name_or_names) -> if Mixin.DEBUG Mixin.Core._Validate.instance(mix_target, 'Mixin.mixout', 'mix_target') _doMixout = (mix_target, mixin_name) => if Mixin.DEBUG Mixin.Core._Validate.string(mixin_name, 'Mixin.mixout', 'mixin_name') if mix_target.constructor._mixin_class_records (return mix_target if class_record.destroyInstance(mix_target, mixin_name)) for class_record in mix_target.constructor._mixin_class_records return mix_target # process one or an array if arguments.length>1 _doMixout(mix_target, parameter) for parameter in Array.prototype.slice.call(arguments, 1) # clear all mixins else if mix_target.constructor._mixin_class_records (return mix_target if class_record.destroyInstance(mix_target)) for class_record in mix_target.constructor._mixin_class_records return mix_target @hasMixin: (mix_target, mixin_name, mark_as_mixed) -> # You're telling me if mark_as_mixed return true if _Manager.hasMixin(mix_target, mixin_name) # already mixed in mixin_info = _Manager.available_mixins[mixin_name] return false if not mixin_info class_record = _Manager._findOrCreateClassRecord(mix_target, mixin_info) class_record.instanceHasMixin(mix_target, mixin_name, mark_as_mixed) # I'm telling you else Mixin.Core._Validate.instanceAndMixinName(mix_target, mixin_name, 'Mixin.hasMixin', 'mix_target') if Mixin.DEBUG return true if _Manager.hasInstanceData(mix_target, mixin_name) # shortcut class_record = _Manager._findClassRecord(mix_target, mixin_name) return false if not class_record return class_record.instanceHasMixin(mix_target, mixin_name) @mixins: (mix_target) -> Mixin.Core._Validate.instance(mix_target, mixins, 'Mixin.mixins', 'mix_target') if Mixin.DEBUG mixins = [] if mix_target.constructor._mixin_class_records class_record.collectMixinsForInstance(mixins, mix_target) for class_record in mix_target.constructor._mixin_class_records return mixins @_getClassRecords: (mix_target) -> class_records = [] constructor = mix_target.constructor while (constructor) if constructor._mixin_class_records (class_records.push(class_record) if (mix_target instanceof class_record.constructor)) for class_record in constructor._mixin_class_records constructor = if (constructor.__super__ and (constructor.__super__.constructor!=constructor)) then constructor.__super__.constructor else undefined return class_records @_findClassRecord: (mix_target, mixin_name) -> class_records = @_getClassRecords(mix_target) (return class_record if class_record.classHasMixin(mixin_name)) for class_record in class_records return undefined @_findOrCreateClassRecord: (mix_target, mixin_info) -> # look for an existing class record class_record = _Manager._findClassRecord(mix_target, mixin_info.mixin_name) return class_record if class_record # not already mixed at this level class_record = _.find(mix_target.constructor._mixin_class_records, (test)-> return test.constructor==mix_target.constructor) if (mix_target.constructor._mixin_class_records) if not class_record class_record = new Mixin.Core._ClassRecord(mix_target.constructor) if mix_target.constructor._mixin_class_records was_added = false # put it before its super class i=0; l=mix_target.constructor._mixin_class_records.length while (i<l) other_class_record = mix_target.constructor._mixin_class_records[i] if (mix_target instanceof other_class_record.constructor) mix_target.constructor._mixin_class_records.splice(i, 0, class_record); was_added = true break; i++ mix_target.constructor._mixin_class_records.push(class_record) if not was_added else mix_target.constructor._mixin_class_records = [class_record] Mixin._statistics.addClassRecord(class_record) if Mixin._statistics return class_record #################################################### # Mix Target Instance Data Methods #################################################### @hasInstanceData: (mix_target, mixin_name) -> Mixin.Core._Validate.instanceAndMixinName(mix_target, mixin_name, 'Mixin.hasInstanceData', 'mix_target') if Mixin.DEBUG return !!(mix_target._mixin_data and mix_target._mixin_data.hasOwnProperty(mixin_name)) @instanceData: (mix_target, mixin_name, data) -> if Mixin.DEBUG Mixin.Core._Validate.instanceAndMixinName(mix_target, mixin_name, 'Mixin.instanceData', 'mix_target') if (data==undefined) throw new Error("Mixin.instanceData: no instance data on '#{_.classOf(mix_target)}'") if not ('_mixin_data' of mix_target) throw new Error("Mixin.instanceData: mixin '#{mixin_name}' instance data not found on '#{_.classOf(mix_target)}'") if not mix_target._mixin_data.hasOwnProperty(mixin_name) else throw new Error("Mixin.instanceData: mixin '#{mixin_name}' not mixed into '#{_.classOf(mix_target)}'") if not _Manager.hasMixin(mix_target, mixin_name) # set if not (data==undefined) mix_target._mixin_data = {} if not mix_target._mixin_data mix_target._mixin_data[mixin_name] = data return mix_target._mixin_data[mixin_name] @_destroyInstanceData: (mix_target, mixin_name) -> return undefined if not mix_target._mixin_data data = mix_target._mixin_data[mixin_name] delete mix_target._mixin_data[mixin_name] delete mix_target['_mixin_data'] if _.isEmpty(mix_target._mixin_data) # create the manager and expose public interface in Mixin namespace Mixin.registerMixin = Mixin.Core._Manager.registerMixin Mixin.isAvailable = Mixin.Core._Manager.isAvailable Mixin.mixin = Mixin.in = Mixin.Core._Manager.mixin Mixin.mixout = Mixin.out = Mixin.Core._Manager.mixout Mixin.hasMixin = Mixin.exists = Mixin.Core._Manager.hasMixin Mixin.mixins = Mixin.Core._Manager.mixins Mixin.hasInstanceData = Mixin.hasID = Mixin.Core._Manager.hasInstanceData Mixin.instanceData = Mixin.iD = Mixin.Core._Manager.instanceData exports.Mixin = Mixin if (typeof(exports) != 'undefined')
[ { "context": "#\n# Copyright 2017 Dr. Michael Menzel, Amazon Web Services Germany GmbH\n#\n# Licensed ", "end": 40, "score": 0.9997379183769226, "start": 26, "tag": "NAME", "value": "Michael Menzel" }, { "context": "edentials(\n IdentityPoolId: 'eu-central-1:68658909-d15f-4...
app/s3.service.coffee
mugglmenzel/s3-bucket-viewer-angular
1
# # Copyright 2017 Dr. Michael Menzel, Amazon Web Services Germany GmbH # # 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. # class S3Client constructor: -> AWS.config.region = 'eu-central-1' AWS.config.credentials = new AWS.CognitoIdentityCredentials( IdentityPoolId: 'eu-central-1:68658909-d15f-4579-a7cb-b1d61670e7ce' ) @s3 = new AWS.S3() client: -> @s3 s3Client = new S3Client().client() angular.module('DemoApp').factory('S3', [ -> list: (bucketName, prefix) -> console.log "ListObjects on S3 API with bucket #{JSON.stringify(bucketName)} and prefix #{JSON.stringify(prefix)}" new Promise((resolve, reject) -> s3Client.listObjects({Bucket: bucketName, Prefix: prefix}, (err, data) -> if err? console.log "[S3Client] error while fetching object list: #{JSON.stringify(err)}" reject(err) else resolve(data.Contents) ) ) downloadLink: (bucketName, objectName) -> new Promise((resolve, reject) -> s3Client.getSignedUrl('getObject', {Bucket: bucketName, Key: objectName, Expires: 300}, (err, data) -> if err? console.log "[S3Client] error while fetching download link: #{JSON.stringify(err)}" reject(err) else resolve(data) ) ) ])
60075
# # Copyright 2017 Dr. <NAME>, Amazon Web Services Germany GmbH # # 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. # class S3Client constructor: -> AWS.config.region = 'eu-central-1' AWS.config.credentials = new AWS.CognitoIdentityCredentials( IdentityPoolId: 'eu-central-1:686<PASSWORD>' ) @s3 = new AWS.S3() client: -> @s3 s3Client = new S3Client().client() angular.module('DemoApp').factory('S3', [ -> list: (bucketName, prefix) -> console.log "ListObjects on S3 API with bucket #{JSON.stringify(bucketName)} and prefix #{JSON.stringify(prefix)}" new Promise((resolve, reject) -> s3Client.listObjects({Bucket: bucketName, Prefix: prefix}, (err, data) -> if err? console.log "[S3Client] error while fetching object list: #{JSON.stringify(err)}" reject(err) else resolve(data.Contents) ) ) downloadLink: (bucketName, objectName) -> new Promise((resolve, reject) -> s3Client.getSignedUrl('getObject', {Bucket: bucketName, Key: objectName, Expires: 300}, (err, data) -> if err? console.log "[S3Client] error while fetching download link: #{JSON.stringify(err)}" reject(err) else resolve(data) ) ) ])
true
# # Copyright 2017 Dr. PI:NAME:<NAME>END_PI, Amazon Web Services Germany GmbH # # 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. # class S3Client constructor: -> AWS.config.region = 'eu-central-1' AWS.config.credentials = new AWS.CognitoIdentityCredentials( IdentityPoolId: 'eu-central-1:686PI:PASSWORD:<PASSWORD>END_PI' ) @s3 = new AWS.S3() client: -> @s3 s3Client = new S3Client().client() angular.module('DemoApp').factory('S3', [ -> list: (bucketName, prefix) -> console.log "ListObjects on S3 API with bucket #{JSON.stringify(bucketName)} and prefix #{JSON.stringify(prefix)}" new Promise((resolve, reject) -> s3Client.listObjects({Bucket: bucketName, Prefix: prefix}, (err, data) -> if err? console.log "[S3Client] error while fetching object list: #{JSON.stringify(err)}" reject(err) else resolve(data.Contents) ) ) downloadLink: (bucketName, objectName) -> new Promise((resolve, reject) -> s3Client.getSignedUrl('getObject', {Bucket: bucketName, Key: objectName, Expires: 300}, (err, data) -> if err? console.log "[S3Client] error while fetching download link: #{JSON.stringify(err)}" reject(err) else resolve(data) ) ) ])
[ { "context": "es.countries\n should.exist res.cities\n\napi.host '216.197.103.72', (err, res) ->\n should.not.exist err\n should.e", "end": 458, "score": 0.9996318817138672, "start": 444, "tag": "IP_ADDRESS", "value": "216.197.103.72" } ]
examples/test.coffee
contra/node-shodan
2
Shodan = require '../index' should = require 'should' api = new Shodan 'o2J4sPGDw8yDCbaiFKRtpcCzA63gnguQ' api.info (err, res) -> should.not.exist err should.exist res api.search 'wrt54g city:Phoenix', (err, res) -> should.not.exist err should.exist res should.exist res.matches[0].ip api.locations 'wrt54g', (err, res) -> should.not.exist err should.exist res should.exist res.countries should.exist res.cities api.host '216.197.103.72', (err, res) -> should.not.exist err should.exist res should.exist res.data should.exist res.data[0].port api.fingerprint 'OpenSSH', (err, res) -> should.not.exist err should.exist res # TODO: Better test value api.wps.locate '00:1D:7E:F0:A2:B0', (err, res) -> should.not.exist err should.exist res should.exist res.location should.exist res.location.address #res.location.address.city.should.equal 'Portland' ### api.exploits.search 'microsoft', (err, res) -> should.not.exist err should.exist res console.log res api.msf.search 'microsoft', (err, res) -> should.not.exist err should.exist res console.log res ###
213607
Shodan = require '../index' should = require 'should' api = new Shodan 'o2J4sPGDw8yDCbaiFKRtpcCzA63gnguQ' api.info (err, res) -> should.not.exist err should.exist res api.search 'wrt54g city:Phoenix', (err, res) -> should.not.exist err should.exist res should.exist res.matches[0].ip api.locations 'wrt54g', (err, res) -> should.not.exist err should.exist res should.exist res.countries should.exist res.cities api.host '192.168.127.12', (err, res) -> should.not.exist err should.exist res should.exist res.data should.exist res.data[0].port api.fingerprint 'OpenSSH', (err, res) -> should.not.exist err should.exist res # TODO: Better test value api.wps.locate '00:1D:7E:F0:A2:B0', (err, res) -> should.not.exist err should.exist res should.exist res.location should.exist res.location.address #res.location.address.city.should.equal 'Portland' ### api.exploits.search 'microsoft', (err, res) -> should.not.exist err should.exist res console.log res api.msf.search 'microsoft', (err, res) -> should.not.exist err should.exist res console.log res ###
true
Shodan = require '../index' should = require 'should' api = new Shodan 'o2J4sPGDw8yDCbaiFKRtpcCzA63gnguQ' api.info (err, res) -> should.not.exist err should.exist res api.search 'wrt54g city:Phoenix', (err, res) -> should.not.exist err should.exist res should.exist res.matches[0].ip api.locations 'wrt54g', (err, res) -> should.not.exist err should.exist res should.exist res.countries should.exist res.cities api.host 'PI:IP_ADDRESS:192.168.127.12END_PI', (err, res) -> should.not.exist err should.exist res should.exist res.data should.exist res.data[0].port api.fingerprint 'OpenSSH', (err, res) -> should.not.exist err should.exist res # TODO: Better test value api.wps.locate '00:1D:7E:F0:A2:B0', (err, res) -> should.not.exist err should.exist res should.exist res.location should.exist res.location.address #res.location.address.city.should.equal 'Portland' ### api.exploits.search 'microsoft', (err, res) -> should.not.exist err should.exist res console.log res api.msf.search 'microsoft', (err, res) -> should.not.exist err should.exist res console.log res ###
[ { "context": "###\n From Vibrant.js by Jari Zwarts\n Ported to node.js by AKFish\n\n Color algorithm ", "end": 36, "score": 0.9998909831047058, "start": 25, "tag": "NAME", "value": "Jari Zwarts" }, { "context": "m Vibrant.js by Jari Zwarts\n Ported to node.js by AKFish\n\n Color...
src/vibrant.coffee
czana/node-logo-colors
0
### From Vibrant.js by Jari Zwarts Ported to node.js by AKFish Color algorithm class that finds variations on colors in an image. Credits -------- Lokesh Dhakar (http://www.lokeshdhakar.com) - Created ColorThief Google - Palette support library in Android ### Swatch = require('./swatch') util = require('./util') DefaultGenerator = require('./generator').Default Filter = require('./filter') module.exports = class Vibrant @DefaultOpts: colorCount: 16 quality: 5 generator: new DefaultGenerator() Image: null Quantizer: require('./quantizer').MMCQ filters: [] minPopulation: 35 minRgbDiff: 15 comparingPopulationIndex: 1 @from: (src) -> new Builder(src) quantize: require('quantize') _swatches: [] constructor: (@sourceImage, opts = {}) -> @opts = util.defaults(opts, @constructor.DefaultOpts) @generator = @opts.generator getPalette: (cb) -> image = new @opts.Image @sourceImage, (err, image) => if err? then return cb(err) try @_process image, @opts cb null, @swatches() catch error return cb(error) getSwatches: (cb) -> @getPalette cb _process: (image, opts) -> image.scaleDown(@opts) imageData = image.getImageData() quantizer = new @opts.Quantizer() quantizer.initialize(imageData.data, @opts) @allSwatches = quantizer.getQuantizedColors() image.removeCanvas() swatches: => finalSwatches = [] @allSwatches = @allSwatches.sort (a, b) -> b.getPopulation() - a.getPopulation() comparingPopulation = @getComparingPopulation(@allSwatches, @opts.comparingPopulationIndex) for swatch in @allSwatches if @populationPercentage(swatch.getPopulation(), comparingPopulation) > @opts.minPopulation should_be_added = true for final_swatch in finalSwatches if Vibrant.Util.rgbDiff(final_swatch.rgb, swatch.rgb) < @opts.minRgbDiff should_be_added = false break if should_be_added finalSwatches.push swatch finalSwatches populationPercentage: (population, comparingPopulation) -> if comparingPopulation == 0 console.log('comparing population equals 0!') return 0 (population / comparingPopulation) * 100 getComparingPopulation: (swatches, index) -> if swatches.length > index swatches[index].getPopulation() else console.log('there is no swatches with index - ' + index) 100 module.exports.Builder = class Builder constructor: (@src, @opts = {}) -> @opts.filters = util.clone Vibrant.DefaultOpts.filters maxColorCount: (n) -> @opts.colorCount = n @ maxDimension: (d) -> @opts.maxDimension = d @ addFilter: (f) -> if typeof f == 'function' @opts.filters.push f @ removeFilter: (f) -> if (i = @opts.filters.indexOf(f)) > 0 @opts.filters.splice(i) @ clearFilters: -> @opts.filters = [] @ quality: (q) -> @opts.quality = q @ minPopulation: (q) -> @opts.minPopulation = q @ minRgbDiff: (q) -> @opts.minRgbDiff = q @ comparingPopulationIndex: (q) -> @opts.comparingPopulationIndex = q @ useImage: (image) -> @opts.Image = image @ useQuantizer: (quantizer) -> @opts.Quantizer = quantizer @ build: -> if not @v? @v = new Vibrant(@src, @opts) @v getSwatches: (cb) -> @build().getPalette cb getPalette: (cb) -> @build().getPalette cb from: (src) -> new Vibrant(src, @opts) module.exports.Util = util module.exports.Swatch = Swatch module.exports.Quantizer = require('./quantizer/') module.exports.Generator = require('./generator/') module.exports.Filter = require('./filter/')
90805
### From Vibrant.js by <NAME> Ported to node.js by AKFish Color algorithm class that finds variations on colors in an image. Credits -------- <NAME> (http://www.lokeshdhakar.com) - Created ColorThief Google - Palette support library in Android ### Swatch = require('./swatch') util = require('./util') DefaultGenerator = require('./generator').Default Filter = require('./filter') module.exports = class Vibrant @DefaultOpts: colorCount: 16 quality: 5 generator: new DefaultGenerator() Image: null Quantizer: require('./quantizer').MMCQ filters: [] minPopulation: 35 minRgbDiff: 15 comparingPopulationIndex: 1 @from: (src) -> new Builder(src) quantize: require('quantize') _swatches: [] constructor: (@sourceImage, opts = {}) -> @opts = util.defaults(opts, @constructor.DefaultOpts) @generator = @opts.generator getPalette: (cb) -> image = new @opts.Image @sourceImage, (err, image) => if err? then return cb(err) try @_process image, @opts cb null, @swatches() catch error return cb(error) getSwatches: (cb) -> @getPalette cb _process: (image, opts) -> image.scaleDown(@opts) imageData = image.getImageData() quantizer = new @opts.Quantizer() quantizer.initialize(imageData.data, @opts) @allSwatches = quantizer.getQuantizedColors() image.removeCanvas() swatches: => finalSwatches = [] @allSwatches = @allSwatches.sort (a, b) -> b.getPopulation() - a.getPopulation() comparingPopulation = @getComparingPopulation(@allSwatches, @opts.comparingPopulationIndex) for swatch in @allSwatches if @populationPercentage(swatch.getPopulation(), comparingPopulation) > @opts.minPopulation should_be_added = true for final_swatch in finalSwatches if Vibrant.Util.rgbDiff(final_swatch.rgb, swatch.rgb) < @opts.minRgbDiff should_be_added = false break if should_be_added finalSwatches.push swatch finalSwatches populationPercentage: (population, comparingPopulation) -> if comparingPopulation == 0 console.log('comparing population equals 0!') return 0 (population / comparingPopulation) * 100 getComparingPopulation: (swatches, index) -> if swatches.length > index swatches[index].getPopulation() else console.log('there is no swatches with index - ' + index) 100 module.exports.Builder = class Builder constructor: (@src, @opts = {}) -> @opts.filters = util.clone Vibrant.DefaultOpts.filters maxColorCount: (n) -> @opts.colorCount = n @ maxDimension: (d) -> @opts.maxDimension = d @ addFilter: (f) -> if typeof f == 'function' @opts.filters.push f @ removeFilter: (f) -> if (i = @opts.filters.indexOf(f)) > 0 @opts.filters.splice(i) @ clearFilters: -> @opts.filters = [] @ quality: (q) -> @opts.quality = q @ minPopulation: (q) -> @opts.minPopulation = q @ minRgbDiff: (q) -> @opts.minRgbDiff = q @ comparingPopulationIndex: (q) -> @opts.comparingPopulationIndex = q @ useImage: (image) -> @opts.Image = image @ useQuantizer: (quantizer) -> @opts.Quantizer = quantizer @ build: -> if not @v? @v = new Vibrant(@src, @opts) @v getSwatches: (cb) -> @build().getPalette cb getPalette: (cb) -> @build().getPalette cb from: (src) -> new Vibrant(src, @opts) module.exports.Util = util module.exports.Swatch = Swatch module.exports.Quantizer = require('./quantizer/') module.exports.Generator = require('./generator/') module.exports.Filter = require('./filter/')
true
### From Vibrant.js by PI:NAME:<NAME>END_PI Ported to node.js by AKFish Color algorithm class that finds variations on colors in an image. Credits -------- PI:NAME:<NAME>END_PI (http://www.lokeshdhakar.com) - Created ColorThief Google - Palette support library in Android ### Swatch = require('./swatch') util = require('./util') DefaultGenerator = require('./generator').Default Filter = require('./filter') module.exports = class Vibrant @DefaultOpts: colorCount: 16 quality: 5 generator: new DefaultGenerator() Image: null Quantizer: require('./quantizer').MMCQ filters: [] minPopulation: 35 minRgbDiff: 15 comparingPopulationIndex: 1 @from: (src) -> new Builder(src) quantize: require('quantize') _swatches: [] constructor: (@sourceImage, opts = {}) -> @opts = util.defaults(opts, @constructor.DefaultOpts) @generator = @opts.generator getPalette: (cb) -> image = new @opts.Image @sourceImage, (err, image) => if err? then return cb(err) try @_process image, @opts cb null, @swatches() catch error return cb(error) getSwatches: (cb) -> @getPalette cb _process: (image, opts) -> image.scaleDown(@opts) imageData = image.getImageData() quantizer = new @opts.Quantizer() quantizer.initialize(imageData.data, @opts) @allSwatches = quantizer.getQuantizedColors() image.removeCanvas() swatches: => finalSwatches = [] @allSwatches = @allSwatches.sort (a, b) -> b.getPopulation() - a.getPopulation() comparingPopulation = @getComparingPopulation(@allSwatches, @opts.comparingPopulationIndex) for swatch in @allSwatches if @populationPercentage(swatch.getPopulation(), comparingPopulation) > @opts.minPopulation should_be_added = true for final_swatch in finalSwatches if Vibrant.Util.rgbDiff(final_swatch.rgb, swatch.rgb) < @opts.minRgbDiff should_be_added = false break if should_be_added finalSwatches.push swatch finalSwatches populationPercentage: (population, comparingPopulation) -> if comparingPopulation == 0 console.log('comparing population equals 0!') return 0 (population / comparingPopulation) * 100 getComparingPopulation: (swatches, index) -> if swatches.length > index swatches[index].getPopulation() else console.log('there is no swatches with index - ' + index) 100 module.exports.Builder = class Builder constructor: (@src, @opts = {}) -> @opts.filters = util.clone Vibrant.DefaultOpts.filters maxColorCount: (n) -> @opts.colorCount = n @ maxDimension: (d) -> @opts.maxDimension = d @ addFilter: (f) -> if typeof f == 'function' @opts.filters.push f @ removeFilter: (f) -> if (i = @opts.filters.indexOf(f)) > 0 @opts.filters.splice(i) @ clearFilters: -> @opts.filters = [] @ quality: (q) -> @opts.quality = q @ minPopulation: (q) -> @opts.minPopulation = q @ minRgbDiff: (q) -> @opts.minRgbDiff = q @ comparingPopulationIndex: (q) -> @opts.comparingPopulationIndex = q @ useImage: (image) -> @opts.Image = image @ useQuantizer: (quantizer) -> @opts.Quantizer = quantizer @ build: -> if not @v? @v = new Vibrant(@src, @opts) @v getSwatches: (cb) -> @build().getPalette cb getPalette: (cb) -> @build().getPalette cb from: (src) -> new Vibrant(src, @opts) module.exports.Util = util module.exports.Swatch = Swatch module.exports.Quantizer = require('./quantizer/') module.exports.Generator = require('./generator/') module.exports.Filter = require('./filter/')
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999114274978638, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" }, { "context": "ser: if @props.selectedUserId? then @props.users[@props.select...
resources/assets/coffee/react/beatmap-discussions/header.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { BeatmapList } from './beatmap-list' import { BigButton } from 'big-button' import { Nominations } from './nominations' import { Subscribe } from './subscribe' import { UserFilter } from './user-filter' import { BeatmapBasicStats } from 'beatmap-basic-stats' import { BeatmapsetMapping } from 'beatmapset-mapping' import HeaderV4 from 'header-v4' import { PlaymodeTabs } from 'playmode-tabs' import * as React from 'react' import { a, div, h1, h2, p } from 'react-dom-factories' el = React.createElement export class Header extends React.PureComponent componentDidMount: => @updateChart() componentDidUpdate: => @updateChart() componentWillUnmount: => $(window).off '.beatmapDiscussionsOverview' render: => el React.Fragment, null, el HeaderV4, theme: 'beatmapsets' titleAppend: el PlaymodeTabs, currentMode: @props.currentBeatmap.mode beatmaps: @props.beatmaps counts: @props.currentDiscussions.countsByPlaymode div className: 'osu-page' @headerTop() div className: 'osu-page osu-page--small' @headerBottom() headerBottom: => bn = 'beatmap-discussions-header-bottom' div className: bn, div className: "#{bn}__content #{bn}__content--details", div className: "#{bn}__details #{bn}__details--full", el BeatmapsetMapping, beatmapset: @props.beatmapset user: @props.users[@props.beatmapset.user_id] div className: "#{bn}__details", el Subscribe, beatmapset: @props.beatmapset div className: "#{bn}__details", el BigButton, modifiers: ['full'] text: osu.trans('beatmaps.discussions.beatmap_information') icon: 'fas fa-info' props: href: laroute.route('beatmapsets.show', beatmapset: @props.beatmapset.id) div className: "#{bn}__content #{bn}__content--nomination", el Nominations, beatmapset: @props.beatmapset currentDiscussions: @props.currentDiscussions currentUser: @props.currentUser discussions: @props.discussions events: @props.events users: @props.users headerTop: => bn = 'beatmap-discussions-header-top' div className: bn div className: "#{bn}__content" style: backgroundImage: osu.urlPresence(@props.beatmapset.covers.cover) a className: "#{bn}__title-container" href: laroute.route('beatmapsets.show', beatmapset: @props.beatmapset.id) h1 className: "#{bn}__title" @props.beatmapset.title h2 className: "#{bn}__title #{bn}__title--artist" @props.beatmapset.artist div className: "#{bn}__filters" div className: "#{bn}__filter-group" el BeatmapList, beatmapset: @props.beatmapset currentBeatmap: @props.currentBeatmap currentDiscussions: @props.currentDiscussions beatmaps: @props.beatmaps[@props.currentBeatmap.mode] div className: "#{bn}__filter-group #{bn}__filter-group--stats" el UserFilter, ownerId: @props.beatmapset.user_id selectedUser: if @props.selectedUserId? then @props.users[@props.selectedUserId] else null users: @props.discussionStarters div className: "#{bn}__stats" @stats() div null, div ref: 'chartArea', className: "#{bn}__chart" div className: "#{bn}__beatmap-stats", el BeatmapBasicStats, beatmap: @props.currentBeatmap setFilter: (e) => e.preventDefault() $.publish 'beatmapsetDiscussions:update', filter: e.currentTarget.dataset.type stats: => bn = 'counter-box' for type in ['mine', 'mapperNotes', 'resolved', 'pending', 'praises', 'deleted', 'total'] continue if type == 'deleted' && !@props.currentUser.is_admin topClasses = "#{bn} #{bn}--beatmap-discussions #{bn}--#{_.kebabCase(type)}" topClasses += ' js-active' if @props.mode != 'events' && @props.currentFilter == type total = 0 for own _mode, discussions of @props.currentDiscussions.byFilter[type] total += _.size(discussions) a key: type href: BeatmapDiscussionHelper.url filter: type beatmapsetId: @props.beatmapset.id beatmapId: @props.currentBeatmap.id mode: @props.mode className: topClasses 'data-type': type onClick: @setFilter div className: "#{bn}__content" div className: "#{bn}__title" osu.trans("beatmaps.discussions.stats.#{_.snakeCase(type)}") div className: "#{bn}__count" total div className: "#{bn}__line" updateChart: => if !@_chart? area = @refs.chartArea length = @props.currentBeatmap.total_length * 1000 @_chart = new BeatmapDiscussionsChart(area, length) $(window).on 'throttled-resize.beatmapDiscussionsOverview', @_chart.resize @_chart.loadData _.values(@props.currentDiscussions.byFilter[@props.currentFilter].timeline)
178153
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { BeatmapList } from './beatmap-list' import { BigButton } from 'big-button' import { Nominations } from './nominations' import { Subscribe } from './subscribe' import { UserFilter } from './user-filter' import { BeatmapBasicStats } from 'beatmap-basic-stats' import { BeatmapsetMapping } from 'beatmapset-mapping' import HeaderV4 from 'header-v4' import { PlaymodeTabs } from 'playmode-tabs' import * as React from 'react' import { a, div, h1, h2, p } from 'react-dom-factories' el = React.createElement export class Header extends React.PureComponent componentDidMount: => @updateChart() componentDidUpdate: => @updateChart() componentWillUnmount: => $(window).off '.beatmapDiscussionsOverview' render: => el React.Fragment, null, el HeaderV4, theme: 'beatmapsets' titleAppend: el PlaymodeTabs, currentMode: @props.currentBeatmap.mode beatmaps: @props.beatmaps counts: @props.currentDiscussions.countsByPlaymode div className: 'osu-page' @headerTop() div className: 'osu-page osu-page--small' @headerBottom() headerBottom: => bn = 'beatmap-discussions-header-bottom' div className: bn, div className: "#{bn}__content #{bn}__content--details", div className: "#{bn}__details #{bn}__details--full", el BeatmapsetMapping, beatmapset: @props.beatmapset user: @props.users[@props.beatmapset.user_id] div className: "#{bn}__details", el Subscribe, beatmapset: @props.beatmapset div className: "#{bn}__details", el BigButton, modifiers: ['full'] text: osu.trans('beatmaps.discussions.beatmap_information') icon: 'fas fa-info' props: href: laroute.route('beatmapsets.show', beatmapset: @props.beatmapset.id) div className: "#{bn}__content #{bn}__content--nomination", el Nominations, beatmapset: @props.beatmapset currentDiscussions: @props.currentDiscussions currentUser: @props.currentUser discussions: @props.discussions events: @props.events users: @props.users headerTop: => bn = 'beatmap-discussions-header-top' div className: bn div className: "#{bn}__content" style: backgroundImage: osu.urlPresence(@props.beatmapset.covers.cover) a className: "#{bn}__title-container" href: laroute.route('beatmapsets.show', beatmapset: @props.beatmapset.id) h1 className: "#{bn}__title" @props.beatmapset.title h2 className: "#{bn}__title #{bn}__title--artist" @props.beatmapset.artist div className: "#{bn}__filters" div className: "#{bn}__filter-group" el BeatmapList, beatmapset: @props.beatmapset currentBeatmap: @props.currentBeatmap currentDiscussions: @props.currentDiscussions beatmaps: @props.beatmaps[@props.currentBeatmap.mode] div className: "#{bn}__filter-group #{bn}__filter-group--stats" el UserFilter, ownerId: @props.beatmapset.user_id selectedUser: if @props.selectedUserId? then @props.users[@props.selectedUserId] else null users: @props.discussionStarters div className: "#{bn}__stats" @stats() div null, div ref: 'chartArea', className: "#{bn}__chart" div className: "#{bn}__beatmap-stats", el BeatmapBasicStats, beatmap: @props.currentBeatmap setFilter: (e) => e.preventDefault() $.publish 'beatmapsetDiscussions:update', filter: e.currentTarget.dataset.type stats: => bn = 'counter-box' for type in ['mine', 'mapperNotes', 'resolved', 'pending', 'praises', 'deleted', 'total'] continue if type == 'deleted' && !@props.currentUser.is_admin topClasses = "#{bn} #{bn}--beatmap-discussions #{bn}--#{_.kebabCase(type)}" topClasses += ' js-active' if @props.mode != 'events' && @props.currentFilter == type total = 0 for own _mode, discussions of @props.currentDiscussions.byFilter[type] total += _.size(discussions) a key: type href: BeatmapDiscussionHelper.url filter: type beatmapsetId: @props.beatmapset.id beatmapId: @props.currentBeatmap.id mode: @props.mode className: topClasses 'data-type': type onClick: @setFilter div className: "#{bn}__content" div className: "#{bn}__title" osu.trans("beatmaps.discussions.stats.#{_.snakeCase(type)}") div className: "#{bn}__count" total div className: "#{bn}__line" updateChart: => if !@_chart? area = @refs.chartArea length = @props.currentBeatmap.total_length * 1000 @_chart = new BeatmapDiscussionsChart(area, length) $(window).on 'throttled-resize.beatmapDiscussionsOverview', @_chart.resize @_chart.loadData _.values(@props.currentDiscussions.byFilter[@props.currentFilter].timeline)
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { BeatmapList } from './beatmap-list' import { BigButton } from 'big-button' import { Nominations } from './nominations' import { Subscribe } from './subscribe' import { UserFilter } from './user-filter' import { BeatmapBasicStats } from 'beatmap-basic-stats' import { BeatmapsetMapping } from 'beatmapset-mapping' import HeaderV4 from 'header-v4' import { PlaymodeTabs } from 'playmode-tabs' import * as React from 'react' import { a, div, h1, h2, p } from 'react-dom-factories' el = React.createElement export class Header extends React.PureComponent componentDidMount: => @updateChart() componentDidUpdate: => @updateChart() componentWillUnmount: => $(window).off '.beatmapDiscussionsOverview' render: => el React.Fragment, null, el HeaderV4, theme: 'beatmapsets' titleAppend: el PlaymodeTabs, currentMode: @props.currentBeatmap.mode beatmaps: @props.beatmaps counts: @props.currentDiscussions.countsByPlaymode div className: 'osu-page' @headerTop() div className: 'osu-page osu-page--small' @headerBottom() headerBottom: => bn = 'beatmap-discussions-header-bottom' div className: bn, div className: "#{bn}__content #{bn}__content--details", div className: "#{bn}__details #{bn}__details--full", el BeatmapsetMapping, beatmapset: @props.beatmapset user: @props.users[@props.beatmapset.user_id] div className: "#{bn}__details", el Subscribe, beatmapset: @props.beatmapset div className: "#{bn}__details", el BigButton, modifiers: ['full'] text: osu.trans('beatmaps.discussions.beatmap_information') icon: 'fas fa-info' props: href: laroute.route('beatmapsets.show', beatmapset: @props.beatmapset.id) div className: "#{bn}__content #{bn}__content--nomination", el Nominations, beatmapset: @props.beatmapset currentDiscussions: @props.currentDiscussions currentUser: @props.currentUser discussions: @props.discussions events: @props.events users: @props.users headerTop: => bn = 'beatmap-discussions-header-top' div className: bn div className: "#{bn}__content" style: backgroundImage: osu.urlPresence(@props.beatmapset.covers.cover) a className: "#{bn}__title-container" href: laroute.route('beatmapsets.show', beatmapset: @props.beatmapset.id) h1 className: "#{bn}__title" @props.beatmapset.title h2 className: "#{bn}__title #{bn}__title--artist" @props.beatmapset.artist div className: "#{bn}__filters" div className: "#{bn}__filter-group" el BeatmapList, beatmapset: @props.beatmapset currentBeatmap: @props.currentBeatmap currentDiscussions: @props.currentDiscussions beatmaps: @props.beatmaps[@props.currentBeatmap.mode] div className: "#{bn}__filter-group #{bn}__filter-group--stats" el UserFilter, ownerId: @props.beatmapset.user_id selectedUser: if @props.selectedUserId? then @props.users[@props.selectedUserId] else null users: @props.discussionStarters div className: "#{bn}__stats" @stats() div null, div ref: 'chartArea', className: "#{bn}__chart" div className: "#{bn}__beatmap-stats", el BeatmapBasicStats, beatmap: @props.currentBeatmap setFilter: (e) => e.preventDefault() $.publish 'beatmapsetDiscussions:update', filter: e.currentTarget.dataset.type stats: => bn = 'counter-box' for type in ['mine', 'mapperNotes', 'resolved', 'pending', 'praises', 'deleted', 'total'] continue if type == 'deleted' && !@props.currentUser.is_admin topClasses = "#{bn} #{bn}--beatmap-discussions #{bn}--#{_.kebabCase(type)}" topClasses += ' js-active' if @props.mode != 'events' && @props.currentFilter == type total = 0 for own _mode, discussions of @props.currentDiscussions.byFilter[type] total += _.size(discussions) a key: type href: BeatmapDiscussionHelper.url filter: type beatmapsetId: @props.beatmapset.id beatmapId: @props.currentBeatmap.id mode: @props.mode className: topClasses 'data-type': type onClick: @setFilter div className: "#{bn}__content" div className: "#{bn}__title" osu.trans("beatmaps.discussions.stats.#{_.snakeCase(type)}") div className: "#{bn}__count" total div className: "#{bn}__line" updateChart: => if !@_chart? area = @refs.chartArea length = @props.currentBeatmap.total_length * 1000 @_chart = new BeatmapDiscussionsChart(area, length) $(window).on 'throttled-resize.beatmapDiscussionsOverview', @_chart.resize @_chart.loadData _.values(@props.currentDiscussions.byFilter[@props.currentFilter].timeline)
[ { "context": "ookmarklet/patterns/squairy_light.png\"\n author: \"Tia Newbury\"\n download: \"/patterns/squairy_light.zip\"\n imag", "end": 251, "score": 0.999897837638855, "start": 240, "tag": "NAME", "value": "Tia Newbury" }, { "context": "ookmarklet/patterns/binding_light.png\"...
subtlepatterns.com/subtlepatterns.coffee
fengyiyi/subtle-patterns-bookmarklet
27
window.SUBTLEPATTERNS = [ link: "http://subtlepatterns.com/squairy/" description: "Super tiny dots and all sorts of great stuff." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/squairy_light.png" author: "Tia Newbury" download: "/patterns/squairy_light.zip" image: "/patterns/squairy_light.png" title: "Squairy" categories: ["light"] , link: "http://subtlepatterns.com/binding-light/" description: "Light gray version of the Binding pattern. A bit like fabric." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/binding_light.png" author: "Tia Newbury" download: "/patterns/binding_light.zip" image: "/patterns/binding_light.png" title: "Binding light" categories: ["light"] , link: "http://subtlepatterns.com/binding-dark/" description: "This works great as-is, or you can tone it down even more." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/binding_dark.png" author: "Tia Newbury" download: "/patterns/binding_dark.zip" image: "/patterns/binding_dark.png" title: "Binding dark" categories: ["dark"] , link: "http://subtlepatterns.com/ps-neutral/" description: "This one is so simple, yet so good. And you know it. Has to be in the collection." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ps_neutral.png" author: "<a href=\"http://www.gluszczenko.com\" target=\"_blank\">Gluszczenko</a>" download: "/patterns/ps_neutral.zip" image: "/patterns/ps_neutral.png" title: "PS Neutral" categories: ["light"] , link: "http://subtlepatterns.com/wave-grind/" description: "Submitted by DomainsInfo – wtf, right? But hey, a free pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wavegrid.png" author: "<a href=\"http://www.domainsinfo.org/\" target=\"_blank\">DomainsInfo</a>" download: "/patterns/wavegrid.zip" image: "/patterns/wavegrid.png" title: "Wave Grind" categories: ["light"] , link: "http://subtlepatterns.com/textured-paper/" description: "You know I love paper patterns. Here is one from Stephen. Say thank you!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/textured_paper.png" author: "<a href=\"http://stephen.io\" target=\"_blank\">Stephen Gilbert</a>" download: "/patterns/textured_paper.zip" image: "/patterns/textured_paper.png" title: "Textured Paper" categories: ["light", "paper"] , link: "http://subtlepatterns.com/grey-washed-wall/" description: "This is a semi-dark pattern, sort of linen-y." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grey_wash_wall.png" author: "<a href=\"http://www.sagive.co.il\" target=\"_blank\">Sagive SEO</a>" download: "/patterns/grey_wash_wall.zip" image: "/patterns/grey_wash_wall.png" title: "Grey Washed Wall" categories: ["dark", "linen"] , link: "http://subtlepatterns.com/p6/" description: "And finally, number 6. Enjoy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/p6.png" author: "<a href=\"http://www.epictextures.com/\" target=\"_blank\">Dima Shiper</a>" download: "/patterns/p6.zip" image: "/patterns/p6.png" title: "P6" categories: ["light"] , link: "http://subtlepatterns.com/p5/" description: "Number five from the same submitter, makes my job easy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/p5.png" author: "<a href=\"http://www.epictextures.com/\" target=\"_blank\">Dima Shiper</a>" download: "/patterns/p5.zip" image: "/patterns/p5.png" title: "P5" categories: ["light"] , link: "http://subtlepatterns.com/p4/" description: "I skipped number 3, cause it wasn’t all that great. Sorry." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/p4.png" author: "<a href=\"http://www.epictextures.com/\" target=\"_blank\">Dima Shiper</a>" download: "/patterns/p4.zip" image: "/patterns/p4.png" title: "P4" categories: ["light"] , image_size: "493B" link: "http://subtlepatterns.com/escheresque-dark/" description: "A comeback for you, the populare Escheresque now in black." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/escheresque_ste.png" author: "Ste Patten" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/escheresque_ste.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/escheresque_ste.png" title: "Escheresque dark" categories: ["dark"] image_dimensions: "46x29" , image_size: "278B" link: "http://subtlepatterns.com/%d0%b2lack-lozenge/" description: "Not the most subtle one, but a nice pattern still." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_lozenge.png" author: "<a href=\"http://www.listvetra.ru\" target=\"_blank\">Listvetra.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_lozenge.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_lozenge.png" title: "Вlack lozenge" categories: ["dark"] image_dimensions: "38x38" , image_size: "3K" link: "http://subtlepatterns.com/kinda-jean/" description: "A nice one indeed, but I got a feeling we have it already? If you spot a copy, let me know on Twitter ." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/kindajean.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Graphiste.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/kindajean.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/kindajean.png" title: "Kinda Jean" categories: ["light"] image_dimensions: "147x147" , image_size: "72K" link: "http://subtlepatterns.com/paper-fibers/" description: "Just what the name says, paper fibers. Always good to have." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper_fibers.png" author: "<a href=\"http://about.me/heliodor\" target=\"_blank\">Heliodor jalba.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_fibers.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_fibers.png" title: "Paper Fibers" categories: ["light"] image_dimensions: "410x410" , image_size: "128B" link: "http://subtlepatterns.com/dark-fish-skin/" description: "It almost looks a bit blurry, but then again so are fishes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_fish_skin.png" author: "<a href=\"http://www.petrsulc.com\" target=\"_blank\">Petr Šulc.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_fish_skin.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_fish_skin.png" title: "Dark Fish Skin" categories: ["dark"] image_dimensions: "6x12" , image_size: "600B" link: "http://subtlepatterns.com/maze-white/" description: "Just like the black maze, only in light gray. Duh." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pw_maze_white.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Peax.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pw_maze_white.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pw_maze_white.png" title: "Maze white" categories: ["light"] image_dimensions: "46x23" , image_size: "600B" link: "http://subtlepatterns.com/maze-black/" description: "Classy little maze for you, in two colors even." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pw_maze_black.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Peax.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pw_maze_black.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pw_maze_black.png" title: "Maze black" categories: ["dark"] image_dimensions: "46x23" , image_size: "137B" link: "http://subtlepatterns.com/satin-weave/" description: "Super simple but very nice indeed. Gray with vertical stripes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/satinweave.png" author: "<a href=\"http://www.merxplat.com\" target=\"_blank\">Merrin Macleod.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/satinweave.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/satinweave.png" title: "Satin weave" categories: ["light"] image_dimensions: "24x12" , image_size: "266B" link: "http://subtlepatterns.com/ecailles/" description: "Almost like little fish shells, or dragon skin." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ecailles.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Graphiste.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ecailles.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ecailles.png" title: "Ecailles" categories: ["light"] image_dimensions: "48x20" , image_size: "82K" link: "http://subtlepatterns.com/subtle-grunge/" description: "A heavy hitter at 400x400px, but lovely still." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_grunge.png" author: "<a href=\"http://breezi.com\" target=\"_blank\">Breezi.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_grunge.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_grunge.png" title: "Subtle grunge" categories: ["light"] image_dimensions: "400x400" , image_size: "11K" link: "http://subtlepatterns.com/honey-im-subtle/" description: "First off in 2013, a mid-gray hexagon pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/honey_im_subtle.png" author: "<a href=\"http://www.blof.dk\" target=\"_blank\">Alex M. Balling.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/honey_im_subtle.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/honey_im_subtle.png" title: "Honey I’m subtle" categories: ["hexagon", "light"] image_dimensions: "179x132" , image_size: "13K" link: "http://subtlepatterns.com/grey-jean/" description: "Yummy, this is one good looking pattern. Grab it!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gray_jean.png" author: "<a href=\"http://mr.pn\" target=\"_blank\">Omur Uluask.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gray_jean.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gray_jean.png" title: "Grey Jean" categories: ["light"] image_dimensions: "150x150" , image_size: "75K" link: "http://subtlepatterns.com/lined-paper-2/" description: "I know there already is one here, but shit – this is sexy!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/linedpaper.png" author: "<a href=\"http://www.tight.no\" target=\"_blank\">Gjermund Gustavsen.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/linedpaper.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/linedpaper.png" title: "Lined paper" categories: ["light"] image_dimensions: "412x300" , image_size: "39K" link: "http://subtlepatterns.com/blach-orchid/" description: "Blach is the new Black." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/blackorchid.png" author: "<a href=\"http://www.hybridixstudio.com\" target=\"_blank\">Hybridixstudio.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blackorchid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blackorchid.png" title: "Blach Orchid" categories: ["dark"] image_dimensions: "300x300" , image_size: "10K" link: "http://subtlepatterns.com/white-wall-2/" description: "A new one called white wall, not by me this time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_wall2.png" author: "<a href=\"https://corabbit.com\" target=\"_blank\">Yuji Honzawa.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_wall2.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_wall2.png" title: "White wall 2" categories: ["light"] image_dimensions: "150x150" , image_size: "279B" link: "http://subtlepatterns.com/diagonales-decalees/" description: "Sounds French. Some 3D square diagonals, that’s all you need to know." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagonales_decalees.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Graphiste.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonales_decalees.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonales_decalees.png" title: "Diagonales decalées" categories: ["light"] image_dimensions: "144x48" , image_size: "12K" link: "http://subtlepatterns.com/cream-paper/" description: "Submitted in a cream color, but you know how I like it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/creampaper.png" author: "<a href=\"http://www.strick9design.com\" target=\"_blank\">Devin Holmes.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/creampaper.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/creampaper.png" title: "Cream paper" categories: ["light"] image_dimensions: "158x144" , image_size: "19K" link: "http://subtlepatterns.com/debut-dark/" description: "Same classic 45 degree pattern with class, dark version." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/debut_dark.png" author: "<a href=\"http://lukemcdonald.com\" target=\"_blank\">Luke McDonald.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/debut_dark.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/debut_dark.png" title: "Debut dark" categories: ["dark"] image_dimensions: "200x200" , image_size: "18K" link: "http://subtlepatterns.com/debut-light/" description: "Classic 45 degree pattern with class, light version." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/debut_light.png" author: "<a href=\"http://lukemcdonald.com\" target=\"_blank\">Luke McDonald.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/debut_light.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/debut_light.png" title: "Debut light" categories: ["light"] image_dimensions: "200x200" , image_size: "9K" link: "http://subtlepatterns.com/twinkle-twinkle/" description: "A very dark spotted twinkle pattern for you twinkle needs." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/twinkle_twinkle.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\">Badhon Ebrahim.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/twinkle_twinkle.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/twinkle_twinkle.png" title: "Twinkle Twinkle" categories: ["dark"] image_dimensions: "360x300" , image_size: "2K" link: "http://subtlepatterns.com/tapestry/" description: "Tiny and subtle. What’s not to love?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tapestry_pattern.png" author: "<a href=\"http://www.pixeden.com\" target=\"_blank\">Pixeden</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tapestry_pattern.zip" image: "http://subtlepatterns.com/patterns/tapestry_pattern.png" title: "Tapestry" categories: ["light"] image_dimensions: "72x61" , image_size: "3K" link: "http://subtlepatterns.com/psychedelic/" description: "Geometric triangles seem to be quite hot these days." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/psychedelic_pattern.png" author: "<a href=\"http://www.pixeden.com\" target=\"_blank\">Pixeden</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/psychedelic_pattern.zip" image: "http://subtlepatterns.com/patterns/psychedelic_pattern.png" title: "Psychedelic" categories: ["light"] image_dimensions: "84x72" , image_size: "2K" link: "http://subtlepatterns.com/triangles-2/" description: "Sharp but soft triangles in light shades of gray." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/triangles_pattern.png" author: "<a href=\"http://www.pixeden.com\" target=\"_blank\">Pixeden</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/triangles_pattern.zip" image: "http://subtlepatterns.com/patterns/triangles_pattern.png" title: "Triangles" categories: ["light"] image_dimensions: "72x72" , image_size: "125B" link: "http://subtlepatterns.com/flower-trail/" description: "Sharp pixel pattern, just like the good old days." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/flowertrail.png" author: "Paridhi" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/flowertrail.zip" image: "http://subtlepatterns.com/patterns/flowertrail.png" title: "Flower Trail" categories: ["flower", "light"] image_dimensions: "16x16" , image_size: "41K" link: "http://subtlepatterns.com/scribble-light/" description: "A bit like smudged paint or some sort of steel, here is scribble light." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/scribble_light.png" author: "<a href=\"http://thelovelyfox.com\" target=\"_blank\">Tegan Male</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/scribble_light.zip" image: "http://subtlepatterns.com/patterns/scribble_light.png" title: "Scribble Light" categories: ["light"] image_dimensions: "304x306" , image_size: "76K" link: "http://subtlepatterns.com/clean-textile/" description: "A nice light textile pattern for your kit." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/clean_textile.png" author: "N8rx" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/clean_textile.zip" image: "http://subtlepatterns.com/patterns/clean_textile.png" title: "Clean Textile" categories: ["light", "textile"] image_dimensions: "420x420" , image_size: "11K" link: "http://subtlepatterns.com/gplay/" description: "A playful triangle pattern with different shades of gray." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gplaypattern.png" author: "<a href=\"http://dhesign.com\" target=\"_blank\">Dimitrie Hoekstra.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gplaypattern.zip" image: "http://subtlepatterns.com/patterns/gplaypattern.png" title: "GPlay" categories: ["light"] image_dimensions: "188x178" , image_size: "235B" link: "http://subtlepatterns.com/weave/" description: "Medium gray pattern with small strokes to give a weave effect." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/weave.png" author: "<a href=\"http://wellterned.com\" target=\"_blank\">Catherine.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/weave.zip" image: "http://subtlepatterns.com/patterns/weave.png" title: "Weave" categories: ["light"] image_dimensions: "35x31" , image_size: "165B" link: "http://subtlepatterns.com/embossed-paper/" description: "One more from Badhon, sharp horizontal lines making an embossed paper feeling." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/embossed_paper.png" author: "<a href=\"http://graphicriver.net/user/graphcoder?ref=graphcoder\" target=\"_blank\">Badhon Ebrahim.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/embossed_paper.zip" image: "http://subtlepatterns.com/patterns/embossed_paper.png" title: "Embossed Paper" categories: ["light"] image_dimensions: "8x10" , image_size: "176B" link: "http://subtlepatterns.com/graphcoders-lil-fiber/" description: "Tiny little fibers making a soft and sweet look." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/lil_fiber.png" author: "<a href=\"http://graphicriver.net/user/graphcoder?ref=graphcoder\" target=\"_blank\">Badhon Ebrahim.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/lil_fiber.zip" image: "http://subtlepatterns.com/patterns/lil_fiber.png" title: "Graphcoders Lil Fiber" categories: ["light"] image_dimensions: "21x35" , image_size: "6K" link: "http://subtlepatterns.com/white-tiles/" description: "A nice and simple white rotated tile pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_tiles.png" author: "<a href=\"http://www.anotherone.fr/\" target=\"_blank\">Another One.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_tiles.zip" image: "http://subtlepatterns.com/patterns/white_tiles.png" title: "White tiles" categories: ["light"] image_dimensions: "800x250" , image_size: "33K" link: "http://subtlepatterns.com/tex2res5/" description: "Number 5 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res5.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\">Janos Koos.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res5.zip" image: "http://subtlepatterns.com/patterns/tex2res5.png" title: "Tex2res5" categories: ["light"] image_dimensions: "500x500" , image_size: "92K" link: "http://subtlepatterns.com/tex2res3/" description: "Number 4 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res3.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\">Janos Koos.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res3.zip" image: "http://subtlepatterns.com/patterns/tex2res3.png" title: "Tex2res3" categories: ["light"] image_dimensions: "500x500" , image_size: "94K" link: "http://subtlepatterns.com/tex2res1/" description: "Number 3 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res1.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\">Janos Koos.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res1.zip" image: "http://subtlepatterns.com/patterns/tex2res1.png" title: "Tex2res1" categories: ["light"] image_dimensions: "500x500" , image_size: "130K" link: "http://subtlepatterns.com/tex2res2/" description: "Number 2 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res2.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\">Janos Koos.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res2.zip" image: "http://subtlepatterns.com/patterns/tex2res2.png" title: "Tex2res2" categories: ["light"] image_dimensions: "500x500" , image_size: "151K" link: "http://subtlepatterns.com/tex2res4/" description: "Number 1 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res4.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\">Janos Koos.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res4.zip" image: "http://subtlepatterns.com/patterns/tex2res4.png" title: "Tex2res4" categories: ["dark"] image_dimensions: "500x500" , image_size: "813B" link: "http://subtlepatterns.com/arches/" description: "One more in the line of patterns inspired by the Japanese/asian styles. Smooth." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/arches.png" author: "<a href=\"http://www.webdesigncreare.co.uk/\" target=\"_blank\">Kim Ruddock.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/arches.zip" image: "http://subtlepatterns.com/patterns/arches.png" title: "Arches" categories: [] image_dimensions: "103x23" , image_size: "141B" link: "http://subtlepatterns.com/shine-caro/" description: "It’s like shine dotted’s sister, only rotated 45 degrees." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/shinecaro.png" author: "<a href=\"http://www.mediumidee.de\" target=\"_blank\">mediumidee.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shinecaro.zip" image: "http://subtlepatterns.com/patterns/shinecaro.png" title: "Shine Caro" categories: ["light", "shiny"] image_dimensions: "9x9" , image_size: "97B" link: "http://subtlepatterns.com/shine-dotted/" description: "Tiny shiny dots all over your screen." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/shinedotted.png" author: "<a href=\"http://www.mediumidee.de\" target=\"_blank\">mediumidee.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shinedotted.zip" image: "http://subtlepatterns.com/patterns/shinedotted.png" title: "Shine dotted" categories: ["dotted", "light"] image_dimensions: "6x5" , image_size: "19K" link: "http://subtlepatterns.com/worn-dots/" description: "These dots are already worn for you, so you don’t have to." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/worn_dots.png" author: "<a href=\"http://mattmcdaniel.me\" target=\"_blank\">Matt McDaniel.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/worn_dots.zip" image: "http://subtlepatterns.com/patterns/worn_dots.png" title: "Worn Dots" categories: ["dots", "light"] image_dimensions: "200x200" , image_size: "24K" link: "http://subtlepatterns.com/light-mesh/" description: "Love me some light mesh on a Monday. Sharp." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/lghtmesh.png" author: "<a href=\"http://dribbble.com/bastienwilmotte\" target=\"_blank\">Wilmotte Bastien.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/lghtmesh.zip" image: "http://subtlepatterns.com/patterns/lghtmesh.png" title: "Light Mesh" categories: ["light"] image_dimensions: "256x256" , image_size: "13K" link: "http://subtlepatterns.com/hexellence/" description: "Detailed but still subtle and quite original. Lovely gray shades." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/hexellence.png" author: "<a href=\"http://www.webdesigncreare.co.uk\" target=\"_blank\">Kim Ruddock</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/hexellence.zip" image: "http://subtlepatterns.com/patterns/hexellence.png" title: "Hexellence" categories: ["geometric", "light"] image_dimensions: "150x173" , image_size: "21K" link: "http://subtlepatterns.com/dark-tire/" description: "Dark, crisp and subtle. Tiny black lines on top of some noise." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_Tire.png" author: "<a href=\"http://dribbble.com/bastienwilmotte\" target=\"_blank\">Wilmotte Bastien.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_Tire.zip" image: "http://subtlepatterns.com/patterns/dark_Tire.png" title: "Dark Tire" categories: ["dark", "tire"] image_dimensions: "250x250" , image_size: "6K" link: "http://subtlepatterns.com/first-aid-kit/" description: "No, not the band but the pattern. Simple squares in gray tones, of course." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/first_aid_kit.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/first_aid_kit.zip" image: "http://subtlepatterns.com/patterns/first_aid_kit.png" title: "First Aid Kit" categories: ["light"] image_dimensions: "99x99" , image_size: "327B" link: "http://subtlepatterns.com/wide-rectangles/" description: "Simple wide squares with a small indent. Fit’s all." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wide_rectangles.png" author: "<a href=\"http://www.petrsulc.com\" target=\"_blank\">Petr Šulc.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wide_rectangles.zip" image: "http://subtlepatterns.com/patterns/wide_rectangles.png" title: "Wide rectangles" categories: ["light"] image_dimensions: "32x14" , image_size: "69K" link: "http://subtlepatterns.com/french-stucco/" description: "Fabric-ish patterns are close to my heart. French Stucco to the rescue." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/frenchstucco.png" author: "<a href=\"http://cwbuecheler.com/\" target=\"_blank\">Christopher Buecheler.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/frenchstucco.zip" image: "http://subtlepatterns.com/patterns/frenchstucco.png" title: "French Stucco" categories: ["light"] image_dimensions: "400x355" , image_size: "13K" link: "http://subtlepatterns.com/light-wool/" description: "Submitted as a black pattern, I made it light and a few steps more subtle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_wool.png" author: "<a href=\"http://www.tall.me.uk\" target=\"_blank\">Andy.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_wool.zip" image: "http://subtlepatterns.com/patterns/light_wool.png" title: "Light wool" categories: ["light", "wool"] image_dimensions: "190x191" , image_size: "48K" link: "http://subtlepatterns.com/gradient-squares/" description: "It’s big, it’s gradient – and they are square." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gradient_squares.png" author: "<a href=\"http://www.brankic1979.com\" target=\"_blank\">Brankic1979.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gradient_squares.zip" image: "http://subtlepatterns.com/patterns/gradient_squares.png" title: "Gradient Squares" categories: ["gradient", "light", "square"] image_dimensions: "202x202" , image_size: "38K" link: "http://subtlepatterns.com/rough-diagonal/" description: "The classic 45 degree diagonal line pattern, done right." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rough_diagonal.png" author: "<a href=\"http://jorickvanhees.com\" target=\"_blank\">Jorick van Hees.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rough_diagonal.zip" image: "http://subtlepatterns.com/patterns/rough_diagonal.png" title: "Rough diagonal" categories: ["diagonal", "light"] image_dimensions: "256x256" , image_size: "495B" link: "http://subtlepatterns.com/kuji/" description: "An interesting and original pattern from Josh." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/kuji.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\">Josh Green.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/kuji.zip" image: "http://subtlepatterns.com/patterns/kuji.png" title: "Kuji" categories: ["kuji", "light"] image_dimensions: "30x30" , image_size: "241B" link: "http://subtlepatterns.com/little-triangles/" description: "The basic shapes never get old. Simple triangle pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/little_triangles.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/little_triangles.zip" image: "http://subtlepatterns.com/patterns/little_triangles.png" title: "Little triangles" categories: ["light", "triangle"] image_dimensions: "10x11" , image_size: "186B" link: "http://subtlepatterns.com/diamond-eyes/" description: "Everyone loves a diamond, right? Make your site sparkle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/daimond_eyes.png" author: "<a href=\"http://ajtroxell.com\" target=\"_blank\">AJ Troxell.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/daimond_eyes.zip" image: "http://subtlepatterns.com/patterns/daimond_eyes.png" title: "Diamond Eyes" categories: ["diamond", "light"] image_dimensions: "33x25" , image_size: "8K" link: "http://subtlepatterns.com/arabesque/" description: "Intricate pattern with arab influences." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/arab_tile.png" author: "<a href=\"http://www.twitter.com/davidsancar\" target=\"_blank\">David Sanchez.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/arab_tile.zip" image: "http://subtlepatterns.com/patterns/arab_tile.png" title: "Arabesque" categories: ["arab", "light"] image_dimensions: "110x110" , image_size: "314B" link: "http://subtlepatterns.com/white-wave/" description: "Light and tiny just the way you like it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_wave.png" author: "Rohit Arun Rao" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_wave.zip" image: "http://subtlepatterns.com/patterns/white_wave.png" title: "White Wave" categories: ["light", "wave"] image_dimensions: "23x12" , image_size: "1K" link: "http://subtlepatterns.com/diagonal-striped-brick/" description: "Might not be super subtle, but quite original in it’s form." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagonal_striped_brick.png" author: "Alex Smith" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonal_striped_brick.zip" image: "http://subtlepatterns.com/patterns/diagonal_striped_brick.png" title: "Diagonal Striped Brick" categories: ["light"] image_dimensions: "150x150" , image_size: "217K" link: "http://subtlepatterns.com/purty-wood/" description: "You know you love wood patterns, so here’s one more." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/purty_wood.png" author: "<a href=\"http://www.purtypixels.com\" target=\"_blank\">Richard Tabor.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/purty_wood.zip" image: "http://subtlepatterns.com/patterns/purty_wood.png" title: "Purty Wood" categories: ["light", "wood"] image_dimensions: "400x400" , image_size: "412B" link: "http://subtlepatterns.com/vaio-pattern/" description: "I’m guessing this is related to the Sony Vaio? It’s a nice pattern no matter where it’s from." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/vaio_hard_edge.png" author: "<a href=\"http://www.zigzain.com\" target=\"_blank\">Zigzain.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/vaio_hard_edge.zip" image: "http://subtlepatterns.com/patterns/vaio_hard_edge.png" title: "Vaio" categories: ["light", "sony", "vaio"] image_dimensions: "37x28" , image_size: "123B" link: "http://subtlepatterns.com/stacked-circles/" description: "A simple circle. That’s all it takes. This one is even transparent, for those who like that." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/stacked_circles.png" author: "<a href=\"http://www.960development.com\" target=\"_blank\">Saqib.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stacked_circles.zip" image: "http://subtlepatterns.com/patterns/stacked_circles.png" title: "Stacked Circles" categories: ["circle", "light", "tiny"] image_dimensions: "9x9" , image_size: "102B" link: "http://subtlepatterns.com/outlets/" description: "Just 4x8px, but still so stylish!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/outlets.png" author: "<a href=\"http://michalchovanec.com\" target=\"_blank\">Michal Chovanec.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/outlets.zip" image: "http://subtlepatterns.com/patterns/outlets.png" title: "Outlets" categories: ["dark", "tiny"] image_dimensions: "4x8" , image_size: "41K" link: "http://subtlepatterns.com/light-sketch/" description: "Nice and gray, just the way I like it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/furley_bg.png" author: "<a href=\"http://dankruse.com\" target=\"_blank\">Dan Kruse.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/furley_bg.zip" image: "http://subtlepatterns.com/patterns/furley_bg.png" title: "Light Sketch" categories: ["light"] image_dimensions: "600x600" , image_size: "126B" link: "http://subtlepatterns.com/tasky/" description: "Your eyes can trip a bit from looking at this – use it wisely." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tasky_pattern.png" author: "<a href=\"http://michalchovanec.com\" target=\"_blank\">Michal Chovanec.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tasky_pattern.zip" image: "http://subtlepatterns.com/patterns/tasky_pattern.png" title: "Tasky" categories: ["dark", "zigzag"] image_dimensions: "10x10" , image_size: "58K" link: "http://subtlepatterns.com/pinstriped-suit/" description: "Just like your old suit, all striped and smooth." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pinstriped_suit.png" author: "<a href=\"http://www.alexberkowitz.com\" target=\"_blank\">Alex Berkowitz.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pinstriped_suit.zip" image: "http://subtlepatterns.com/patterns/pinstriped_suit.png" title: "Pinstriped Suit" categories: ["dark", "suit"] image_dimensions: "400x333" , image_size: "240B" link: "http://subtlepatterns.com/blizzard/" description: "This is so subtle I hope you can see it! Tweak at will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/blizzard.png" author: "<a href=\"http://www.alexandrenaud.fr\" target=\"_blank\">Alexandre Naud.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blizzard.zip" image: "http://subtlepatterns.com/patterns/blizzard.png" title: "Blizzard" categories: ["blizzard", "light"] image_dimensions: "25x25" , image_size: "1K" link: "http://subtlepatterns.com/bo-play/" description: "Inspired by the B&O Play , I had to make this pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/bo_play_pattern.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bo_play_pattern.zip" image: "http://subtlepatterns.com/patterns/bo_play_pattern.png" title: "BO Play" categories: ["bo", "carbon", "dark", "play"] image_dimensions: "42x22" , image_size: "152K" link: "http://subtlepatterns.com/farmer/" description: "Farmer could be some sort of fabric pattern, with a hint of green." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/farmer.png" author: "<a href=\"http://fabianschultz.de\" target=\"_blank\">Fabian Schultz.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/farmer.zip" image: "http://subtlepatterns.com/patterns/farmer.png" title: "Farmer" categories: ["farmer", "light", "paper"] image_dimensions: "349x349" , image_size: "83K" link: "http://subtlepatterns.com/paper/" description: "Nicely crafted paper pattern, all though a bit on the large side (500x593px)." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper.png" author: "<a href=\"http://timeproduction.ru\" target=\"_blank\">Blaq Annabiosis.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper.zip" image: "http://subtlepatterns.com/patterns/paper.png" title: "Paper" categories: ["light", "paper"] image_dimensions: "500x593" , image_size: "167K" link: "http://subtlepatterns.com/tileable-wood/" description: "Not so subtle, and the name is obvious – these tilable wood patterns are very useful." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tileable_wood_texture.png" author: "<a href=\"http://elemisfreebies.com/\" target=\"_blank\">Elemis.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tileable_wood_texture.zip" image: "http://subtlepatterns.com/patterns/tileable_wood_texture.png" title: "Tileable wood" categories: ["light", "wood"] image_dimensions: "400x317" , image_size: "25K" link: "http://subtlepatterns.com/vintage-speckles/" description: "Lovely pattern with splattered vintage speckles." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/vintage_speckles.png" author: "<a href=\"http://simpleasmilk.co.uk\" target=\"_blank\">David Pomfret.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/vintage_speckles.zip" image: "http://subtlepatterns.com/patterns/vintage_speckles.png" title: "Vintage Speckles" categories: ["light", "vintage"] image_dimensions: "400x300" , image_size: "463B" link: "http://subtlepatterns.com/quilt/" description: "Not sure what this is, but it looks good!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/quilt.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\">Josh Green.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/quilt.zip" image: "http://subtlepatterns.com/patterns/quilt.png" title: "Quilt" categories: ["light", "quilt"] image_dimensions: "25x24" , image_size: "139K" link: "http://subtlepatterns.com/large-leather/" description: "More leather, and this time it’s bigger! You know, in case you need that." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/large_leather.png" author: "<a href=\"http://elemisfreebies.com/\" target=\"_blank\">Elemis.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/large_leather.zip" image: "http://subtlepatterns.com/patterns/large_leather.png" title: "Large leather" categories: ["leather", "light"] image_dimensions: "400x343" , image_size: "108B" link: "http://subtlepatterns.com/dark-dot/" description: "That’s what it is, a dark dot. Or sort of carbon-ish looking." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_dotted.png" author: "<a href=\"http://dribbble.com/bscsystem\" target=\"_blank\">Tsvetelin Nikolov.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_dotted.zip" image: "http://subtlepatterns.com/patterns/dark_dotted.png" title: "Dark dot" categories: ["dark"] image_dimensions: "5x5" , image_size: "4K" link: "http://subtlepatterns.com/grid-noise/" description: "Crossing lines on a light background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grid_noise.png" author: "Daivid Serif" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grid_noise.zip" image: "http://subtlepatterns.com/patterns/grid_noise.png" title: "Grid noise" categories: ["light"] image_dimensions: "98x98" , image_size: "1K" link: "http://subtlepatterns.com/argyle/" description: "Classy golf-pants pattern, or crossed stripes if you will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/argyle.png" author: "Will Monson" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/argyle.zip" image: "http://subtlepatterns.com/patterns/argyle.png" title: "Argyle" categories: ["dark"] image_dimensions: "106x96" , image_size: "6K" link: "http://subtlepatterns.com/grey-sandbag/" description: "A bit strange this one, but nice at the same time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grey_sandbag.png" author: "<a href=\"http://www.diogosilva.net\" target=\"_blank\">Diogo Silva</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grey_sandbag.zip" image: "http://subtlepatterns.com/patterns/grey_sandbag.png" title: "Grey Sandbag" categories: ["light", "sandbag"] image_dimensions: "100x98" , image_size: "52K" link: "http://subtlepatterns.com/white-leather-2/" description: "I took the liberty of using Dmitry’s pattern and made a version without perforation." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_leather.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_leather.zip" image: "http://subtlepatterns.com/patterns/white_leather.png" title: "White leather" categories: ["leather", "light"] image_dimensions: "300x300" , image_size: "92K" link: "http://subtlepatterns.com/ice-age/" description: "I asked Gjermund if he could make a pattern for us – result!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ice_age.png" author: "<a href=\"http://tight.no\" target=\"_blank\">Gjermund Gustavsen</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ice_age.zip" image: "http://subtlepatterns.com/patterns/ice_age.png" title: "Ice age" categories: ["ice", "light", "snow"] image_dimensions: "400x400" , image_size: "55K" link: "http://subtlepatterns.com/perforated-white-leather/" description: "A bit of scratched up grayness. Always good." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/perforated_white_leather.png" author: "Dmitry" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/perforated_white_leather.zip" image: "http://subtlepatterns.com/patterns/perforated_white_leather.png" title: "Perforated White Leather" categories: ["leather", "light"] image_dimensions: "300x300" , image_size: "7K" link: "http://subtlepatterns.com/church/" description: "I have no idea what J Boo means by this name, but hey – it’s hot." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/chruch.png" author: "j Boo" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/chruch.zip" image: "http://subtlepatterns.com/patterns/chruch.png" title: "Church" categories: ["light"] image_dimensions: "100x100" , image_size: "82K" link: "http://subtlepatterns.com/old-husks/" description: "A bit of scratched up grayness. Always good." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/husk.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\">Josh Green</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/husk.zip" image: "http://subtlepatterns.com/patterns/husk.png" title: "Old husks" categories: ["brushed", "light"] image_dimensions: "500x500" , image_size: "379B" link: "http://subtlepatterns.com/cutcube/" description: "Cubes, geometry, 3D. What’s not to love?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cutcube.png" author: "<a href=\"http://cubecolour.co.uk\" target=\"_blank\">Michael Atkins</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cutcube.zip" image: "http://subtlepatterns.com/patterns/cutcube.png" title: "Cutcube" categories: ["3d", "cube", "light"] image_dimensions: "20x36" , image_size: "91K" link: "http://subtlepatterns.com/snow/" description: "Real snow that tiles, not easy. This is not perfect, but an attempt." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/snow.png" author: "<a href=\"http://www.atlemo.com/\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/snow.zip" image: "http://subtlepatterns.com/patterns/snow.png" title: "Snow" categories: ["light", "snow"] image_dimensions: "500x500" , image_size: "25K" link: "http://subtlepatterns.com/cross-scratches/" description: "Subtle scratches on a light gray background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cross_scratches.png" author: "<a href=\"http://www.ovcharov.me/\" target=\"_blank\">Andrey Ovcharov</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cross_scratches.zip" image: "http://subtlepatterns.com/patterns/cross_scratches.png" title: "Cross scratches" categories: ["light", "scratch"] image_dimensions: "256x256" , image_size: "403B" link: "http://subtlepatterns.com/subtle-zebra-3d/" description: "It’s a subtle zebra, in 3D. Oh yes!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_zebra_3d.png" author: "<a href=\"http://www.miketheindian.com\" target=\"_blank\">Mike Warner</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_zebra_3d.zip" image: "http://subtlepatterns.com/patterns/subtle_zebra_3d.png" title: "Subtle Zebra 3D" categories: ["3d", "light"] image_dimensions: "121x38" , image_size: "494B" link: "http://subtlepatterns.com/fake-luxury/" description: "Fake or not, it’s quite luxurious." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fake_luxury.png" author: "<a href=\"http://www.factorio.us\" target=\"_blank\">Factorio.us Collective</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fake_luxury.zip" image: "http://subtlepatterns.com/patterns/fake_luxury.png" title: "Fake luxury" categories: ["light"] image_dimensions: "16x26" , image_size: "817B" link: "http://subtlepatterns.com/dark-geometric/" description: "Continuing the geometric trend, here is one more." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_geometric.png" author: "<a href=\"http://www.miketheindian.com\" target=\"_blank\">Mike Warner</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_geometric.zip" image: "http://subtlepatterns.com/patterns/dark_geometric.png" title: "Dark Geometric" categories: ["dark", "geometric"] image_dimensions: "70x70" , image_size: "5K" link: "http://subtlepatterns.com/blu-stripes/" description: "Very simple, very blu(e). Subtle and nice." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/blu_stripes.png" author: "<a href=\"http://twitter.com/iamsebj\" target=\"_blank\">Seb Jachec</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blu_stripes.zip" image: "http://subtlepatterns.com/patterns/blu_stripes.png" title: "Blu Stripes" categories: ["blue", "light", "stripes"] image_dimensions: "100x100" , image_size: "128K" link: "http://subtlepatterns.com/texturetastic-gray/" description: "This ladies and gentlemen, is texturetastic! Love it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/texturetastic_gray.png" author: "<a href=\"http://www.adampickering.com\" target=\"_blank\">Adam Pickering</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/texturetastic_gray.zip" image: "http://subtlepatterns.com/patterns/texturetastic_gray.png" title: "Texturetastic Gray" categories: ["fabric", "light", "tactile"] image_dimensions: "476x476" , image_size: "220B" link: "http://subtlepatterns.com/soft-pad/" description: "Bumps, highlight and shadows – all good things." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/soft_pad.png" author: "<a href=\"http://ow.ly/8v3IG\" target=\"_blank\">Badhon Ebrahim</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/soft_pad.zip" image: "http://subtlepatterns.com/patterns/soft_pad.png" title: "Soft Pad" categories: ["light"] image_dimensions: "8x8" , image_size: "8K" link: "http://subtlepatterns.com/classy-fabric/" description: "This is lovely, just the right amount of subtle noise, lines and textures." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/classy_fabric.png" author: "<a href=\"http://www.purtypixels.com\" target=\"_blank\">Richard Tabor</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/classy_fabric.zip" image: "http://subtlepatterns.com/patterns/classy_fabric.png" title: "Classy Fabric" categories: ["classy", "dark", "fabric"] image_dimensions: "102x102" , image_size: "911B" link: "http://subtlepatterns.com/hixs-evolution/" description: "Quite some heavy depth and shadows here, but might work well on some mobile apps?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/hixs_pattern_evolution.png" author: "<a href=\"http://www.hybridixstudio.com\" target=\"_blank\">Damian Rivas</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/hixs_pattern_evolution.zip" image: "http://subtlepatterns.com/patterns/hixs_pattern_evolution.png" title: "HIXS Evolution" categories: ["dark", "hexagon", "hixs"] image_dimensions: "35x34" , image_size: "2K" link: "http://subtlepatterns.com/subtle-dark-vertical/" description: "Classic vertical lines, in all it’s subtlety." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dvsup.png" author: "<a href=\"http://tirl.tk/\" target=\"_blank\">Cody L</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dvsup.zip" image: "http://subtlepatterns.com/patterns/dvsup.png" title: "Subtle Dark Vertical" categories: ["dark", "lines", "vertical"] image_dimensions: "40x40" , image_size: "225B" link: "http://subtlepatterns.com/grid-me/" description: "Nice little grid. Would work great as a base on top of some other patterns." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gridme.png" author: "<a href=\"http://www.gobigbang.nl\" target=\"_blank\">Arno Gregorian</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gridme.zip" image: "http://subtlepatterns.com/patterns/gridme.png" title: "Grid Me" categories: ["grid", "light"] image_dimensions: "50x50" , image_size: "2K" link: "http://subtlepatterns.com/knitted-netting/" description: "A bit like some carbon, or knitted netting if you will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/knitted-netting.png" author: "<a href=\"http://graphicriver.net/user/Naf_Naf?ref=Naf_Naf\" target=\"_blank\">Anna Litvinuk</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/knitted-netting.zip" image: "http://subtlepatterns.com/patterns/knitted-netting.png" title: "Knitted Netting" categories: ["carbon", "light", "netting"] image_dimensions: "8x8" , image_size: "166B" link: "http://subtlepatterns.com/dark-matter/" description: "The name is totally random, but hey, it sounds good?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_matter.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_matter.zip" image: "http://subtlepatterns.com/patterns/dark_matter.png" title: "Dark matter" categories: ["dark", "noise", "pixles"] image_dimensions: "7x7" , image_size: "783B" link: "http://subtlepatterns.com/black-thread/" description: "Geometric lines are always hot, and this pattern is no exception." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_thread.png" author: "<a href=\"http://listvetra.ru/\" target=\"_blank\">Listvetra</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_thread.zip" image: "http://subtlepatterns.com/patterns/black_thread.png" title: "Black Thread" categories: ["dark", "geometry"] image_dimensions: "49x28" , image_size: "173K" link: "http://subtlepatterns.com/vertical-cloth/" description: "You just can’t get enough of the fabric patterns, so here is one more for your collection." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/vertical_cloth.png" author: "<a href=\"http://dribbble.com/krisp\" target=\"_blank\">Krisp Designs</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/vertical_cloth.zip" image: "http://subtlepatterns.com/patterns/vertical_cloth.png" title: "Vertical cloth" categories: ["cloth", "dark", "fabric", "lines"] image_dimensions: "399x400" , image_size: "22K" link: "http://subtlepatterns.com/934/" description: "This is the third pattern called Dark Denim, but hey, we all love them!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/darkdenim3.png" author: "<a href=\"http://www.brandonjacoby.com\" target=\"_blank\">Brandon Jacoby</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/darkdenim3.zip" image: "http://subtlepatterns.com/patterns/darkdenim3.png" title: "Dark Denim 3" categories: ["dark", "denim"] image_dimensions: "420x326" , image_size: "255B" link: "http://subtlepatterns.com/white-brick-wall/" description: "If you’re sick of the fancy 3d, grunge and noisy patterns, take a look at this flat 2d brick wall." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_brick_wall.png" author: "<a href=\"http://listvetra.ru/\" target=\"_blank\">Listvetra</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_brick_wall.zip" image: "http://subtlepatterns.com/patterns/white_brick_wall.png" title: "White Brick Wall" categories: ["brick", "light", "wall"] image_dimensions: "24x16" , image_size: "5K" link: "http://subtlepatterns.com/fabric-plaid/" description: "You know you can’t get enough of these linen-fabric-y patterns." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fabric_plaid.png" author: "<a href=\"http://twitter.com/jbasoo\" target=\"_blank\">James Basoo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fabric_plaid.zip" image: "http://subtlepatterns.com/patterns/fabric_plaid.png" title: "Fabric (Plaid)" categories: ["fabric", "light", "plaid"] image_dimensions: "200x200" , image_size: "146B" link: "http://subtlepatterns.com/merely-cubed/" description: "Tiny, tiny 3D cubes. Reminds me of the good old pattern from k10k." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/merely_cubed.png" author: "<a href=\"http://www.etiennerallion.fr\" target=\"_blank\">Etienne Rallion</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/merely_cubed.zip" image: "http://subtlepatterns.com/patterns/merely_cubed.png" title: "Merely Cubed" categories: ["3d", "light"] image_dimensions: "16x16" , image_size: "54K" link: "http://subtlepatterns.com/iron-grip/" description: "Sounds like something from World of Warcraft. Has to be good." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/irongrip.png" author: "<a href=\"http://www.tonykinard.net\" target=\"_blank\">Tony Kinard</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/irongrip.zip" image: "http://subtlepatterns.com/patterns/irongrip.png" title: "Iron Grip" categories: ["dark", "grip", "iron"] image_dimensions: "300x301" , image_size: "847B" link: "http://subtlepatterns.com/starring/" description: "If you need stars, this is the one to get." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/starring.png" author: "<a href=\"http://logosmile.net/\" target=\"_blank\">Agus Riyadi</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/starring.zip" image: "http://subtlepatterns.com/patterns/starring.png" title: "Starring" categories: ["dark", "star", "stars"] image_dimensions: "35x39" , image_size: "1K" link: "http://subtlepatterns.com/pineapple-cut/" description: "I love the movie Pineapple Express, and I’m also liking this Pineapple right here." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pineapplecut.png" author: "<a href=\"http://audeemirza.com\" target=\"_blank\">Audee Mirza</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pineapplecut.zip" image: "http://subtlepatterns.com/patterns/pineapplecut.png" title: "Pineapple Cut" categories: ["light"] image_dimensions: "36x62" , image_size: "13K" link: "http://subtlepatterns.com/grilled-noise/" description: "You could get a bit dizzy from this one, but it might come in handy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grilled.png" author: "<a href=\"http://30.nl\" target=\"_blank\">Dertig Media</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grilled.zip" image: "http://subtlepatterns.com/patterns/grilled.png" title: "Grilled noise" categories: ["dizzy", "light"] image_dimensions: "170x180" , image_size: "2K" link: "http://subtlepatterns.com/foggy-birds/" description: "Hey, you never know when you’ll need a bird-pattern, right?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/foggy_birds.png" author: "<a href=\"http://buttonpresser.com\" target=\"_blank\">Pete Fecteau</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/foggy_birds.zip" image: "http://subtlepatterns.com/patterns/foggy_birds.png" title: "Foggy Birds" categories: ["bird", "light"] image_dimensions: "206x206" , image_size: "39K" link: "http://subtlepatterns.com/groovepaper/" description: "With a name like this, it has to be hot. Diagonal lines in light shades." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/groovepaper.png" author: "<a href=\"http://graphicriver.net/user/krispdesigns\" target=\"_blank\">Isaac</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/groovepaper.zip" image: "http://subtlepatterns.com/patterns/groovepaper.png" title: "Groovepaper" categories: ["diagonal", "light"] image_dimensions: "300x300" , image_size: "277B" link: "http://subtlepatterns.com/nami/" description: "Not sure if this is related to the Nami you get in Google image search, but hey, it’s nice!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/nami.png" author: "<a href=\"http://30.nl\" target=\"_blank\">Dertig Media</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/nami.zip" image: "http://subtlepatterns.com/patterns/nami.png" title: "Nami" categories: ["anime", "asian", "dark"] image_dimensions: "16x16" , image_size: "154B" link: "http://subtlepatterns.com/medic-packaging-foil/" description: "8 by 8 pixels, and just what the title says." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/foil.png" author: "<a href=\"http://be.net/pixilated\" target=\"_blank\">pixilated</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/foil.zip" image: "http://subtlepatterns.com/patterns/foil.png" title: "Medic Packaging Foil" categories: ["foil", "light", "medic", "paper"] image_dimensions: "8x8" , image_size: "30K" link: "http://subtlepatterns.com/white-paperboard/" description: "Could be paper, could be a polaroid frame – up to you!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_paperboard.png" author: "Chaos" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_paperboard.zip" image: "http://subtlepatterns.com/patterns/white_paperboard.png" title: "White Paperboard" categories: ["light", "paper", "paperboard", "polaroid"] image_dimensions: "256x252" , image_size: "20K" link: "http://subtlepatterns.com/dark-denim-2/" description: "Thin lines, noise and texture creates this crisp dark denim pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/denim.png" author: "<a href=\"http://slootenweb.nl\" target=\"_blank\">Marco Slooten</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/denim.zip" image: "http://subtlepatterns.com/patterns/denim.png" title: "Dark Denim" categories: ["dark", "denim"] image_dimensions: "135x135" , image_size: "101K" link: "http://subtlepatterns.com/wood-pattern/" description: "One of the few “full color” patterns here, but this one was just too good to pass up." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wood_pattern.png" author: "Alexey Usoltsev" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wood_pattern.zip" image: "http://subtlepatterns.com/patterns/wood_pattern.png" title: "Wood pattern" categories: ["light", "wood"] image_dimensions: "203x317" , image_size: "28K" link: "http://subtlepatterns.com/white-plaster/" description: "Sweet and subtle white plaster with hints of noise and grunge." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_plaster.png" author: "<a href=\"http://aurer.co.uk\" target=\"_blank\">Phil Maurer</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_plaster.zip" image: "http://subtlepatterns.com/patterns/white_plaster.png" title: "White plaster" categories: ["light"] image_dimensions: "300x300" , image_size: "9K" link: "http://subtlepatterns.com/white-diamond/" description: "To celebrate the new feature, we need some sparkling diamonds." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/whitediamond.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/whitediamond.zip" image: "http://subtlepatterns.com/patterns/whitediamond.png" title: "White Diamond" categories: ["diamond", "light", "triangle"] image_dimensions: "128x224" , image_size: "81K" link: "http://subtlepatterns.com/broken-noise/" description: "Beautiful dark noise pattern with some dust and grunge." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/broken_noise.png" author: "<a href=\"http://vincentklaiber.com\" target=\"_blank\">Vincent Klaiber</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/broken_noise.zip" image: "http://subtlepatterns.com/patterns/broken_noise.png" title: "Broken noise" categories: ["broken", "dark", "grunge", "noise"] image_dimensions: "476x476" , image_size: "153B" link: "http://subtlepatterns.com/gun-metal/" description: "With a name this awesome, how can I go wrong?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gun_metal.png" author: "<a href=\"http://www.zigzain.com\" target=\"_blank\">Nikolay Boltachev</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gun_metal.zip" image: "http://subtlepatterns.com/patterns/gun_metal.png" title: "Gun metal" categories: ["dark", "gun", "metal"] image_dimensions: "10x10" , image_size: "221B" link: "http://subtlepatterns.com/fake-brick/" description: "Black, simple, elegant & useful." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fake_brick.png" author: "Marat" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fake_brick.zip" image: "http://subtlepatterns.com/patterns/fake_brick.png" title: "Fake brick" categories: ["dark", "dots"] image_dimensions: "76x76" , image_size: "295B" link: "http://subtlepatterns.com/candyhole/" description: "It’s a hole, in a pattern. On your website. Dig it!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/candyhole.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\">Josh Green</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/candyhole.zip" image: "http://subtlepatterns.com/patterns/candyhole.png" title: "Candyhole" categories: ["hole", "light"] image_dimensions: "25x25" , image_size: "50K" link: "http://subtlepatterns.com/ravenna/" description: "I guess this is inspired by the city of Ravenna in Italy and it’s stone walls." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ravenna.png" author: "<a href=\"http://sentel.co\" target=\"_blank\">Sentel</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ravenna.zip" image: "http://subtlepatterns.com/patterns/ravenna.png" title: "Ravenna" categories: ["light", "stone", "stones", "wall"] image_dimensions: "387x201" , image_size: "235B" link: "http://subtlepatterns.com/small-crackle-bright/" description: "Light gray pattern with an almost wall tile-like appearance." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/small-crackle-bright.png" author: "<a href=\"http://www.markustinner.ch\" target=\"_blank\">Markus Tinner</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/small-crackle-bright.zip" image: "http://subtlepatterns.com/patterns/small-crackle-bright.png" title: "Small crackle bright" categories: ["light"] image_dimensions: "14x14" , image_size: "29K" link: "http://subtlepatterns.com/nasty-fabric/" description: "Nasty or not, it’s a nice pattern that tiles. Like they all do." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/nasty_fabric.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\">Badhon Ebrahim.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/nasty_fabric.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/nasty_fabric.png" title: "Nasty Fabric" categories: ["light"] image_dimensions: "198x200" , image_size: "997B" link: "http://subtlepatterns.com/diagonal-waves/" description: "It has waves, so make sure you don’t get sea sickness." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagonal_waves.png" author: "<a href=\"http://coolpatterns.net\" target=\"_blank\">CoolPatterns.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonal_waves.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonal_waves.png" title: "Diagonal Waves" categories: ["light"] image_dimensions: "38x38" , image_size: "10K" link: "http://subtlepatterns.com/otis-redding/" description: "Otis Ray Redding was an American soul singer-songwriter, record producer, arranger, and talent scout. So you know." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/otis_redding.png" author: "<a href=\"http://thomasmyrman.com\" target=\"_blank\">Thomas Myrman.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/otis_redding.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/otis_redding.png" title: "Otis Redding" categories: ["light"] image_dimensions: "100x100" , image_size: "10K" link: "http://subtlepatterns.com/billie-holiday/" description: "No relation to the band, but damn it’s subtle!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/billie_holiday.png" author: "<a href=\"http://thomasmyrman.com\" target=\"_blank\">Thomas Myrman.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/billie_holiday.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/billie_holiday.png" title: "Billie Holiday" categories: ["light"] image_dimensions: "100x100" , image_size: "196B" link: "http://subtlepatterns.com/az-subtle/" description: "The A – Z of Subtle? Up to you." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/az_subtle.png" author: "<a href=\"http://www.azmind.com\" target=\"_blank\">Anli.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/az_subtle.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/az_subtle.png" title: "AZ Subtle" categories: ["light"] image_dimensions: "100x100" , image_size: "21K" link: "http://subtlepatterns.com/wild-oliva/" description: "Wild Oliva or Oliva Wilde? Darker than the others, sort of a medium dark pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wild_oliva.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\">Badhon Ebrahim.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wild_oliva.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wild_oliva.png" title: "Wild Oliva" categories: ["dark"] image_dimensions: "198x200" , image_size: "16K" link: "http://subtlepatterns.com/stressed-linen/" description: "We have some linen patterns here, but none that are stressed. Until now." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/stressed_linen.png" author: "Jordan Pittman" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stressed_linen.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stressed_linen.png" title: "Stressed Linen" categories: ["dark"] image_dimensions: "256x256" , image_size: "116K" link: "http://subtlepatterns.com/navy/" description: "It was called Navy Blue, but I made it dark. You know, the way I like it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/navy_blue.png" author: "<a href=\"http://ultranotch.com/\" target=\"_blank\">Ethan Hamilton.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/navy_blue.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/navy_blue.png" title: "Navy" categories: ["dark"] image_dimensions: "600x385" , image_size: "106B" link: "http://subtlepatterns.com/simple-horizontal-light/" description: "Some times you just need the simplest thing." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/shl.png" author: "Fabricio" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shl.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shl.png" title: "Simple Horizontal Light" categories: ["light"] image_dimensions: "4x4" , image_size: "661B" link: "http://subtlepatterns.com/cream_dust/" description: "I love cream! 50x50px and lovely in all the good ways." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cream_dust.png" author: "<a href=\"http://thomasmyrman.com\" target=\"_blank\">Thomas Myrman.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cream_dust.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cream_dust.png" title: "Cream Dust" categories: ["light"] image_dimensions: "50x50" , link: "http://subtlepatterns.com/slash-it/" description: "I have no idea what this is, but it’s tiny and it tiles. Whey!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/slash_it.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\">Venam</a>" download: "/patterns/slash_it.zip" image: "/patterns/slash_it.png" title: "Slash it" categories: ["dark"] , link: "http://subtlepatterns.com/simple-dashed/" description: "Tiny lines going both ways – not the way you think, silly." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/simple_dashed.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\">Venam</a>" download: "/patterns/simple_dashed.zip" image: "/patterns/simple_dashed.png" title: "Simple Dashed" categories: ["dark"] , link: "http://subtlepatterns.com/moulin/" description: "No relation to Moulin Rouge, but still sexy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/moulin.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\">Venam</a>" download: "/patterns/moulin.zip" image: "/patterns/moulin.png" title: "Moulin" categories: ["dark"] , link: "http://subtlepatterns.com/dark-exa/" description: "Looks a bit like little bugs, but they are harmless." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_exa.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\">Venam</a>" download: "/patterns/dark_exa.zip" image: "/patterns/dark_exa.png" title: "Dark Exa" categories: ["dark"] , link: "http://subtlepatterns.com/dark-dotted-2/" description: "Dark dots never go out of fashion, do they? Nope." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_dotted2.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\">Venam</a>" download: "/patterns/dark_dotted2.zip" image: "/patterns/dark_dotted2.png" title: "Dark Dotted 2" categories: ["dark", "dots"] , image_size: "191B" link: "http://subtlepatterns.com/graphy/" description: "Looks like a technical drawing board, small squares forming a nice grid." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/graphy.png" author: "<a href=\"http://www.wearepixel8.com\" target=\"_blank\">We Are Pixel8</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/graphy.zip" image: "http://subtlepatterns.com/patterns/graphy.png" title: "Graphy" categories: ["grid", "light", "maths"] image_dimensions: "80x160" , image_size: "861B" link: "http://subtlepatterns.com/connected/" description: "White circles connecting on a light gray background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/connect.png" author: "<a href=\"http://pixxel.co/\" target=\"_blank\">Mark Collins</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/connect.zip" image: "http://subtlepatterns.com/patterns/connect.png" title: "Connected" categories: ["connection", "dots", "light"] image_dimensions: "160x160" , image_size: "36K" link: "http://subtlepatterns.com/old-wall/" description: "Old concrete wall in light shades." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/old_wall.png" author: "<a href=\"http://twitter.com/simek\" target=\"_blank\">Bartosz Kaszubowski</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/old_wall.zip" image: "http://subtlepatterns.com/patterns/old_wall.png" title: "Old wall" categories: ["concrete", "light", "sement", "wall"] image_dimensions: "300x300" , image_size: "1K" link: "http://subtlepatterns.com/light-grey-floral-motif/" description: "Lovely light gray floral motif with some subtle shades." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_grey_floral_motif.png" author: "<a href=\"http://www.graphicswall.com/\" target=\"_blank\">GraphicsWall</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_grey_floral_motif.zip" image: "http://subtlepatterns.com/patterns/light_grey_floral_motif.png" title: "Light Grey Floral Motif" categories: ["floral", "gray", "light"] image_dimensions: "32x56" , image_size: "3K" link: "http://subtlepatterns.com/3px-tile/" description: "Tiny dark square tiles with varied color tones." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/px_by_Gre3g.png" author: "<a href=\"http://gre3g.livejournal.com\" target=\"_blank\">Gre3g</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/px_by_Gre3g.zip" image: "http://subtlepatterns.com/patterns/px_by_Gre3g.png" title: "3px tile" categories: ["dark", "square", "tile"] image_dimensions: "100x100" , image_size: "276K" link: "http://subtlepatterns.com/rice-paper-2/" description: "One can never have too few rice paper patterns, so here is one more." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ricepaper2.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ricepaper2.zip" image: "http://subtlepatterns.com/patterns/ricepaper2.png" title: "Rice paper 2" categories: ["light", "paper", "rice"] image_dimensions: "485x485" , image_size: "130K" link: "http://subtlepatterns.com/rice-paper/" description: "Scanned some rice paper and tiled it up for you. Enjoy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ricepaper.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ricepaper.zip" image: "http://subtlepatterns.com/patterns/ricepaper.png" title: "Rice paper" categories: ["light", "paper", "rice"] image_dimensions: "500x500" , image_size: "1K" link: "http://subtlepatterns.com/diagmonds/" description: "Love the style on this one, very fresh. Diagonal diamond pattern. Get it?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagmonds.png" author: "<a href=\"http://www.flickr.com/photos/ins\" target=\"_blank\">INS</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagmonds.zip" image: "http://subtlepatterns.com/patterns/diagmonds.png" title: "Diagmonds" categories: ["dark", "diamond"] image_dimensions: "141x142" , image_size: "46K" link: "http://subtlepatterns.com/polonez-pattern-2/" description: "Wtf, a car pattern?! Can it be subtle? I say yes!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/polonez_car.png" author: "<a href=\"http://designcocktails.com\" target=\"_blank\">Radosław Rzepecki</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/polonez_car.zip" image: "http://subtlepatterns.com/patterns/polonez_car.png" title: "Polonez Pattern" categories: ["car", "light"] image_dimensions: "300x300" , image_size: "1K" link: "http://subtlepatterns.com/polonez-pattern/" description: "Repeating squares overlapping." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/plaid.png" author: "<a href=\"http://buttonpresser.com\" target=\"_blank\">Pete Fecteau</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/plaid.zip" image: "http://subtlepatterns.com/patterns/plaid.png" title: "My Little Plaid" categories: ["geometry", "light"] image_dimensions: "54x54" , image_size: "430B" link: "http://subtlepatterns.com/axiom-pattern/" description: "Not even 1kb, but very stylish. Gray thin lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/struckaxiom.png" author: "<a href=\"http://www.struckaxiom.com\" target=\"_blank\">Struck Axiom</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/struckaxiom.zip" image: "http://subtlepatterns.com/patterns/struckaxiom.png" title: "Axiom Pattern" categories: ["diagonal", "light", "stripes"] image_dimensions: "81x81" , image_size: "149B" link: "http://subtlepatterns.com/zig-zag/" description: "So tiny, just 7 by 7 pixels – but still so sexy. Ah yes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/zigzag.png" author: "<a href=\"http://www.behance.net/dmpr0\" target=\"_blank\">Dmitriy Prodchenko</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/zigzag.zip" image: "http://subtlepatterns.com/patterns/zigzag.png" title: "Zig Zag" categories: ["dark", "embossed"] image_dimensions: "10x10" , image_size: "1K" link: "http://subtlepatterns.com/carbon-fibre-big/" description: "Bigger is better, right? So here you have some large Carbon fibre." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/carbon_fibre_big.png" author: "<a href=\"http://factorio.us/\" target=\"_blank\">Factorio.us Collective</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/carbon_fibre_big.zip" image: "http://subtlepatterns.com/patterns/carbon_fibre_big.png" title: "Carbon Fibre Big" categories: ["dark"] image_dimensions: "20x22" , image_size: "1K" link: "http://subtlepatterns.com/batthern/" description: "Some times simple really is what you need, and this could fit you well." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/batthern.png" author: "<a href=\"http://factorio.us/\" target=\"_blank\">Factorio.us Collective</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/batthern.zip" image: "http://subtlepatterns.com/patterns/batthern.png" title: "Batthern" categories: ["light"] image_dimensions: "100x99" , image_size: "406B" link: "http://subtlepatterns.com/checkered-pattern/" description: "Simple gray checkered lines, in light tones." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/checkered_pattern.png" author: "<a href=\"http://designcocktails.com\" target=\"_blank\">Radosław Rzepecki</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/checkered_pattern.zip" image: "http://subtlepatterns.com/patterns/checkered_pattern.png" title: "Checkered Pattern" categories: ["light", "lines"] image_dimensions: "72x72" , image_size: "131K" link: "http://subtlepatterns.com/dark-wood/" description: "A beautiful dark wood pattern, superbly tiled." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_wood.png" author: "<a href=\"http://www.oaadesigns.com\" target=\"_blank\">Omar Alvarado</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_wood.zip" image: "http://subtlepatterns.com/patterns/dark_wood.png" title: "Dark wood" categories: ["dark"] image_dimensions: "512x512" , image_size: "741B" link: "http://subtlepatterns.com/soft-kill/" description: "Pattern #100! A black classic knit-looking pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/soft_kill.png" author: "<a href=\"http://www.factorio.us\" target=\"_blank\">Factorio.us Collective</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/soft_kill.zip" image: "http://subtlepatterns.com/patterns/soft_kill.png" title: "Soft kill" categories: ["dark"] image_dimensions: "28x48" , image_size: "401B" link: "http://subtlepatterns.com/elegant-grid/" description: "This is a hot one. Small, sharp and unique." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/elegant_grid.png" author: "<a href=\"http://www.graphicswall.com\" target=\"_blank\">GraphicsWall</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/elegant_grid.zip" image: "http://subtlepatterns.com/patterns/elegant_grid.png" title: "Elegant Grid" categories: ["light"] image_dimensions: "16x28" , image_size: "36K" link: "http://subtlepatterns.com/xv/" description: "Floral patterns will never go out of style, so enjoy this one." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/xv.png" author: "<a href=\"http://www.oddfur.com\" target=\"_blank\">Lasma</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/xv.zip" image: "http://subtlepatterns.com/patterns/xv.png" title: "Xv" categories: ["light"] image_dimensions: "294x235" , image_size: "66K" link: "http://subtlepatterns.com/rough-cloth/" description: "More tactile goodness. This time in the form of some rough cloth." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/roughcloth.png" author: "<a href=\"http://twitter.com/simek\" target=\"_blank\">Bartosz Kaszubowski</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/roughcloth.zip" image: "http://subtlepatterns.com/patterns/roughcloth.png" title: "Rough Cloth" categories: ["light"] image_dimensions: "320x320" , image_size: "228B" link: "http://subtlepatterns.com/little-knobs/" description: "White little knobs, coming in at 10x10px. Sweet!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/littleknobs.png" author: "<a href=\"http://www.freepx.net\" target=\"_blank\">Amos</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/littleknobs.zip" image: "http://subtlepatterns.com/patterns/littleknobs.png" title: "Little knobs" categories: ["light"] image_dimensions: "10x10" , image_size: "5K" link: "http://subtlepatterns.com/dotnoise-light-grey/" description: "Sort of like the back of a wooden board. Light, subtle and stylish just the way we like it!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/bgnoise_lg.png" author: "Nikolalek" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bgnoise_lg.zip" image: "http://subtlepatterns.com/patterns/bgnoise_lg.png" title: "Dotnoise light grey" categories: ["light"] image_dimensions: "100x100" , image_size: "207B" link: "http://subtlepatterns.com/dark-circles/" description: "People seem to enjoy dark patterns, so here is one with some circles." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_circles.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_circles.zip" image: "http://subtlepatterns.com/patterns/dark_circles.png" title: "Dark circles" categories: ["dark"] image_dimensions: "10x12" , image_size: "42K" link: "http://subtlepatterns.com/light-aluminum/" description: "Used correctly, this could be nice. Used in a bad way, all Hell will break loose." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_alu.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_alu.zip" image: "http://subtlepatterns.com/patterns/light_alu.png" title: "Light aluminum" categories: ["light"] image_dimensions: "282x282" , image_size: "552B" link: "http://subtlepatterns.com/squares/" description: "Dark, square, clean and tidy. What more can you ask for?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/squares.png" author: "<a href=\"http://www.toshtak.com/\" target=\"_blank\">Jaromír Kavan</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/squares.zip" image: "http://subtlepatterns.com/patterns/squares.png" title: "Squares" categories: ["dark"] image_dimensions: "32x32" , image_size: "129K" link: "http://subtlepatterns.com/felt/" description: "Got some felt in my mailbox today, so I scanned it for you to use." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/felt.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/felt.zip" image: "http://subtlepatterns.com/patterns/felt.png" title: "Felt" categories: ["light"] image_dimensions: "500x466" , image_size: "2K" link: "http://subtlepatterns.com/transparent-square-tiles/" description: "The first pattern on here using opacity. Try it on a site with a colored background, or even using mixed colors." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/square_bg.png" author: "<a href=\"http://nspady.com\" target=\"_blank\">Nathan Spady</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/square_bg.zip" image: "http://subtlepatterns.com/patterns/square_bg.png" title: "Transparent Square Tiles" categories: ["light"] image_dimensions: "252x230" , image_size: "418B" link: "http://subtlepatterns.com/paven/" description: "A subtle shadowed checkered pattern. Increase the lightness for even more subtle sexyness." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paven.png" author: "<a href=\"http://emailcoder.net\" target=\"_blank\">Josh Green</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paven.zip" image: "http://subtlepatterns.com/patterns/paven.png" title: "Paven" categories: ["light"] image_dimensions: "20x20" , image_size: "34K" link: "http://subtlepatterns.com/stucco/" description: "A nice and simple gray stucco material. Great on it’s own, or as a base for a new pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/stucco.png" author: "<a href=\"http://twitter.com/#!/simek\" target=\"_blank\">Bartosz Kaszubowski</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stucco.zip" image: "http://subtlepatterns.com/patterns/stucco.png" title: "Stucco" categories: ["light"] image_dimensions: "250x249" , image_size: "21K" link: "http://subtlepatterns.com/r-i-p-steve-jobs/" description: "He influenced us all. “Don’t be sad because it’s over. Smile because it happened.” - Dr. Seuss" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rip_jobs.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rip_jobs.zip" image: "http://subtlepatterns.com/patterns/rip_jobs.png" title: "R.I.P Steve Jobs" categories: ["light"] image_dimensions: "200x200" , image_size: "1K" link: "http://subtlepatterns.com/woven/" description: "Can’t believe we don’t have this in the collection already! Slick woven pattern with crisp details." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/woven.png" author: "<a href=\"http://www.maxthemes.com\" target=\"_blank\">Max Rudberg</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/woven.zip" image: "http://subtlepatterns.com/patterns/woven.png" title: "Woven" categories: ["dark"] image_dimensions: "42x42" , image_size: "5K" link: "http://subtlepatterns.com/washi/" description: "Washi (和紙?) is a type of paper made in Japan. Here’s the pattern for you!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/washi.png" author: "<a href=\"http://www.sweetstudio.co.uk\" target=\"_blank\">Carolynne</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/washi.zip" image: "http://subtlepatterns.com/patterns/washi.png" title: "Washi" categories: ["light"] image_dimensions: "100x100" , image_size: "418B" link: "http://subtlepatterns.com/real-carbon-fibre/" description: "Carbon fibre is never out of fashion, so here is one more style for you." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/real_cf.png" author: "Alfred Lee" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/real_cf.zip" image: "http://subtlepatterns.com/patterns/real_cf.png" title: "Real Carbon Fibre" categories: ["dark"] image_dimensions: "56x56" , image_size: "1K" link: "http://subtlepatterns.com/gold-scale/" description: "More Japanese-inspired patterns, Gold Scales this time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gold_scale.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\">Josh Green</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gold_scale.zip" image: "http://subtlepatterns.com/patterns/gold_scale.png" title: "Gold Scale" categories: ["light"] image_dimensions: "25x25" , image_size: "1K" link: "http://subtlepatterns.com/elastoplast/" description: "A fun looking elastoplast/band-aid pattern. A hint of orange tone in this one." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/elastoplast.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\">Josh Green</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/elastoplast.zip" image: "http://subtlepatterns.com/patterns/elastoplast.png" title: "Elastoplast" categories: ["light"] image_dimensions: "37x37" , image_size: "1K" link: "http://subtlepatterns.com/checkered-light-emboss/" description: "Sort of like the Photoshop transparent background, but better!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_checkered_tiles.png" author: "<a href=\"http://twitter.com/misterparker\" target=\"_blank\">Alex Parker</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_checkered_tiles.zip" image: "http://subtlepatterns.com/patterns/light_checkered_tiles.png" title: "Checkered light emboss" categories: ["light"] image_dimensions: "60x60" , image_size: "200K" link: "http://subtlepatterns.com/cardboard/" description: "A good starting point for a cardboard pattern. This would work well in a variety of colors." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cardboard.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cardboard.zip" image: "http://subtlepatterns.com/patterns/cardboard.png" title: "Cardboard" categories: ["light"] image_dimensions: "600x600" , image_size: "15K" link: "http://subtlepatterns.com/type/" description: "The perfect pattern for all your blogs about type, or type related matters." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/type.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/type.zip" image: "http://subtlepatterns.com/patterns/type.png" title: "Type" categories: ["dark"] image_dimensions: "200x200" , image_size: "278B" link: "http://subtlepatterns.com/mbossed/" description: "Embossed lines and squares with subtle highlights." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/small_tiles.png" author: "<a href=\"http://twitter.com/misterparker\" target=\"_blank\">Alex Parker</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/small_tiles.zip" image: "http://subtlepatterns.com/patterns/small_tiles.png" title: "MBossed" categories: ["light"] image_dimensions: "26x26" , image_size: "279B" link: "http://subtlepatterns.com/black-scales/" description: "Same as Silver Scales, but in black – turn your site in to a dragon with this great scale pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_scales.png" author: "<a href=\"http://twitter.com/misterparker\" target=\"_blank\">Alex Parker</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_scales.zip" image: "http://subtlepatterns.com/patterns/black_scales.png" title: "Black Scales" categories: ["dark"] image_dimensions: "40x40" , image_size: "289B" link: "http://subtlepatterns.com/silver-scales/" description: "Turn your site in to a dragon with this great scale pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/silver_scales.png" author: "<a href=\"http://twitter.com/misterparker\" target=\"_blank\">Alex Parker</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/silver_scales.zip" image: "http://subtlepatterns.com/patterns/silver_scales.png" title: "Silver Scales" categories: ["light"] image_dimensions: "40x40" , image_size: "5K" link: "http://subtlepatterns.com/polaroid/" description: "Smooth Polaroid pattern with a light blue tint." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/polaroid.png" author: "<a href=\"http://danielbeaton.tumblr.com\" target=\"_blank\">Daniel Beaton</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/polaroid.zip" image: "http://subtlepatterns.com/patterns/polaroid.png" title: "Polaroid" categories: ["light"] image_dimensions: "58x36" , image_size: "247B" link: "http://subtlepatterns.com/circles/" description: "One more sharp little tile for you. Subtle circles this time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/circles.png" author: "<a href=\"http://www.blunia.com/\" target=\"_blank\">Blunia</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/circles.zip" image: "http://subtlepatterns.com/patterns/circles.png" title: "Circles" categories: ["light"] image_dimensions: "16x12" , image_size: "2K" link: "http://subtlepatterns.com/diamonds-are-forever/" description: "Sharp diamond pattern. A small 24x18px tile." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diamonds.png" author: "<a href=\"http://imaketees.co.uk\" target=\"_blank\">Tom Neal</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diamonds.zip" image: "http://subtlepatterns.com/patterns/diamonds.png" title: "Diamonds Are Forever" categories: ["light"] image_dimensions: "24x18" , image_size: "8K" link: "http://subtlepatterns.com/diagonal-noise/" description: "A simple but elegant classic. Every collection needs one of these." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagonal-noise.png" author: "<a href=\"http://ChristopherBurton.net\" target=\"_blank\">Christopher Burton</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonal-noise.zip" image: "http://subtlepatterns.com/patterns/diagonal-noise.png" title: "Diagonal Noise" categories: ["light"] image_dimensions: "100x100" , image_size: "30K" link: "http://subtlepatterns.com/noise-pattern-with-subtle-cross-lines/" description: "More bright luxury. This is a bit larger than fancy deboss, and with a bit more noise." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noise_pattern_with_crosslines.png" author: "<a href=\"http://visztpeter.me\" target=\"_blank\">Viszt Péter</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noise_pattern_with_crosslines.zip" image: "http://subtlepatterns.com/patterns/noise_pattern_with_crosslines.png" title: "Noise pattern with subtle cross lines" categories: [] image_dimensions: "240x240" , image_size: "265B" link: "http://subtlepatterns.com/fancy-deboss/" description: "Luxury pattern, looking like it came right out of Paris." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fancy_deboss.png" author: "<a href=\"http://danielbeaton.tumblr.com\" target=\"_blank\">Daniel Beaton</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fancy_deboss.zip" image: "http://subtlepatterns.com/patterns/fancy_deboss.png" title: "Fancy Deboss" categories: ["light"] image_dimensions: "18x13" , image_size: "40K" link: "http://subtlepatterns.com/pool-table/" description: "This makes me wanna shoot some pool! Sweet green pool table pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pool_table.png" author: "<a href=\"http://caveman.chlova.com\" target=\"_blank\">Caveman</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pool_table.zip" image: "http://subtlepatterns.com/patterns/pool_table.png" title: "Pool Table" categories: ["color", "dark"] image_dimensions: "256x256" , image_size: "5K" link: "http://subtlepatterns.com/dark-brick-wall/" description: "Black brick wall pattern. Brick your site up!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_brick_wall.png" author: "<a href=\"http://alexparker.me\" target=\"_blank\">Alex Parker</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_brick_wall.zip" image: "http://subtlepatterns.com/patterns/dark_brick_wall.png" title: "Dark Brick Wall" categories: ["dark"] image_dimensions: "96x96" , image_size: "723B" link: "http://subtlepatterns.com/cubes/" description: "This reminds me of Game Cube. A nice light 3D cube pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cubes.png" author: "<a href=\"http://www.experimint.nl\" target=\"_blank\">Sander Ottens</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cubes.zip" image: "http://subtlepatterns.com/patterns/cubes.png" title: "Cubes" categories: ["light"] image_dimensions: "67x100" , image_size: "5K" link: "http://subtlepatterns.com/white-texture/" description: "Not the most creative name, but it’s a good all-purpose light background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_texture.png" author: "Dmitry" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_texture.zip" image: "http://subtlepatterns.com/patterns/white_texture.png" title: "White Texture" categories: ["light"] image_dimensions: "102x102" , image_size: "72K" link: "http://subtlepatterns.com/black-leather/" description: "You were craving for more leather, so I whipped this up by scanning a leather jacket." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_leather.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_leather.zip" image: "http://subtlepatterns.com/patterns/dark_leather.png" title: "Dark leather" categories: ["dark"] image_dimensions: "398x484" , image_size: "5K" link: "http://subtlepatterns.com/robots/" description: "And some more testing, this time with Seamless Studio . It’s Robots FFS!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/robots.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/robots.zip" image: "http://subtlepatterns.com/patterns/robots.png" title: "Robots" categories: ["dark"] image_dimensions: "200x200" , image_size: "5K" link: "http://subtlepatterns.com/mirrored-squares/" description: "Did some testing with Repper Pro tonight, and this gray mid-tone pattern came out." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/mirrored_squares.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/mirrored_squares.zip" image: "http://subtlepatterns.com/patterns/mirrored_squares.png" title: "Mirrored Squares" categories: ["dark"] image_dimensions: "166x166" , image_size: "10K" link: "http://subtlepatterns.com/dark-mosaic/" description: "Small dots with minor circles spread across to form a nice mosaic." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_mosaic.png" author: "John Burks" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_mosaic.zip" image: "http://subtlepatterns.com/patterns/dark_mosaic.png" title: "Dark Mosaic" categories: ["dark"] image_dimensions: "300x295" , image_size: "224B" link: "http://subtlepatterns.com/project-papper/" description: "Light square grid pattern, great for a “DIY projects” sort of website, maybe?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/project_papper.png" author: "<a href=\"http://www.fotografiaetc.com.br/\" target=\"_blank\">Rafael Almeida</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/project_papper.zip" image: "http://subtlepatterns.com/patterns/project_papper.png" title: "Project Papper" categories: ["light"] image_dimensions: "105x105" , image_size: "31K" link: "http://subtlepatterns.com/inflicted/" description: "Dark squares with some virus-looking dots in the grid." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/inflicted.png" author: "<a href=\"http://www.inflicted.nl\" target=\"_blank\">Hugo Loning</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/inflicted.zip" image: "http://subtlepatterns.com/patterns/inflicted.png" title: "Inflicted" categories: ["dark"] image_dimensions: "240x240" , image_size: "116B" link: "http://subtlepatterns.com/small-crosses/" description: "Sharp pixel pattern looking like some sort of fabric." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/crosses.png" author: "Ian Dmitry" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/crosses.zip" image: "http://subtlepatterns.com/patterns/crosses.png" title: "Small Crosses" categories: ["light"] image_dimensions: "10x10" , image_size: "9K" link: "http://subtlepatterns.com/soft-circle-scales/" description: "Japanese looking fish scale pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/soft_circle_scales.png" author: "<a href=\"http://iansoper.com\" title=\"Ian Soper\" target=\"_blank\">Ian Soper</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/soft_circle_scales.zip" image: "http://subtlepatterns.com/patterns/soft_circle_scales.png" title: "Soft Circle Scales" categories: ["light"] image_dimensions: "256x56" , image_size: "60K" link: "http://subtlepatterns.com/crissxcross/" description: "Dark pattern with some nice diagonal stitched lines crossing over." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/crissXcross.png" author: "Ashton" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/crissXcross.zip" image: "http://subtlepatterns.com/patterns/crissXcross.png" title: "crissXcross" categories: ["dark"] image_dimensions: "512x512" , image_size: "85K" link: "http://subtlepatterns.com/whitey/" description: "A white version of the very popular linen pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/whitey.png" author: "<a href=\"http://www.turkhitbox.com\" target=\"_blank\">Ant Ekşiler</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/whitey.zip" image: "http://subtlepatterns.com/patterns/whitey.png" title: "Whitey" categories: ["light"] image_dimensions: "654x654" , image_size: "42K" link: "http://subtlepatterns.com/green-dust-scratches/" description: "Snap! It’s a pattern, and it’s not grayscale! Of course you can always change the color in Photoshop." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/green_dust_scratch.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/green_dust_scratch.zip" image: "http://subtlepatterns.com/patterns/green_dust_scratch.png" title: "Green Dust & Scratches" categories: ["light"] image_dimensions: "296x300" , image_size: "635B" link: "http://subtlepatterns.com/carbon-fibre-v2/" description: "One more updated pattern. Not really carbon fibre, but it’s the most popular pattern, so I’ll give you an extra choice." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/carbon_fibre_v2.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/carbon_fibre_v2.zip" image: "http://subtlepatterns.com/patterns/carbon_fibre_v2.png" title: "Carbon fibre v2" categories: ["dark"] image_dimensions: "32x36" , image_size: "137K" link: "http://subtlepatterns.com/black-linen-2/" description: "A new take on the black linen pattern. Softer this time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_linen_v2.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_linen_v2.zip" image: "http://subtlepatterns.com/patterns/black_linen_v2.png" title: "Black linen 2" categories: ["dark"] image_dimensions: "640x640" , image_size: "1004B" link: "http://subtlepatterns.com/darth-stripe/" description: "A very slick dark rubber grip pattern, sort of like the grip on a camera." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rubber_grip.png" author: "<a href=\"http://be.net/pixilated\">Sinisha</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rubber_grip.zip" image: "http://subtlepatterns.com/patterns/rubber_grip.png" title: "Rubber grip" categories: ["dark"] image_dimensions: "5x20" , image_size: "218K" link: "http://subtlepatterns.com/darth-stripe-2/" description: "Diagonal lines with a lot of texture to them." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/darth_stripe.png" author: "Ashton" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/darth_stripe.zip" image: "http://subtlepatterns.com/patterns/darth_stripe.png" title: "Darth Stripe" categories: ["dark"] image_dimensions: "511x511" , image_size: "71K" link: "http://subtlepatterns.com/subtle-orange-emboss/" description: "A hint or orange color, and some crossed & embossed lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_orange_emboss.png" author: "<a href=\"http://www.depcore.com\" target=\"_blank\">Adam Anlauf</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_orange_emboss.zip" image: "http://subtlepatterns.com/patterns/subtle_orange_emboss.png" title: "Subtle orange emboss" categories: ["light"] image_dimensions: "497x249" , image_size: "225K" link: "http://subtlepatterns.com/soft-wallpaper/" description: "Coming in at 666x666px, this is an evil big pattern, but nice and soft at the same time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/soft_wallpaper.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/soft_wallpaper.zip" image: "http://subtlepatterns.com/patterns/soft_wallpaper.png" title: "Soft Wallpaper" categories: ["light"] image_dimensions: "666x666" , image_size: "60K" link: "http://subtlepatterns.com/concrete-wall-3/" description: "All good things are 3, so I give you the third in my little concrete wall series." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/concrete_wall_3.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/concrete_wall_3.zip" image: "http://subtlepatterns.com/patterns/concrete_wall_3.png" title: "Concrete wall 3" categories: ["light"] image_dimensions: "400x299" , image_size: "38K" link: "http://subtlepatterns.com/green-fibers/" description: "The Green fibers pattern will work very well in grayscale as well." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/green-fibers.png" author: "<a href=\"http://www.matteodicapua.com\" target=\"_blank\">Matteo Di Capua</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/green-fibers.zip" image: "http://subtlepatterns.com/patterns/green-fibers.png" title: "Green Fibers" categories: ["dark"] image_dimensions: "200x200" , image_size: "14K" link: "http://subtlepatterns.com/subtle-freckles/" description: "This shit is so subtle we’re talking 1% opacity. Get your squint on!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_freckles.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_freckles.zip" image: "http://subtlepatterns.com/patterns/subtle_freckles.png" title: "Subtle freckles" categories: ["light"] image_dimensions: "198x198" , image_size: "40K" link: "http://subtlepatterns.com/bright-squares/" description: "It’s Okay to be square! A nice light gray pattern with random squares." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/bright_squares.png" author: "<a href=\"http://twitter.com/dwaseem\" target=\"_blank\">Waseem Dahman</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bright_squares.zip" image: "http://subtlepatterns.com/patterns/bright_squares.png" title: "Bright Squares" categories: ["light"] image_dimensions: "297x297" , image_size: "1K" link: "http://subtlepatterns.com/green-gobbler/" description: "Luxurious looking pattern (for a t-shirt maybe?) with a hint of green." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/green_gobbler.png" author: "<a href=\"http://www.simonmeek.com\" target=\"_blank\">Simon Meek</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/green_gobbler.zip" image: "http://subtlepatterns.com/patterns/green_gobbler.png" title: "Green gobbler" categories: ["light"] image_dimensions: "39x39" , image_size: "23K" link: "http://subtlepatterns.com/beige-paper/" description: "This was submitted in a beige color, hence the name. Now it’s a gray paper pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/beige_paper.png" author: "<a href=\"http://twitter.com/phenix_h_k\" target=\"_blank\">Konstantin Ivanov</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/beige_paper.zip" image: "http://subtlepatterns.com/patterns/beige_paper.png" title: "Beige paper" categories: ["light"] image_dimensions: "200x200" , image_size: "106K" link: "http://subtlepatterns.com/grunge-wall/" description: "Light gray grunge wall with a nice texture overlay." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grunge_wall.png" author: "<a href=\"http://www.depcore.pl\" target=\"_blank\">Adam Anlauf</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grunge_wall.zip" image: "http://subtlepatterns.com/patterns/grunge_wall.png" title: "Grunge wall" categories: ["light"] image_dimensions: "500x375" , image_size: "272K" link: "http://subtlepatterns.com/concrete-wall-2/" description: "A light gray wall or floor (you decide) of concrete." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/concrete_wall_2.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/concrete_wall_2.zip" image: "http://subtlepatterns.com/patterns/concrete_wall_2.png" title: "Concrete wall 2" categories: ["concrete", "light"] image_dimensions: "597x545" , image_size: "173K" link: "http://subtlepatterns.com/concrete-wall/" description: "Dark blue concrete wall with some small dust spots." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/concrete_wall.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/concrete_wall.zip" image: "http://subtlepatterns.com/patterns/concrete_wall.png" title: "Concrete wall" categories: ["dark"] image_dimensions: "520x520" , image_size: "1K" link: "http://subtlepatterns.com/wavecut/" description: "If you like it a bit trippy, this wave pattern might be for you." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wavecut.png" author: "<a href=\"http://iansoper.com\" target=\"_blank\">Ian Soper</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wavecut.zip" image: "http://subtlepatterns.com/patterns/wavecut.png" title: "WaveCut" categories: ["light"] image_dimensions: "162x15" , image_size: "131K" link: "http://subtlepatterns.com/little-pluses/" description: "Subtle grunge and many little pluses on top." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/little_pluses.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/little_pluses.zip" image: "http://subtlepatterns.com/patterns/little_pluses.png" title: "Little pluses" categories: ["light"] image_dimensions: "300x300" , image_size: "2K" link: "http://subtlepatterns.com/vichy/" description: "This one could be the shirt of a golf player. Angled lines in different thicknesses." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/vichy.png" author: "<a href=\"http://www.olivierpineda.com\" target=\"_blank\">Olivier Pineda</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/vichy.zip" image: "http://subtlepatterns.com/patterns/vichy.png" title: "Vichy" categories: ["light"] image_dimensions: "70x70" , image_size: "8K" link: "http://subtlepatterns.com/random-grey-variations/" description: "Stefan is hard at work, this time with a funky pattern of squares." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/random_grey_variations.png" author: "<a href=\"http://www.MentalWardDesign.com\" target=\"_blank\">Stefan Aleksić</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/random_grey_variations.zip" image: "http://subtlepatterns.com/patterns/random_grey_variations.png" title: "Random Grey Variations" categories: ["dark"] image_dimensions: "200x200" , image_size: "10K" link: "http://subtlepatterns.com/brushed-alum/" description: "A light brushed aluminum pattern for your pleasure." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/brushed_alu.png" author: "<a href=\"http://www.MentalWardDesign.com\" target=\"_blank\">Tim Ward</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/brushed_alu.zip" image: "http://subtlepatterns.com/patterns/brushed_alu.png" title: "Brushed Alum" categories: ["aluminum", "light"] image_dimensions: "400x400" , image_size: "89K" link: "http://subtlepatterns.com/brushed-alum-dark/" description: "Because I love dark patterns, here is Brushed Alum in a dark coating." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/brushed_alu_dark.png" author: "<a href=\"http://www.MentalWardDesign.com\" target=\"_blank\">Tim Ward</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/brushed_alu_dark.zip" image: "http://subtlepatterns.com/patterns/brushed_alu_dark.png" title: "Brushed Alum Dark" categories: ["dark", "square"] image_dimensions: "400x400" , image_size: "82K" link: "http://subtlepatterns.com/black-linen/" description: "In the spirit of WWDC 2011, here is a dark iOS inspired linen pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black-Linen.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black-Linen.zip" image: "http://subtlepatterns.com/patterns/black-Linen.png" title: "Black Linen" categories: ["dark"] image_dimensions: "482x490" , image_size: "16K" link: "http://subtlepatterns.com/padded/" description: "A beautiful dark padded pattern, like an old classic sofa." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/padded.png" author: "<a href=\"http://papertank.co.uk\" target=\"_blank\">Chris Baldie</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/padded.zip" image: "http://subtlepatterns.com/patterns/padded.png" title: "Padded" categories: ["dark"] image_dimensions: "160x160" , image_size: "26K" link: "http://subtlepatterns.com/light-honeycomb/" description: "Light honeycomb pattern made up of the classic hexagon shape." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_honeycomb.png" author: "<a href=\"http://about.me/federicca\" target=\"_blank\">Federica Pelzel</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_honeycomb.zip" image: "http://subtlepatterns.com/patterns/light_honeycomb.png" title: "Light Honeycomb" categories: ["light"] image_dimensions: "270x289" , image_size: "93K" link: "http://subtlepatterns.com/black-mamba/" description: "The name alone is awesome, but so is this sweet dark pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/blackmamba.png" author: "<a href=\"http://about.me/federicca\" target=\"_blank\">Federica Pelzel</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blackmamba.zip" image: "http://subtlepatterns.com/patterns/blackmamba.png" title: "Black Mamba" categories: ["dark"] image_dimensions: "500x500" , image_size: "79K" link: "http://subtlepatterns.com/black-paper/" description: "Black paper texture, based on two different images." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_paper.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a> based on textures from <a href=\"http://www.designkindle.com/2011/03/03/vintage-paper-textures-vol-1/\" target=\"_blank\">Design Kindle</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_paper.zip" image: "http://subtlepatterns.com/patterns/black_paper.png" title: "Black paper" categories: ["dark"] image_dimensions: "400x400" , image_size: "353B" link: "http://subtlepatterns.com/always-grey/" description: "Crossing lines with a subtle emboss effect on a dark background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/always_grey.png" author: "<a href=\"http://www.facebook.com/stefanaleksic88\" target=\"_blank\">Stefan Aleksić</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/always_grey.zip" image: "http://subtlepatterns.com/patterns/always_grey.png" title: "Always Grey" categories: ["dark"] image_dimensions: "35x35" , image_size: "7K" link: "http://subtlepatterns.com/double-lined/" description: "Horizontal and vertical lines on a light gray background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/double_lined.png" author: "<a href=\"http://www.depcore.pl\" target=\"_blank\">Adam Anlauf</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/double_lined.zip" image: "http://subtlepatterns.com/patterns/double_lined.png" title: "Double lined" categories: ["light"] image_dimensions: "150x64" , image_size: "614K" link: "http://subtlepatterns.com/wood/" description: "Dark wooden pattern, given the subtle treatment." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wood_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a> based on texture from <a href=\"http://cloaks.deviantart.com/\" target=\"_blank\">Cloaks</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wood_1.zip" image: "http://subtlepatterns.com/patterns/wood_1.png" title: "Wood" categories: ["dark"] image_dimensions: "700x700" , image_size: "1015B" link: "http://subtlepatterns.com/cross-stripes/" description: "Nice and simple crossed lines in dark gray tones." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/crossed_stripes.png" author: "<a href=\"http://www.facebook.com/stefanaleksic88\" target=\"_blank\">Stefan Aleksić</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/crossed_stripes.zip" image: "http://subtlepatterns.com/patterns/crossed_stripes.png" title: "Cross Stripes" categories: ["dark"] image_dimensions: "6x6" , image_size: "20K" link: "http://subtlepatterns.com/noisy/" description: "Looks a bit like concrete with subtle specs spread around the pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noisy.png" author: "<a href=\"http://anticdesign.info\" target=\"_blank\">Mladjan Antic</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy.zip" image: "http://subtlepatterns.com/patterns/noisy.png" title: "Noisy" categories: ["light", "noise"] image_dimensions: "300x300" , image_size: "47K" link: "http://subtlepatterns.com/old-mathematics/" description: "This one takes you back to math class. Classic mathematic board underlay." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/old_mathematics.png" author: "<a href=\"http://emailcoder.net/\" target=\"_blank\">Josh Green</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/old_mathematics.zip" image: "http://subtlepatterns.com/patterns/old_mathematics.png" title: "Old Mathematics" categories: ["blue", "grid", "light", "mathematic"] image_dimensions: "200x200" , image_size: "100K" link: "http://subtlepatterns.com/rocky-wall/" description: "High detail stone wall with minor cracks and specks." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rockywall.png" author: "<a href=\"http://projecteightyfive.com/\" target=\"_blank\">Projecteightyfive</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rockywall.zip" image: "http://subtlepatterns.com/patterns/rockywall.png" title: "Rocky wall" categories: ["light", "rock", "wall"] image_dimensions: "500x500" , image_size: "1K" link: "http://subtlepatterns.com/dark-stripes/" description: "Very dark pattern with some noise and 45 degree lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_stripes.png" author: "<a href=\"http://www.facebook.com/stefanaleksic88\" target=\"_blank\">Stefan Aleksić</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_stripes.zip" image: "http://subtlepatterns.com/patterns/dark_stripes.png" title: "Dark stripes" categories: ["dark", "stripes"] image_dimensions: "50x50" , image_size: "6K" link: "http://subtlepatterns.com/handmade-paper/" description: "White hand made paper pattern with small bumps." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/handmadepaper.png" author: "Le Marqui" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/handmadepaper.zip" image: "http://subtlepatterns.com/patterns/handmadepaper.png" title: "Handmade paper" categories: ["light", "paper"] image_dimensions: "100x100" , image_size: "537B" link: "http://subtlepatterns.com/pinstripe/" description: "Light gray pattern with a thin pinstripe." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pinstripe.png" author: "<a href=\"http://extrast.com\" target=\"_blank\">Brandon</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pinstripe.zip" image: "http://subtlepatterns.com/patterns/pinstripe.png" title: "Pinstripe" categories: ["gray", "light", "pinstripe"] image_dimensions: "50x500" , image_size: "45K" link: "http://subtlepatterns.com/wine-cork/" description: "Wine cork texture based off a scanned corkboard." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cork_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cork_1.zip" image: "http://subtlepatterns.com/patterns/cork_1.png" title: "Wine Cork" categories: ["cork", "light"] image_dimensions: "300x300" , image_size: "85K" link: "http://subtlepatterns.com/bedge-grunge/" description: "A large (588x375px) sand colored pattern for your ever growing collection. Shrink at will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/bedge_grunge.png" author: "<a href=\"http://www.tapein.com\" target=\"_blank\">Alex Tapein.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bedge_grunge.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bedge_grunge.png" title: "Bedge grunge" categories: ["light"] image_dimensions: "588x375" , image_size: "24K" link: "http://subtlepatterns.com/noisy-net/" description: "Little x’es, noise and all the stuff you like. Dark like a Monday, with a hint of blue." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noisy_net.png" author: "<a href=\"http://twitter.com/_mcrdl\" target=\"_blank\">Tom McArdle.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy_net.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy_net.png" title: "Noisy Net" categories: ["dark", "noise"] image_dimensions: "200x200" , image_size: "53K" link: "http://subtlepatterns.com/grid/" description: "There are quite a few grid patterns, but this one is a super tiny grid with some dust for good measure." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grid.png" author: "<a href=\"http://www.werk.sk\" target=\"_blank\">Dominik Kiss.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grid.png" title: "Grid" categories: ["grid", "light"] image_dimensions: "310x310" , image_size: "202B" link: "http://subtlepatterns.com/straws/" description: "Super detailed 16×16 tile that forms a beautiful pattern of straws." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/straws.png" author: "<a href=\"http://evaluto.com\" target=\"_blank\">Pavel.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/straws.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/straws.png" title: "Straws" categories: ["light"] image_dimensions: "16x16" , image_size: "32K" link: "http://subtlepatterns.com/cardboard-flat/" description: "Not a flat you live inside, like in the UK – but a flat piece of cardboard." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cardboard_flat.png" author: "Appleshadow" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cardboard_flat.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cardboard_flat.png" title: "Cardboard Flat" categories: ["light"] image_dimensions: "256x256" , image_size: "32K" link: "http://subtlepatterns.com/noisy-grid/" description: "This is a grid, only it’s noisy. You know. Reminds you of those printed grids you draw on." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noisy_grid.png" author: "<a href=\"http://www.vectorpile.com\" target=\"_blank\">Vectorpile.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy_grid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy_grid.png" title: "Noisy Grid" categories: ["grid", "light"] image_dimensions: "150x150" , image_size: "2K" link: "http://subtlepatterns.com/office/" description: "I guess this one is inspired by an office. A dark office." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/office.png" author: "<a href=\"http://www.andresrigo.com\" target=\"_blank\">Andrés Rigo.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/office.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/office.png" title: "Office" categories: ["dark"] image_dimensions: "70x70" , image_size: "44K" link: "http://subtlepatterns.com/subtle-grey/" description: "The Grid. A digital frontier. I tried to picture clusters of information as they traveled through the computer." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grey.png" author: "Haris Šumić" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grey.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grey.png" title: "Subtle Grey" categories: ["light"] image_dimensions: "397x322" , image_size: "218B" link: "http://subtlepatterns.com/hexabump/" description: "Hexagonal dark 3D pattern, what more can you ask for?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/hexabump.png" author: "<a href=\"http://spom.me\" target=\"_blank\">Norbert Levajsics</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/hexabump.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/hexabump.png" title: "Hexabump" categories: ["dark"] image_dimensions: "19x33" , image_size: "134K" link: "http://subtlepatterns.com/shattered/" description: "A large pattern with funky shapes and form. An original. Sort of origami-ish." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/shattered.png" author: "<a href=\"http://luukvanbaars.com\" target=\"_blank\">Luuk van Baars</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shattered.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shattered.png" title: "Shattered" categories: ["light", "origami"] image_dimensions: "500x500" , image_size: "32K" link: "http://subtlepatterns.com/paper-3/" description: "Light gray paper pattern with small traces of fibre and some dust." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper_3.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_3.zip" image: "http://subtlepatterns.com/patterns/paper_3.png" title: "Paper 3" categories: ["light", "paper"] image_dimensions: "276x276" , image_size: "9K" link: "http://subtlepatterns.com/dark-denim/" description: "A dark denim looking pattern. 145×145 pixels." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_denim.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_denim.zip" image: "http://subtlepatterns.com/patterns/black_denim.png" title: "Dark denim" categories: ["dark"] image_dimensions: "145x145" , image_size: "74K" link: "http://subtlepatterns.com/smooth-wall/" description: "Some rectangles, a bit of dust and grunge, plus a hint of concrete." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/smooth_wall.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/smooth_wall.zip" image: "http://subtlepatterns.com/patterns/smooth_wall.png" title: "Smooth Wall" categories: ["light"] image_dimensions: "358x358" , image_size: "622B" link: "http://subtlepatterns.com/131/" description: "Never out of fashion and so much hotter than the 45º everyone knows, here is a sweet 60º line pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/60degree_gray.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/60degree_gray.zip" image: "http://subtlepatterns.com/patterns/60degree_gray.png" title: "60º lines" categories: ["light"] image_dimensions: "31x31" , image_size: "141K" link: "http://subtlepatterns.com/exclusive-paper/" description: "Exclusive looking paper pattern with small dust particles and 45 degree strokes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/exclusive_paper.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/exclusive_paper.zip" image: "http://subtlepatterns.com/patterns/exclusive_paper.png" title: "Exclusive paper" categories: ["light"] image_dimensions: "560x420" , image_size: "43K" link: "http://subtlepatterns.com/paper-2/" description: "New paper pattern with a slightly organic feel to it, using some thin threads." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper_2.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_2.zip" image: "http://subtlepatterns.com/patterns/paper_2.png" title: "Paper 2" categories: ["light"] image_dimensions: "280x280" , image_size: "17K" link: "http://subtlepatterns.com/white-sand/" description: "Same as gray sand but lighter. A sandy pattern with small light dots, and some angled strokes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_sand.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_sand.zip" image: "http://subtlepatterns.com/patterns/white_sand.png" title: "White sand" categories: ["light"] image_dimensions: "211x211" , image_size: "16K" link: "http://subtlepatterns.com/gray-sand/" description: "A dark gray, sandy pattern with small light dots, and some angled strokes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gray_sand.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gray_sand.zip" image: "http://subtlepatterns.com/patterns/gray_sand.png" title: "Gray sand" categories: ["dark"] image_dimensions: "211x211" , image_size: "82K" link: "http://subtlepatterns.com/paper-1/" description: "A slightly grainy paper pattern with small horisontal and vertical strokes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_1.zip" image: "http://subtlepatterns.com/patterns/paper_1.png" title: "Paper 1" categories: ["light"] image_dimensions: "400x400" , image_size: "75K" link: "http://subtlepatterns.com/leather-1/" description: "A leather pattern with a hint of yellow." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/leather_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/leather_1.zip" image: "http://subtlepatterns.com/patterns/leather_1.png" title: "Leather 1" categories: ["light"] image_dimensions: "300x300" , image_size: "133B" link: "http://subtlepatterns.com/white-carbon/" description: "Same as the black version, but now in shades of gray. Very subtle and fine grained." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_carbon.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_carbon.zip" image: "http://subtlepatterns.com/patterns/white_carbon.png" title: "White carbon" categories: ["light"] image_dimensions: "8x8" , image_size: "99K" link: "http://subtlepatterns.com/fabric-1/" description: "Semi light fabric pattern made out of random pixles in shades of gray." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fabric_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fabric_1.zip" image: "http://subtlepatterns.com/patterns/fabric_1.png" title: "Fabric 1" categories: ["light"] image_dimensions: "400x400" , image_size: "117B" link: "http://subtlepatterns.com/micro-carbon/" description: "Three shades of gray makes this pattern look like a small carbon fibre surface. Great readability even for small fonts." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/micro_carbon.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/micro_carbon.zip" image: "http://subtlepatterns.com/patterns/micro_carbon.png" title: "Micro carbon" categories: ["dark"] image_dimensions: "4x4" , image_size: "1K" link: "http://subtlepatterns.com/tactile-noise/" description: "A heavy dark gray base, some subtle noise and a 45 degree grid makes this look like a pattern with a tactile feel to it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tactile_noise.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tactile_noise.zip" image: "http://subtlepatterns.com/patterns/tactile_noise.png" title: "Tactile noise" categories: ["dark"] image_dimensions: "48x48" , image_size: "142B" link: "http://subtlepatterns.com/carbon-fibre-2/" description: "A dark pattern made out of 3×3 circles and a 1px shadow. This works well as a carbon texture or background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/carbon_fibre.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/carbon_fibre.zip" image: "http://subtlepatterns.com/patterns/carbon_fibre.png" title: "Carbon fibre" categories: ["dark"] image_dimensions: "24x22" , image_size: "78K" link: "http://subtlepatterns.com/awesome-pattern/" description: "Medium gray fabric pattern with 45 degree lines going across." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/45degreee_fabric.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/45degreee_fabric.zip" image: "http://subtlepatterns.com/patterns/45degreee_fabric.png" title: "45 degree fabric" categories: ["light"] image_dimensions: "315x315" , image_size: "138B" link: "http://subtlepatterns.com/subtle-carbon/" description: "There are many carbon patterns, but this one is tiny." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_carbon.png" author: "<a href=\"http://www.designova.net\" target=\"_blank\">Designova</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_carbon.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_carbon.png" title: "Subtle Carbon" categories: ["carbon", "dark"] image_dimensions: "18x15" , image_size: "4K" link: "http://subtlepatterns.com/swirl/" description: "The name tells you it has curves. Oh yes it does!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/swirl.png" author: "<a href=\"http://peterchondesign.com\" target=\"_blank\">Peter Chon</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/swirl.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/swirl.png" title: "Swirl" categories: ["light", "swirl"] image_dimensions: "200x200" , image_size: "424B" link: "http://subtlepatterns.com/back-pattern/" description: "Pixel by pixel, sharp and clean. Very light pattern with clear lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/back_pattern.png" author: "M.Ashok" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/back_pattern.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/back_pattern.png" title: "Back pattern" categories: ["light"] image_dimensions: "28x28" , image_size: "470B" link: "http://subtlepatterns.com/translucent-fibres/" description: "The file was named striped lens, but hey – Translucent Fibres works too." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/striped_lens.png" author: "<a href=\"http://fleeting_days.livejournal.com\" target=\"_blank\">Angelica</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/striped_lens.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/striped_lens.png" title: "Translucent Fibres" categories: ["light"] image_dimensions: "16x16" , image_size: "141B" link: "http://subtlepatterns.com/skeletal-weave/" description: "Imagine you zoomed in 1000X on some fabric. But then it turned out to be a skeleton!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/skelatal_weave.png" author: "<a href=\"http://fleeting_days.livejournal.com\" target=\"_blank\">Angelica</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/skelatal_weave.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/skelatal_weave.png" title: "Skeletal Weave" categories: ["light"] image_dimensions: "25x25" , image_size: "191B" link: "http://subtlepatterns.com/black-twill/" description: "Trippy little gradients at an angle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_twill.png" author: "Cary Fleming" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_twill.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_twill.png" title: "Black Twill" categories: ["dark"] image_dimensions: "14x14" , image_size: "150K" link: "http://subtlepatterns.com/asfalt/" description: "A very dark asfalt pattern based off of a photo taken with my iPhone. If you want to tweak it, I put the PSD here (a hint lighter, maybe?)." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/asfalt.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/asfalt.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/asfalt.png" title: "Asfalt" categories: ["asfalt", "dark"] image_dimensions: "466x349" , image_size: "199B" link: "http://subtlepatterns.com/subtle-surface/" description: "Super subtle indeed, a medium gray pattern with tiny dots in a grid." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_surface.png" author: "<a href=\"http://www.designova.net\" target=\"_blank\">Designova</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_surface.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_surface.png" title: "Subtle Surface" categories: ["gray", "light"] image_dimensions: "16x8" , image_size: "99K" link: "http://subtlepatterns.com/retina-wood/" description: "I’m not going to use the word Retina for all the new patterns, but it just felt right for this one. Huge wood pattern for ya’ll." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/retina_wood.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retina_wood.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retina_wood.png" title: "Retina Wood" categories: ["light", "retina", "wood"] image_dimensions: "512x512" , image_size: "1K" link: "http://subtlepatterns.com/subtle-dots/" description: "As simple and subtle as it get’s, but sometimes that’s just what you want." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_dots.png" author: "<a href=\"http://www.designova.net\" target=\"_blank\">Designova</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_dots.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_dots.png" title: "Subtle Dots" categories: ["dots", "light"] image_dimensions: "27x15" , image_size: "89K" link: "http://subtlepatterns.com/dust/" description: "Another one bites the dust! Boyah." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dust.png" author: "<a href=\"http://www.werk.sk\" target=\"_blank\">Dominik Kiss</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dust.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dust.png" title: "Dust" categories: ["light"] image_dimensions: "400x300" , image_size: "1K" link: "http://subtlepatterns.com/use-your-illusion/" description: "A dark one with geometric shapes and dotted lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/use_your_illusion.png" author: "<a href=\"http://www.mohawkstudios.com\" target=\"_blank\">Mohawk Studios</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/use_your_illusion.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/use_your_illusion.png" title: "Use Your Illusion" categories: ["dark"] image_dimensions: "54x58" , image_size: "17K" link: "http://subtlepatterns.com/retina-dust/" description: "First pattern tailor made for Retina, with many more to come. All the old ones are upscaled, in case you want to re-download." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/retina_dust.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retina_dust.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retina_dust.png" title: "Retina dust" categories: ["light", "retina"] image_dimensions: "200x200" , image_size: "8K" link: "http://subtlepatterns.com/gray-lines/" description: "Some more diagonal lines and noise, because you know you want it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_noise_diagonal.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_noise_diagonal.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_noise_diagonal.png" title: "Gray lines" categories: ["diagonal", "light", "noise"] image_dimensions: "150x150" , image_size: "2K" link: "http://subtlepatterns.com/noise-lines/" description: "Lovely pattern with some good looking non-random-noise-lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noise_lines.png" author: "Thomas Zucx" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noise_lines.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noise_lines.png" title: "Noise lines" categories: ["diagonal", "light", "noise"] image_dimensions: "60x59" , image_size: "139B" link: "http://subtlepatterns.com/pyramid/" description: "Could remind you a bit of those squares in Super Mario Bros, yeh?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pyramid.png" author: "Jeff Wall" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pyramid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pyramid.png" title: "Pyramid" categories: ["light"] image_dimensions: "16x16" , image_size: "4K" link: "http://subtlepatterns.com/retro-intro/" description: "A slightly more textured pattern, medium gray. A bit like a potato sack?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/retro_intro.png" author: "<a href=\"http://www.twitter.com/Creartinc\" target=\"_blank\">Bilal Ketab</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retro_intro.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retro_intro.png" title: "Retro Intro" categories: ["light", "textured"] image_dimensions: "109x109" , image_size: "240B" link: "http://subtlepatterns.com/tiny-grid/" description: "You know, tiny and sharp. I’m sure you’ll find a use for it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tiny_grid.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tiny_grid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tiny_grid.png" title: "Tiny Grid" categories: ["grid", "light"] image_dimensions: "26x26" , image_size: "33K" link: "http://subtlepatterns.com/textured-stripes/" description: "A lovely light gray pattern with stripes and a dash of noise." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/textured_stripes.png" author: "<a href=\"http://tiled-bg.blogspot.com\" target=\"_blank\">V Hartikainen</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/textured_stripes.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/textured_stripes.png" title: "Textured Stripes" categories: ["light"] image_dimensions: "256x256" , image_size: "27K" link: "http://subtlepatterns.com/strange-bullseyes/" description: "This is indeed a bit strange, but here’s to the crazy ones!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/strange_bullseyes.png" author: "<a href=\"http://cwbuecheler.com\" target=\"_blank\">Christopher Buecheler</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/strange_bullseyes.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/strange_bullseyes.png" title: "Strange Bullseyes" categories: ["light"] image_dimensions: "300x300" , image_size: "22K" link: "http://subtlepatterns.com/low-contrast-linen/" description: "A smooth mid-tone gray, or low contrast if you will, linen pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/low_contrast_linen.png" author: "Jordan Pittman" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/low_contrast_linen.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/low_contrast_linen.png" title: "Low Contrast Linen" categories: ["dark"] image_dimensions: "256x256" , image_size: "56K" link: "http://subtlepatterns.com/egg-shell/" description: "It’s an egg, in the form of a pattern. This really is 2012." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/egg_shell.png" author: "<a href=\"http://phoenixweiss.me\" target=\"_blank\">Paul Phönixweiß</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/egg_shell.zip" image: "http://subtlepatterns.com/patterns/egg_shell.png" title: "Egg Shell" categories: ["light"] image_dimensions: "256x256" , image_size: "142K" link: "http://subtlepatterns.com/clean-gray-paper/" description: "On a large canvas you can see it tiling, but used on smaller areas it’s beautiful." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/extra_clean_paper.png" author: "<a href=\"http://phoenixweiss.me\" target=\"_blank\">Paul Phönixweiß</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/extra_clean_paper.zip" image: "http://subtlepatterns.com/patterns/extra_clean_paper.png" title: "Clean gray paper" categories: ["light"] image_dimensions: "512x512" , image_size: "443B" link: "http://subtlepatterns.com/norwegian-rose/" description: "I’m not going to lie – if you submit something with the words Norwegian and Rose in it, it’s likely I’ll publish it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/norwegian_rose.png" author: "Fredrik Scheide" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/norwegian_rose.zip" image: "http://subtlepatterns.com/patterns/norwegian_rose.png" title: "Norwegian Rose" categories: ["light", "rose"] image_dimensions: "48x48" , image_size: "291B" link: "http://subtlepatterns.com/subtlenet/" description: "You can never get enough of these tiny pixel patterns with sharp lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtlenet2.png" author: "<a href=\"http://www.designova.net\" target=\"_blank\">Designova</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtlenet2.zip" image: "http://subtlepatterns.com/patterns/subtlenet2.png" title: "SubtleNet" categories: ["light"] image_dimensions: "60x60" , image_size: "32K" link: "http://subtlepatterns.com/dirty-old-black-shirt/" description: "Used in small doses, this could be a nice subtle pattern. Used on a large surface, it’s dirty!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dirty_old_shirt.png" author: "<a href=\"https://twitter.com/#!/PaulReulat\" target=\"_blank\">Paul Reulat</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dirty_old_shirt.zip" image: "http://subtlepatterns.com/patterns/dirty_old_shirt.png" title: "Dirty old black shirt" categories: ["dark"] image_dimensions: "250x250" , image_size: "71K" link: "http://subtlepatterns.com/redox-02/" description: "After 1 comes 2, same but different. You get the idea." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/redox_02.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">Hendrik Lammers</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/redox_02.zip" image: "http://subtlepatterns.com/patterns/redox_02.png" title: "Redox 02" categories: ["light"] image_dimensions: "600x340" , image_size: "88K" link: "http://subtlepatterns.com/redox-01/" description: "Bright gray tones with a hint of some metal surface." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/redox_01.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">Hendrik Lammers</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/redox_01.zip" image: "http://subtlepatterns.com/patterns/redox_01.png" title: "Redox 01" categories: ["light"] image_dimensions: "600x375" , image_size: "51K" link: "http://subtlepatterns.com/skin-side-up/" description: "White fabric looking texture with some nice random wave features." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/skin_side_up.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">Hendrik Lammers</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/skin_side_up.zip" image: "http://subtlepatterns.com/patterns/skin_side_up.png" title: "Skin Side Up" categories: ["light"] image_dimensions: "320x360" , image_size: "211K" link: "http://subtlepatterns.com/solid/" description: "A mid-tone gray patterns with some cement looking texture." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/solid.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">Hendrik Lammers</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/solid.zip" image: "http://subtlepatterns.com/patterns/solid.png" title: "Solid" categories: ["cement", "light"] image_dimensions: "500x500" , image_size: "297B" link: "http://subtlepatterns.com/stitched-wool/" description: "I love these crisp, tiny, super subtle patterns." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/stitched_wool.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\">Badhon Ebrahim</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stitched_wool.zip" image: "http://subtlepatterns.com/patterns/stitched_wool.png" title: "Stitched Wool" categories: ["light"] image_dimensions: "224x128" , image_size: "50K" link: "http://subtlepatterns.com/crisp-paper-ruffles/" description: "Sort of reminds me of those old house wallpapers." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/crisp_paper_ruffles.png" author: "<a href=\"http://www.ayonnette.blogspot.com\" target=\"_blank\">Tish</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/crisp_paper_ruffles.zip" image: "http://subtlepatterns.com/patterns/crisp_paper_ruffles.png" title: "Crisp Paper Ruffles" categories: ["light"] image_dimensions: "481x500" , image_size: "1K" link: "http://subtlepatterns.com/white-linen/" description: "Dead simple but beautiful horizontal line pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/linen.png" author: "<a href=\"http://fabianschultz.de/\" target=\"_blank\">Fabian Schultz</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/linen.zip" image: "http://subtlepatterns.com/patterns/linen.png" title: "White Linen" categories: ["light"] image_dimensions: "400x300" , image_size: "122B" link: "http://subtlepatterns.com/polyester-lite/" description: "A tiny polyester pixel pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/polyester_lite.png" author: "<a href=\"http://dribbble.com/jeremyelder\" target=\"_blank\">Jeremy</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/polyester_lite.zip" image: "http://subtlepatterns.com/patterns/polyester_lite.png" title: "Polyester Lite" categories: ["light"] image_dimensions: "17x22" , image_size: "131K" link: "http://subtlepatterns.com/light-paper-fibers/" description: "More in the paper realm, this time with fibers." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/lightpaperfibers.png" author: "<a href=\"http://www.jorgefuentes.net\" target=\"_blank\">Jorge Fuentes</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/lightpaperfibers.zip" image: "http://subtlepatterns.com/patterns/lightpaperfibers.png" title: "Light paper fibers" categories: ["light"] image_dimensions: "500x300" , image_size: "98K" link: "http://subtlepatterns.com/natural-paper/" description: "You know I’m a sucker for these. Well crafted paper pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/natural_paper.png" author: "Mihaela Hinayon" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/natural_paper.zip" image: "http://subtlepatterns.com/patterns/natural_paper.png" title: "Natural Paper" categories: ["light"] image_dimensions: "523x384" , image_size: "47K" link: "http://subtlepatterns.com/burried/" description: "Have you wondered about how it feels to be buried alive? Here is the pattern for it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/burried.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">Hendrik Lammers</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/burried.zip" image: "http://subtlepatterns.com/patterns/burried.png" title: "Burried" categories: ["dark", "mud"] image_dimensions: "350x350" , image_size: "44K" link: "http://subtlepatterns.com/rebel/" description: "Not the Rebel alliance, but a dark textured pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rebel.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">Hendrik Lammers</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rebel.zip" image: "http://subtlepatterns.com/patterns/rebel.png" title: "Rebel" categories: ["dark"] image_dimensions: "320x360" , image_size: "7K" link: "http://subtlepatterns.com/assault/" description: "Dark, crisp and sort of muddy this one." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/assault.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">Hendrik Lammers</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/assault.zip" image: "http://subtlepatterns.com/patterns/assault.png" title: "Assault" categories: ["dark"] image_dimensions: "154x196" , image_size: "146B" link: "http://subtlepatterns.com/absurdity/" description: "Bit of a strange name on this one, but still nice. Tiny gray square things." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/absurdidad.png" author: "<a href=\"http://saveder.blogspot.mx/\" target=\"_blank\">Carlos Valdez</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/absurdidad.zip" image: "http://subtlepatterns.com/patterns/absurdidad.png" title: "Absurdity" categories: ["light"] image_dimensions: "4x4" , image_size: "103B" link: "http://subtlepatterns.com/white-carbonfiber/" description: "More carbon fiber for your collections. This time in white or semi-dark gray." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_carbonfiber.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\">Badhon Ebrahim</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_carbonfiber.zip" image: "http://subtlepatterns.com/patterns/white_carbonfiber.png" title: "White Carbonfiber" categories: ["carbon", "light"] image_dimensions: "4x4" , image_size: "1K" link: "http://subtlepatterns.com/white-bed-sheet/" description: "Nothing like a clean set of bed sheets, huh?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_bed_sheet.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\">Badhon Ebrahim</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_bed_sheet.zip" image: "http://subtlepatterns.com/patterns/white_bed_sheet.png" title: "White Bed Sheet" categories: ["light"] image_dimensions: "54x54" , image_size: "24K" link: "http://subtlepatterns.com/skewed-print/" description: "An interesting dark spotted pattern at an angle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/skewed_print.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">Hendrik Lammers</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/skewed_print.zip" image: "http://subtlepatterns.com/patterns/skewed_print.png" title: "Skewed print" categories: ["dark"] image_dimensions: "330x320" , image_size: "31K" link: "http://subtlepatterns.com/dark-wall/" description: "Just to prove my point, here is a slightly modified dark version." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_wall.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_wall.zip" image: "http://subtlepatterns.com/patterns/dark_wall.png" title: "Dark Wall" categories: ["dark"] image_dimensions: "300x300" , image_size: "47K" link: "http://subtlepatterns.com/wall-4-light/" description: "I’m starting to think I have a concrete wall fetish." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wall4.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wall4.zip" image: "http://subtlepatterns.com/patterns/wall4.png" title: "Wall #4 Light" categories: ["light"] image_dimensions: "300x300" , image_size: "395B" link: "http://subtlepatterns.com/escheresque/" description: "Cubes as far as your eyes can see. You know, because they tile." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/escheresque.png" author: "<a href=\"http://dribbble.com/janmeeus\" target=\"_blank\">Jan Meeus</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/escheresque.zip" image: "http://subtlepatterns.com/patterns/escheresque.png" title: "Escheresque" categories: ["light"] image_dimensions: "46x29" , image_size: "209B" link: "http://subtlepatterns.com/climpek/" description: "Small gradient crosses inside 45 degree boxes, or bigger crosses if you will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/climpek.png" author: "<a href=\"http://blugraphic.com\" target=\"_blank\">Wassim</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/climpek.zip" image: "http://subtlepatterns.com/patterns/climpek.png" title: "Climpek" categories: ["light"] image_dimensions: "44x44" , image_size: "154B" link: "http://subtlepatterns.com/nistri/" description: "No idea what Nistri means, but it’s a crisp little pattern nonetheless." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/nistri.png" author: "<a href=\"http://reitermark.us/\" target=\"_blank\">Markus Reiter</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/nistri.zip" image: "http://subtlepatterns.com/patterns//nistri.png" title: "Nistri" categories: ["light"] image_dimensions: "38x38" , image_size: "242K" link: "http://subtlepatterns.com/white-wall/" description: "A huge one at 800x600px. Made from a photo I took going home after work." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_wall.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_wall.zip" image: "http://subtlepatterns.com/patterns/white_wall.png" title: "White wall" categories: ["light", "wall"] image_dimensions: "800x600" , image_size: "390B" link: "http://subtlepatterns.com/the-black-mamba/" description: "Super dark, crisp and detailed. And a Kill Bill reference." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_mamba.png" author: "<a href=\"http://graphicriver.net/user/graphcoder?ref=graphcoder\" target=\"_blank\">Badhon Ebrahim</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_mamba.zip" image: "http://subtlepatterns.com/patterns/black_mamba.png" title: "The Black Mamba" categories: ["dark"] image_dimensions: "192x192" , image_size: "8K" link: "http://subtlepatterns.com/diamond-upholstery/" description: "A re-make of the Gradient Squares pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diamond_upholstery.png" author: "<a href=\"http://hellogrid.com\" target=\"_blank\">Dimitar Karaytchev</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diamond_upholstery.zip" image: "http://subtlepatterns.com/patterns/diamond_upholstery.png" title: "Diamond Upholstery" categories: ["diamond", "light"] image_dimensions: "200x200" , image_size: "179B" link: "http://subtlepatterns.com/corrugation/" description: "The act or state of corrugating or of being corrugated, a wrinkle; fold; furrow; ridge." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/corrugation.png" author: "<a href=\"http://graphicriver.net/user/Naf_Naf?ref=Naf_Naf\" target=\"_blank\">Anna Litvinuk</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/corrugation.zip" image: "http://subtlepatterns.com/patterns/corrugation.png" title: "Corrugation" categories: ["light"] image_dimensions: "8x5" , image_size: "479B" link: "http://subtlepatterns.com/reticular-tissue/" description: "Tiny and crisp, just the way it should be." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/reticular_tissue.png" author: "<a href=\"http://graphicriver.net/user/Naf_Naf?ref=Naf_Naf\" target=\"_blank\">Anna Litvinuk</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/reticular_tissue.zip" image: "http://subtlepatterns.com/patterns/reticular_tissue.png" title: "Reticular Tissue" categories: ["light"] image_dimensions: "25x25" , image_size: "408B" link: "http://subtlepatterns.com/lyonnette/" description: "Small crosses with round edges. Quite cute." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/lyonnette.png" author: "<a href=\"http://www.ayonnette.blogspot.com\" target=\"_blank\">Tish</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/lyonnette.zip" image: "http://subtlepatterns.com/patterns/lyonnette.png" title: "Lyonnette" categories: ["light"] image_dimensions: "90x90" , image_size: "21K" link: "http://subtlepatterns.com/light-toast/" description: "Has nothing to do with toast, but it’s nice and subtle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_toast.png" author: "<a href=\"https://twitter.com/#!/pippinlee\" target=\"_blank\">Pippin Lee</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_toast.zip" image: "http://subtlepatterns.com/patterns/light_toast.png" title: "Light Toast" categories: ["light", "noise"] image_dimensions: "200x200" , image_size: "24K" link: "http://subtlepatterns.com/txture/" description: "Dark, lines, noise, tactile. You get the drift." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/txture.png" author: "<a href=\"http://designchomp.com/\" target=\"_blank\">Anatoli Nicolae</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/txture.zip" image: "http://subtlepatterns.com/patterns/txture.png" title: "Txture" categories: ["dark"] image_dimensions: "400x300" , image_size: "6K" link: "http://subtlepatterns.com/gray-floral/" description: "Floral patterns might not be the hottest thing right now, but you never know when you need it!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/greyfloral.png" author: "<a href=\"http://laurenharrison.org\" target=\"_blank\">Lauren</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/greyfloral.zip" image: "http://subtlepatterns.com/patterns/greyfloral.png" title: "Gray Floral" categories: ["floral", "light"] image_dimensions: "150x124" , image_size: "85B" link: "http://subtlepatterns.com/brilliant/" description: "This is so subtle you need to bring your magnifier!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/brillant.png" author: "<a href=\"http://saveder.blogspot.mx/\" target=\"_blank\">Carlos Valdez</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/brillant.zip" image: "http://subtlepatterns.com/patterns/brillant.png" title: "Brilliant" categories: ["light", "subtle"] image_dimensions: "3x3" , image_size: "1K" link: "http://subtlepatterns.com/subtle-stripes/" description: "Vertical lines with a bumpy yet crisp feel to it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_stripes.png" author: "<a href=\"http://cargocollective.com/raasa\" target=\"_blank\">Raasa</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_stripes.zip" image: "http://subtlepatterns.com/patterns/subtle_stripes.png" title: "Subtle stripes" categories: ["light", "stripes"] image_dimensions: "40x40" , image_size: "86K" link: "http://subtlepatterns.com/cartographer/" description: "A topographic map like this has actually been requested a few times, so here you go!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cartographer.png" author: "<a href=\"http://sam.feyaerts.me\" target=\"_blank\">Sam Feyaerts</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cartographer.zip" image: "http://subtlepatterns.com/patterns/cartographer.png" title: "Cartographer" categories: ["cartographer", "dark", "topography"] image_dimensions: "500x499" ]
12086
window.SUBTLEPATTERNS = [ link: "http://subtlepatterns.com/squairy/" description: "Super tiny dots and all sorts of great stuff." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/squairy_light.png" author: "<NAME>" download: "/patterns/squairy_light.zip" image: "/patterns/squairy_light.png" title: "Squairy" categories: ["light"] , link: "http://subtlepatterns.com/binding-light/" description: "Light gray version of the Binding pattern. A bit like fabric." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/binding_light.png" author: "<NAME>" download: "/patterns/binding_light.zip" image: "/patterns/binding_light.png" title: "Binding light" categories: ["light"] , link: "http://subtlepatterns.com/binding-dark/" description: "This works great as-is, or you can tone it down even more." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/binding_dark.png" author: "<NAME>" download: "/patterns/binding_dark.zip" image: "/patterns/binding_dark.png" title: "Binding dark" categories: ["dark"] , link: "http://subtlepatterns.com/ps-neutral/" description: "This one is so simple, yet so good. And you know it. Has to be in the collection." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ps_neutral.png" author: "<a href=\"http://www.gluszczenko.com\" target=\"_blank\">Gluszczenko</a>" download: "/patterns/ps_neutral.zip" image: "/patterns/ps_neutral.png" title: "PS Neutral" categories: ["light"] , link: "http://subtlepatterns.com/wave-grind/" description: "Submitted by DomainsInfo – wtf, right? But hey, a free pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wavegrid.png" author: "<a href=\"http://www.domainsinfo.org/\" target=\"_blank\">DomainsInfo</a>" download: "/patterns/wavegrid.zip" image: "/patterns/wavegrid.png" title: "Wave Grind" categories: ["light"] , link: "http://subtlepatterns.com/textured-paper/" description: "You know I love paper patterns. Here is one from <NAME>. Say thank you!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/textured_paper.png" author: "<a href=\"http://stephen.io\" target=\"_blank\"><NAME></a>" download: "/patterns/textured_paper.zip" image: "/patterns/textured_paper.png" title: "Textured Paper" categories: ["light", "paper"] , link: "http://subtlepatterns.com/grey-washed-wall/" description: "This is a semi-dark pattern, sort of linen-y." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grey_wash_wall.png" author: "<a href=\"http://www.sagive.co.il\" target=\"_blank\">Sagive SEO</a>" download: "/patterns/grey_wash_wall.zip" image: "/patterns/grey_wash_wall.png" title: "Grey Washed Wall" categories: ["dark", "linen"] , link: "http://subtlepatterns.com/p6/" description: "And finally, number 6. Enjoy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/p6.png" author: "<a href=\"http://www.epictextures.com/\" target=\"_blank\"><NAME></a>" download: "/patterns/p6.zip" image: "/patterns/p6.png" title: "P6" categories: ["light"] , link: "http://subtlepatterns.com/p5/" description: "Number five from the same submitter, makes my job easy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/p5.png" author: "<a href=\"http://www.epictextures.com/\" target=\"_blank\"><NAME></a>" download: "/patterns/p5.zip" image: "/patterns/p5.png" title: "P5" categories: ["light"] , link: "http://subtlepatterns.com/p4/" description: "I skipped number 3, cause it wasn’t all that great. Sorry." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/p4.png" author: "<a href=\"http://www.epictextures.com/\" target=\"_blank\"><NAME></a>" download: "/patterns/p4.zip" image: "/patterns/p4.png" title: "P4" categories: ["light"] , image_size: "493B" link: "http://subtlepatterns.com/escheresque-dark/" description: "A comeback for you, the populare Escheresque now in black." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/escheresque_ste.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/escheresque_ste.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/escheresque_ste.png" title: "Escheresque dark" categories: ["dark"] image_dimensions: "46x29" , image_size: "278B" link: "http://subtlepatterns.com/%d0%b2lack-lozenge/" description: "Not the most subtle one, but a nice pattern still." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_lozenge.png" author: "<a href=\"http://www.listvetra.ru\" target=\"_blank\">List<NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_lozenge.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_lozenge.png" title: "Вlack lozenge" categories: ["dark"] image_dimensions: "38x38" , image_size: "3K" link: "http://subtlepatterns.com/kinda-jean/" description: "A nice one indeed, but I got a feeling we have it already? If you spot a copy, let me know on Twitter ." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/kindajean.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Graphiste.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/kindajean.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/kindajean.png" title: "Kind<NAME> Jean" categories: ["light"] image_dimensions: "147x147" , image_size: "72K" link: "http://subtlepatterns.com/paper-fibers/" description: "Just what the name says, paper fibers. Always good to have." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper_fibers.png" author: "<a href=\"http://about.me/heliodor\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_fibers.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_fibers.png" title: "Paper Fibers" categories: ["light"] image_dimensions: "410x410" , image_size: "128B" link: "http://subtlepatterns.com/dark-fish-skin/" description: "It almost looks a bit blurry, but then again so are fishes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_fish_skin.png" author: "<a href=\"http://www.petrsulc.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_fish_skin.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_fish_skin.png" title: "Dark Fish Skin" categories: ["dark"] image_dimensions: "6x12" , image_size: "600B" link: "http://subtlepatterns.com/maze-white/" description: "Just like the black maze, only in light gray. Duh." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pw_maze_white.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Pe<NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pw_maze_white.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pw_maze_white.png" title: "Maze white" categories: ["light"] image_dimensions: "46x23" , image_size: "600B" link: "http://subtlepatterns.com/maze-black/" description: "Classy little maze for you, in two colors even." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pw_maze_black.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Peax.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pw_maze_black.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pw_maze_black.png" title: "Maze black" categories: ["dark"] image_dimensions: "46x23" , image_size: "137B" link: "http://subtlepatterns.com/satin-weave/" description: "Super simple but very nice indeed. Gray with vertical stripes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/satinweave.png" author: "<a href=\"http://www.merxplat.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/satinweave.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/satinweave.png" title: "Satin weave" categories: ["light"] image_dimensions: "24x12" , image_size: "266B" link: "http://subtlepatterns.com/ecailles/" description: "Almost like little fish shells, or dragon skin." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ecailles.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Graphiste.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ecailles.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ecailles.png" title: "Ecailles" categories: ["light"] image_dimensions: "48x20" , image_size: "82K" link: "http://subtlepatterns.com/subtle-grunge/" description: "A heavy hitter at 400x400px, but lovely still." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_grunge.png" author: "<a href=\"http://breezi.com\" target=\"_blank\">Breezi.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_grunge.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_grunge.png" title: "Subtle grunge" categories: ["light"] image_dimensions: "400x400" , image_size: "11K" link: "http://subtlepatterns.com/honey-im-subtle/" description: "First off in 2013, a mid-gray hexagon pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/honey_im_subtle.png" author: "<a href=\"http://www.blof.dk\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/honey_im_subtle.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/honey_im_subtle.png" title: "Honey I’m subtle" categories: ["hexagon", "light"] image_dimensions: "179x132" , image_size: "13K" link: "http://subtlepatterns.com/grey-jean/" description: "Yummy, this is one good looking pattern. Grab it!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gray_jean.png" author: "<a href=\"http://mr.pn\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gray_jean.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gray_jean.png" title: "Grey Jean" categories: ["light"] image_dimensions: "150x150" , image_size: "75K" link: "http://subtlepatterns.com/lined-paper-2/" description: "I know there already is one here, but shit – this is sexy!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/linedpaper.png" author: "<a href=\"http://www.tight.no\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/linedpaper.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/linedpaper.png" title: "Lined paper" categories: ["light"] image_dimensions: "412x300" , image_size: "39K" link: "http://subtlepatterns.com/blach-orchid/" description: "Blach is the new Black." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/blackorchid.png" author: "<a href=\"http://www.hybridixstudio.com\" target=\"_blank\">Hybridixstudio.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blackorchid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blackorchid.png" title: "Blach Orchid" categories: ["dark"] image_dimensions: "300x300" , image_size: "10K" link: "http://subtlepatterns.com/white-wall-2/" description: "A new one called white wall, not by me this time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_wall2.png" author: "<a href=\"https://corabbit.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_wall2.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_wall2.png" title: "White wall 2" categories: ["light"] image_dimensions: "150x150" , image_size: "279B" link: "http://subtlepatterns.com/diagonales-decalees/" description: "Sounds French. Some 3D square diagonals, that’s all you need to know." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagonales_decalees.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Graphiste.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonales_decalees.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonales_decalees.png" title: "Diagonales decalées" categories: ["light"] image_dimensions: "144x48" , image_size: "12K" link: "http://subtlepatterns.com/cream-paper/" description: "Submitted in a cream color, but you know how I like it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/creampaper.png" author: "<a href=\"http://www.strick9design.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/creampaper.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/creampaper.png" title: "Cream paper" categories: ["light"] image_dimensions: "158x144" , image_size: "19K" link: "http://subtlepatterns.com/debut-dark/" description: "Same classic 45 degree pattern with class, dark version." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/debut_dark.png" author: "<a href=\"http://lukemcdonald.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/debut_dark.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/debut_dark.png" title: "Debut dark" categories: ["dark"] image_dimensions: "200x200" , image_size: "18K" link: "http://subtlepatterns.com/debut-light/" description: "Classic 45 degree pattern with class, light version." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/debut_light.png" author: "<a href=\"http://lukemcdonald.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/debut_light.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/debut_light.png" title: "Debut light" categories: ["light"] image_dimensions: "200x200" , image_size: "9K" link: "http://subtlepatterns.com/twinkle-twinkle/" description: "A very dark spotted twinkle pattern for you twinkle needs." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/twinkle_twinkle.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/twinkle_twinkle.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/twinkle_twinkle.png" title: "Twinkle Twinkle" categories: ["dark"] image_dimensions: "360x300" , image_size: "2K" link: "http://subtlepatterns.com/tapestry/" description: "Tiny and subtle. What’s not to love?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tapestry_pattern.png" author: "<a href=\"http://www.pixeden.com\" target=\"_blank\">Pixeden</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tapestry_pattern.zip" image: "http://subtlepatterns.com/patterns/tapestry_pattern.png" title: "Tapestry" categories: ["light"] image_dimensions: "72x61" , image_size: "3K" link: "http://subtlepatterns.com/psychedelic/" description: "Geometric triangles seem to be quite hot these days." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/psychedelic_pattern.png" author: "<a href=\"http://www.pixeden.com\" target=\"_blank\">Pixeden</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/psychedelic_pattern.zip" image: "http://subtlepatterns.com/patterns/psychedelic_pattern.png" title: "Psychedelic" categories: ["light"] image_dimensions: "84x72" , image_size: "2K" link: "http://subtlepatterns.com/triangles-2/" description: "Sharp but soft triangles in light shades of gray." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/triangles_pattern.png" author: "<a href=\"http://www.pixeden.com\" target=\"_blank\">Pixeden</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/triangles_pattern.zip" image: "http://subtlepatterns.com/patterns/triangles_pattern.png" title: "Triangles" categories: ["light"] image_dimensions: "72x72" , image_size: "125B" link: "http://subtlepatterns.com/flower-trail/" description: "Sharp pixel pattern, just like the good old days." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/flowertrail.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/flowertrail.zip" image: "http://subtlepatterns.com/patterns/flowertrail.png" title: "Flower Trail" categories: ["flower", "light"] image_dimensions: "16x16" , image_size: "41K" link: "http://subtlepatterns.com/scribble-light/" description: "A bit like smudged paint or some sort of steel, here is scribble light." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/scribble_light.png" author: "<a href=\"http://thelovelyfox.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/scribble_light.zip" image: "http://subtlepatterns.com/patterns/scribble_light.png" title: "Scribble Light" categories: ["light"] image_dimensions: "304x306" , image_size: "76K" link: "http://subtlepatterns.com/clean-textile/" description: "A nice light textile pattern for your kit." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/clean_textile.png" author: "N8rx" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/clean_textile.zip" image: "http://subtlepatterns.com/patterns/clean_textile.png" title: "Clean Textile" categories: ["light", "textile"] image_dimensions: "420x420" , image_size: "11K" link: "http://subtlepatterns.com/gplay/" description: "A playful triangle pattern with different shades of gray." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gplaypattern.png" author: "<a href=\"http://dhesign.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gplaypattern.zip" image: "http://subtlepatterns.com/patterns/gplaypattern.png" title: "GPlay" categories: ["light"] image_dimensions: "188x178" , image_size: "235B" link: "http://subtlepatterns.com/weave/" description: "Medium gray pattern with small strokes to give a weave effect." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/weave.png" author: "<a href=\"http://wellterned.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/weave.zip" image: "http://subtlepatterns.com/patterns/weave.png" title: "Weave" categories: ["light"] image_dimensions: "35x31" , image_size: "165B" link: "http://subtlepatterns.com/embossed-paper/" description: "One more from Badhon, sharp horizontal lines making an embossed paper feeling." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/embossed_paper.png" author: "<a href=\"http://graphicriver.net/user/graphcoder?ref=graphcoder\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/embossed_paper.zip" image: "http://subtlepatterns.com/patterns/embossed_paper.png" title: "Embossed Paper" categories: ["light"] image_dimensions: "8x10" , image_size: "176B" link: "http://subtlepatterns.com/graphcoders-lil-fiber/" description: "Tiny little fibers making a soft and sweet look." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/lil_fiber.png" author: "<a href=\"http://graphicriver.net/user/graphcoder?ref=graphcoder\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/lil_fiber.zip" image: "http://subtlepatterns.com/patterns/lil_fiber.png" title: "Graphcoders Lil Fiber" categories: ["light"] image_dimensions: "21x35" , image_size: "6K" link: "http://subtlepatterns.com/white-tiles/" description: "A nice and simple white rotated tile pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_tiles.png" author: "<a href=\"http://www.anotherone.fr/\" target=\"_blank\">Another One.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_tiles.zip" image: "http://subtlepatterns.com/patterns/white_tiles.png" title: "White tiles" categories: ["light"] image_dimensions: "800x250" , image_size: "33K" link: "http://subtlepatterns.com/tex2res5/" description: "Number 5 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res5.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res5.zip" image: "http://subtlepatterns.com/patterns/tex2res5.png" title: "Tex2res5" categories: ["light"] image_dimensions: "500x500" , image_size: "92K" link: "http://subtlepatterns.com/tex2res3/" description: "Number 4 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res3.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res3.zip" image: "http://subtlepatterns.com/patterns/tex2res3.png" title: "Tex2res3" categories: ["light"] image_dimensions: "500x500" , image_size: "94K" link: "http://subtlepatterns.com/tex2res1/" description: "Number 3 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res1.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res1.zip" image: "http://subtlepatterns.com/patterns/tex2res1.png" title: "Tex2res1" categories: ["light"] image_dimensions: "500x500" , image_size: "130K" link: "http://subtlepatterns.com/tex2res2/" description: "Number 2 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res2.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res2.zip" image: "http://subtlepatterns.com/patterns/tex2res2.png" title: "Tex2res2" categories: ["light"] image_dimensions: "500x500" , image_size: "151K" link: "http://subtlepatterns.com/tex2res4/" description: "Number 1 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res4.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res4.zip" image: "http://subtlepatterns.com/patterns/tex2res4.png" title: "Tex2res4" categories: ["dark"] image_dimensions: "500x500" , image_size: "813B" link: "http://subtlepatterns.com/arches/" description: "One more in the line of patterns inspired by the Japanese/asian styles. Smooth." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/arches.png" author: "<a href=\"http://www.webdesigncreare.co.uk/\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/arches.zip" image: "http://subtlepatterns.com/patterns/arches.png" title: "Arches" categories: [] image_dimensions: "103x23" , image_size: "141B" link: "http://subtlepatterns.com/shine-caro/" description: "It’s like shine dotted’s sister, only rotated 45 degrees." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/shinecaro.png" author: "<a href=\"http://www.mediumidee.de\" target=\"_blank\">mediumidee.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shinecaro.zip" image: "http://subtlepatterns.com/patterns/shinecaro.png" title: "Shine Caro" categories: ["light", "shiny"] image_dimensions: "9x9" , image_size: "97B" link: "http://subtlepatterns.com/shine-dotted/" description: "Tiny shiny dots all over your screen." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/shinedotted.png" author: "<a href=\"http://www.mediumidee.de\" target=\"_blank\">mediumidee.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shinedotted.zip" image: "http://subtlepatterns.com/patterns/shinedotted.png" title: "Shine dotted" categories: ["dotted", "light"] image_dimensions: "6x5" , image_size: "19K" link: "http://subtlepatterns.com/worn-dots/" description: "These dots are already worn for you, so you don’t have to." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/worn_dots.png" author: "<a href=\"http://mattmcdaniel.me\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/worn_dots.zip" image: "http://subtlepatterns.com/patterns/worn_dots.png" title: "Worn Dots" categories: ["dots", "light"] image_dimensions: "200x200" , image_size: "24K" link: "http://subtlepatterns.com/light-mesh/" description: "Love me some light mesh on a Monday. Sharp." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/lghtmesh.png" author: "<a href=\"http://dribbble.com/bastienwilmotte\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/lghtmesh.zip" image: "http://subtlepatterns.com/patterns/lghtmesh.png" title: "Light Mesh" categories: ["light"] image_dimensions: "256x256" , image_size: "13K" link: "http://subtlepatterns.com/hexellence/" description: "Detailed but still subtle and quite original. Lovely gray shades." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/hexellence.png" author: "<a href=\"http://www.webdesigncreare.co.uk\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/hexellence.zip" image: "http://subtlepatterns.com/patterns/hexellence.png" title: "Hexellence" categories: ["geometric", "light"] image_dimensions: "150x173" , image_size: "21K" link: "http://subtlepatterns.com/dark-tire/" description: "Dark, crisp and subtle. Tiny black lines on top of some noise." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_Tire.png" author: "<a href=\"http://dribbble.com/bastienwilmotte\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_Tire.zip" image: "http://subtlepatterns.com/patterns/dark_Tire.png" title: "Dark Tire" categories: ["dark", "tire"] image_dimensions: "250x250" , image_size: "6K" link: "http://subtlepatterns.com/first-aid-kit/" description: "No, not the band but the pattern. Simple squares in gray tones, of course." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/first_aid_kit.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/first_aid_kit.zip" image: "http://subtlepatterns.com/patterns/first_aid_kit.png" title: "First Aid Kit" categories: ["light"] image_dimensions: "99x99" , image_size: "327B" link: "http://subtlepatterns.com/wide-rectangles/" description: "Simple wide squares with a small indent. Fit’s all." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wide_rectangles.png" author: "<a href=\"http://www.petrsulc.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wide_rectangles.zip" image: "http://subtlepatterns.com/patterns/wide_rectangles.png" title: "Wide rectangles" categories: ["light"] image_dimensions: "32x14" , image_size: "69K" link: "http://subtlepatterns.com/french-stucco/" description: "Fabric-ish patterns are close to my heart. French Stucco to the rescue." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/frenchstucco.png" author: "<a href=\"http://cwbuecheler.com/\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/frenchstucco.zip" image: "http://subtlepatterns.com/patterns/frenchstucco.png" title: "French Stucco" categories: ["light"] image_dimensions: "400x355" , image_size: "13K" link: "http://subtlepatterns.com/light-wool/" description: "Submitted as a black pattern, I made it light and a few steps more subtle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_wool.png" author: "<a href=\"http://www.tall.me.uk\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_wool.zip" image: "http://subtlepatterns.com/patterns/light_wool.png" title: "Light wool" categories: ["light", "wool"] image_dimensions: "190x191" , image_size: "48K" link: "http://subtlepatterns.com/gradient-squares/" description: "It’s big, it’s gradient – and they are square." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gradient_squares.png" author: "<a href=\"http://www.brankic1979.com\" target=\"_blank\">Br<NAME>1<NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gradient_squares.zip" image: "http://subtlepatterns.com/patterns/gradient_squares.png" title: "Gradient Squares" categories: ["gradient", "light", "square"] image_dimensions: "202x202" , image_size: "38K" link: "http://subtlepatterns.com/rough-diagonal/" description: "The classic 45 degree diagonal line pattern, done right." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rough_diagonal.png" author: "<a href=\"http://jorickvanhees.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rough_diagonal.zip" image: "http://subtlepatterns.com/patterns/rough_diagonal.png" title: "Rough diagonal" categories: ["diagonal", "light"] image_dimensions: "256x256" , image_size: "495B" link: "http://subtlepatterns.com/kuji/" description: "An interesting and original pattern from J<NAME>." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/kuji.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/kuji.zip" image: "http://subtlepatterns.com/patterns/kuji.png" title: "Kuji" categories: ["kuji", "light"] image_dimensions: "30x30" , image_size: "241B" link: "http://subtlepatterns.com/little-triangles/" description: "The basic shapes never get old. Simple triangle pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/little_triangles.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/little_triangles.zip" image: "http://subtlepatterns.com/patterns/little_triangles.png" title: "Little triangles" categories: ["light", "triangle"] image_dimensions: "10x11" , image_size: "186B" link: "http://subtlepatterns.com/diamond-eyes/" description: "Everyone loves a diamond, right? Make your site sparkle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/daimond_eyes.png" author: "<a href=\"http://ajtroxell.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/daimond_eyes.zip" image: "http://subtlepatterns.com/patterns/daimond_eyes.png" title: "Diamond Eyes" categories: ["diamond", "light"] image_dimensions: "33x25" , image_size: "8K" link: "http://subtlepatterns.com/arabesque/" description: "Intricate pattern with arab influences." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/arab_tile.png" author: "<a href=\"http://www.twitter.com/davidsancar\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/arab_tile.zip" image: "http://subtlepatterns.com/patterns/arab_tile.png" title: "Arabesque" categories: ["arab", "light"] image_dimensions: "110x110" , image_size: "314B" link: "http://subtlepatterns.com/white-wave/" description: "Light and tiny just the way you like it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_wave.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_wave.zip" image: "http://subtlepatterns.com/patterns/white_wave.png" title: "White Wave" categories: ["light", "wave"] image_dimensions: "23x12" , image_size: "1K" link: "http://subtlepatterns.com/diagonal-striped-brick/" description: "Might not be super subtle, but quite original in it’s form." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagonal_striped_brick.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonal_striped_brick.zip" image: "http://subtlepatterns.com/patterns/diagonal_striped_brick.png" title: "Diagonal Striped Brick" categories: ["light"] image_dimensions: "150x150" , image_size: "217K" link: "http://subtlepatterns.com/purty-wood/" description: "You know you love wood patterns, so here’s one more." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/purty_wood.png" author: "<a href=\"http://www.purtypixels.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/purty_wood.zip" image: "http://subtlepatterns.com/patterns/purty_wood.png" title: "Purty Wood" categories: ["light", "wood"] image_dimensions: "400x400" , image_size: "412B" link: "http://subtlepatterns.com/vaio-pattern/" description: "I’m guessing this is related to the Sony Vaio? It’s a nice pattern no matter where it’s from." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/vaio_hard_edge.png" author: "<a href=\"http://www.zigzain.com\" target=\"_blank\">Z<NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/vaio_hard_edge.zip" image: "http://subtlepatterns.com/patterns/vaio_hard_edge.png" title: "Vaio" categories: ["light", "sony", "vaio"] image_dimensions: "37x28" , image_size: "123B" link: "http://subtlepatterns.com/stacked-circles/" description: "A simple circle. That’s all it takes. This one is even transparent, for those who like that." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/stacked_circles.png" author: "<a href=\"http://www.960development.com\" target=\"_blank\">Saqib.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stacked_circles.zip" image: "http://subtlepatterns.com/patterns/stacked_circles.png" title: "Stacked Circles" categories: ["circle", "light", "tiny"] image_dimensions: "9x9" , image_size: "102B" link: "http://subtlepatterns.com/outlets/" description: "Just 4x8px, but still so stylish!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/outlets.png" author: "<a href=\"http://michalchovanec.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/outlets.zip" image: "http://subtlepatterns.com/patterns/outlets.png" title: "Outlets" categories: ["dark", "tiny"] image_dimensions: "4x8" , image_size: "41K" link: "http://subtlepatterns.com/light-sketch/" description: "Nice and gray, just the way I like it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/furley_bg.png" author: "<a href=\"http://dankruse.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/furley_bg.zip" image: "http://subtlepatterns.com/patterns/furley_bg.png" title: "Light Sketch" categories: ["light"] image_dimensions: "600x600" , image_size: "126B" link: "http://subtlepatterns.com/tasky/" description: "Your eyes can trip a bit from looking at this – use it wisely." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tasky_pattern.png" author: "<a href=\"http://michalchovanec.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tasky_pattern.zip" image: "http://subtlepatterns.com/patterns/tasky_pattern.png" title: "Tasky" categories: ["dark", "zigzag"] image_dimensions: "10x10" , image_size: "58K" link: "http://subtlepatterns.com/pinstriped-suit/" description: "Just like your old suit, all striped and smooth." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pinstriped_suit.png" author: "<a href=\"http://www.alexberkowitz.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pinstriped_suit.zip" image: "http://subtlepatterns.com/patterns/pinstriped_suit.png" title: "Pinstriped Suit" categories: ["dark", "suit"] image_dimensions: "400x333" , image_size: "240B" link: "http://subtlepatterns.com/blizzard/" description: "This is so subtle I hope you can see it! Tweak at will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/blizzard.png" author: "<a href=\"http://www.alexandrenaud.fr\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blizzard.zip" image: "http://subtlepatterns.com/patterns/blizzard.png" title: "Blizzard" categories: ["blizzard", "light"] image_dimensions: "25x25" , image_size: "1K" link: "http://subtlepatterns.com/bo-play/" description: "Inspired by the B&O Play , I had to make this pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/bo_play_pattern.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bo_play_pattern.zip" image: "http://subtlepatterns.com/patterns/bo_play_pattern.png" title: "BO Play" categories: ["bo", "carbon", "dark", "play"] image_dimensions: "42x22" , image_size: "152K" link: "http://subtlepatterns.com/farmer/" description: "Farmer could be some sort of fabric pattern, with a hint of green." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/farmer.png" author: "<a href=\"http://fabianschultz.de\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/farmer.zip" image: "http://subtlepatterns.com/patterns/farmer.png" title: "Farmer" categories: ["farmer", "light", "paper"] image_dimensions: "349x349" , image_size: "83K" link: "http://subtlepatterns.com/paper/" description: "Nicely crafted paper pattern, all though a bit on the large side (500x593px)." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper.png" author: "<a href=\"http://timeproduction.ru\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper.zip" image: "http://subtlepatterns.com/patterns/paper.png" title: "Paper" categories: ["light", "paper"] image_dimensions: "500x593" , image_size: "167K" link: "http://subtlepatterns.com/tileable-wood/" description: "Not so subtle, and the name is obvious – these tilable wood patterns are very useful." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tileable_wood_texture.png" author: "<a href=\"http://elemisfreebies.com/\" target=\"_blank\">Elemis.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tileable_wood_texture.zip" image: "http://subtlepatterns.com/patterns/tileable_wood_texture.png" title: "Tileable wood" categories: ["light", "wood"] image_dimensions: "400x317" , image_size: "25K" link: "http://subtlepatterns.com/vintage-speckles/" description: "Lovely pattern with splattered vintage speckles." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/vintage_speckles.png" author: "<a href=\"http://simpleasmilk.co.uk\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/vintage_speckles.zip" image: "http://subtlepatterns.com/patterns/vintage_speckles.png" title: "Vintage Speckles" categories: ["light", "vintage"] image_dimensions: "400x300" , image_size: "463B" link: "http://subtlepatterns.com/quilt/" description: "Not sure what this is, but it looks good!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/quilt.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/quilt.zip" image: "http://subtlepatterns.com/patterns/quilt.png" title: "Quilt" categories: ["light", "quilt"] image_dimensions: "25x24" , image_size: "139K" link: "http://subtlepatterns.com/large-leather/" description: "More leather, and this time it’s bigger! You know, in case you need that." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/large_leather.png" author: "<a href=\"http://elemisfreebies.com/\" target=\"_blank\">Elemis.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/large_leather.zip" image: "http://subtlepatterns.com/patterns/large_leather.png" title: "Large leather" categories: ["leather", "light"] image_dimensions: "400x343" , image_size: "108B" link: "http://subtlepatterns.com/dark-dot/" description: "That’s what it is, a dark dot. Or sort of carbon-ish looking." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_dotted.png" author: "<a href=\"http://dribbble.com/bscsystem\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_dotted.zip" image: "http://subtlepatterns.com/patterns/dark_dotted.png" title: "Dark dot" categories: ["dark"] image_dimensions: "5x5" , image_size: "4K" link: "http://subtlepatterns.com/grid-noise/" description: "Crossing lines on a light background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grid_noise.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grid_noise.zip" image: "http://subtlepatterns.com/patterns/grid_noise.png" title: "Grid noise" categories: ["light"] image_dimensions: "98x98" , image_size: "1K" link: "http://subtlepatterns.com/argyle/" description: "Classy golf-pants pattern, or crossed stripes if you will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/argyle.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/argyle.zip" image: "http://subtlepatterns.com/patterns/argyle.png" title: "Argyle" categories: ["dark"] image_dimensions: "106x96" , image_size: "6K" link: "http://subtlepatterns.com/grey-sandbag/" description: "A bit strange this one, but nice at the same time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grey_sandbag.png" author: "<a href=\"http://www.diogosilva.net\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grey_sandbag.zip" image: "http://subtlepatterns.com/patterns/grey_sandbag.png" title: "Grey Sandbag" categories: ["light", "sandbag"] image_dimensions: "100x98" , image_size: "52K" link: "http://subtlepatterns.com/white-leather-2/" description: "I took the liberty of using Dmitry’s pattern and made a version without perforation." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_leather.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">At<NAME> Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_leather.zip" image: "http://subtlepatterns.com/patterns/white_leather.png" title: "White leather" categories: ["leather", "light"] image_dimensions: "300x300" , image_size: "92K" link: "http://subtlepatterns.com/ice-age/" description: "I asked Gjermund if he could make a pattern for us – result!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ice_age.png" author: "<a href=\"http://tight.no\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ice_age.zip" image: "http://subtlepatterns.com/patterns/ice_age.png" title: "Ice age" categories: ["ice", "light", "snow"] image_dimensions: "400x400" , image_size: "55K" link: "http://subtlepatterns.com/perforated-white-leather/" description: "A bit of scratched up grayness. Always good." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/perforated_white_leather.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/perforated_white_leather.zip" image: "http://subtlepatterns.com/patterns/perforated_white_leather.png" title: "Perforated White Leather" categories: ["leather", "light"] image_dimensions: "300x300" , image_size: "7K" link: "http://subtlepatterns.com/church/" description: "I have no idea what <NAME> means by this name, but hey – it’s hot." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/chruch.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/chruch.zip" image: "http://subtlepatterns.com/patterns/chruch.png" title: "Church" categories: ["light"] image_dimensions: "100x100" , image_size: "82K" link: "http://subtlepatterns.com/old-husks/" description: "A bit of scratched up grayness. Always good." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/husk.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/husk.zip" image: "http://subtlepatterns.com/patterns/husk.png" title: "Old husks" categories: ["brushed", "light"] image_dimensions: "500x500" , image_size: "379B" link: "http://subtlepatterns.com/cutcube/" description: "Cubes, geometry, 3D. What’s not to love?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cutcube.png" author: "<a href=\"http://cubecolour.co.uk\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cutcube.zip" image: "http://subtlepatterns.com/patterns/cutcube.png" title: "Cutcube" categories: ["3d", "cube", "light"] image_dimensions: "20x36" , image_size: "91K" link: "http://subtlepatterns.com/snow/" description: "Real snow that tiles, not easy. This is not perfect, but an attempt." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/snow.png" author: "<a href=\"http://www.atlemo.com/\" target=\"_blank\">At<NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/snow.zip" image: "http://subtlepatterns.com/patterns/snow.png" title: "Snow" categories: ["light", "snow"] image_dimensions: "500x500" , image_size: "25K" link: "http://subtlepatterns.com/cross-scratches/" description: "Subtle scratches on a light gray background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cross_scratches.png" author: "<a href=\"http://www.ovcharov.me/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cross_scratches.zip" image: "http://subtlepatterns.com/patterns/cross_scratches.png" title: "Cross scratches" categories: ["light", "scratch"] image_dimensions: "256x256" , image_size: "403B" link: "http://subtlepatterns.com/subtle-zebra-3d/" description: "It’s a subtle zebra, in 3D. Oh yes!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_zebra_3d.png" author: "<a href=\"http://www.miketheindian.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_zebra_3d.zip" image: "http://subtlepatterns.com/patterns/subtle_zebra_3d.png" title: "Subtle Zebra 3D" categories: ["3d", "light"] image_dimensions: "121x38" , image_size: "494B" link: "http://subtlepatterns.com/fake-luxury/" description: "Fake or not, it’s quite luxurious." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fake_luxury.png" author: "<a href=\"http://www.factorio.us\" target=\"_blank\">Factorio.us Collective</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fake_luxury.zip" image: "http://subtlepatterns.com/patterns/fake_luxury.png" title: "Fake luxury" categories: ["light"] image_dimensions: "16x26" , image_size: "817B" link: "http://subtlepatterns.com/dark-geometric/" description: "Continuing the geometric trend, here is one more." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_geometric.png" author: "<a href=\"http://www.miketheindian.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_geometric.zip" image: "http://subtlepatterns.com/patterns/dark_geometric.png" title: "Dark Geometric" categories: ["dark", "geometric"] image_dimensions: "70x70" , image_size: "5K" link: "http://subtlepatterns.com/blu-stripes/" description: "Very simple, very blu(e). Subtle and nice." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/blu_stripes.png" author: "<a href=\"http://twitter.com/iamsebj\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blu_stripes.zip" image: "http://subtlepatterns.com/patterns/blu_stripes.png" title: "Blu Stripes" categories: ["blue", "light", "stripes"] image_dimensions: "100x100" , image_size: "128K" link: "http://subtlepatterns.com/texturetastic-gray/" description: "This ladies and gentlemen, is texturetastic! Love it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/texturetastic_gray.png" author: "<a href=\"http://www.adampickering.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/texturetastic_gray.zip" image: "http://subtlepatterns.com/patterns/texturetastic_gray.png" title: "Texturetastic Gray" categories: ["fabric", "light", "tactile"] image_dimensions: "476x476" , image_size: "220B" link: "http://subtlepatterns.com/soft-pad/" description: "Bumps, highlight and shadows – all good things." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/soft_pad.png" author: "<a href=\"http://ow.ly/8v3IG\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/soft_pad.zip" image: "http://subtlepatterns.com/patterns/soft_pad.png" title: "Soft Pad" categories: ["light"] image_dimensions: "8x8" , image_size: "8K" link: "http://subtlepatterns.com/classy-fabric/" description: "This is lovely, just the right amount of subtle noise, lines and textures." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/classy_fabric.png" author: "<a href=\"http://www.purtypixels.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/classy_fabric.zip" image: "http://subtlepatterns.com/patterns/classy_fabric.png" title: "Classy Fabric" categories: ["classy", "dark", "fabric"] image_dimensions: "102x102" , image_size: "911B" link: "http://subtlepatterns.com/hixs-evolution/" description: "Quite some heavy depth and shadows here, but might work well on some mobile apps?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/hixs_pattern_evolution.png" author: "<a href=\"http://www.hybridixstudio.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/hixs_pattern_evolution.zip" image: "http://subtlepatterns.com/patterns/hixs_pattern_evolution.png" title: "HIXS Evolution" categories: ["dark", "hexagon", "hixs"] image_dimensions: "35x34" , image_size: "2K" link: "http://subtlepatterns.com/subtle-dark-vertical/" description: "Classic vertical lines, in all it’s subtlety." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dvsup.png" author: "<a href=\"http://tirl.tk/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dvsup.zip" image: "http://subtlepatterns.com/patterns/dvsup.png" title: "Subtle Dark Vertical" categories: ["dark", "lines", "vertical"] image_dimensions: "40x40" , image_size: "225B" link: "http://subtlepatterns.com/grid-me/" description: "Nice little grid. Would work great as a base on top of some other patterns." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gridme.png" author: "<a href=\"http://www.gobigbang.nl\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gridme.zip" image: "http://subtlepatterns.com/patterns/gridme.png" title: "Grid Me" categories: ["grid", "light"] image_dimensions: "50x50" , image_size: "2K" link: "http://subtlepatterns.com/knitted-netting/" description: "A bit like some carbon, or knitted netting if you will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/knitted-netting.png" author: "<a href=\"http://graphicriver.net/user/Naf_Naf?ref=Naf_Naf\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/knitted-netting.zip" image: "http://subtlepatterns.com/patterns/knitted-netting.png" title: "Knitted Netting" categories: ["carbon", "light", "netting"] image_dimensions: "8x8" , image_size: "166B" link: "http://subtlepatterns.com/dark-matter/" description: "The name is totally random, but hey, it sounds good?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_matter.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_matter.zip" image: "http://subtlepatterns.com/patterns/dark_matter.png" title: "Dark matter" categories: ["dark", "noise", "pixles"] image_dimensions: "7x7" , image_size: "783B" link: "http://subtlepatterns.com/black-thread/" description: "Geometric lines are always hot, and this pattern is no exception." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_thread.png" author: "<a href=\"http://listvetra.ru/\" target=\"_blank\">List<NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_thread.zip" image: "http://subtlepatterns.com/patterns/black_thread.png" title: "Black Thread" categories: ["dark", "geometry"] image_dimensions: "49x28" , image_size: "173K" link: "http://subtlepatterns.com/vertical-cloth/" description: "You just can’t get enough of the fabric patterns, so here is one more for your collection." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/vertical_cloth.png" author: "<a href=\"http://dribbble.com/krisp\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/vertical_cloth.zip" image: "http://subtlepatterns.com/patterns/vertical_cloth.png" title: "Vertical cloth" categories: ["cloth", "dark", "fabric", "lines"] image_dimensions: "399x400" , image_size: "22K" link: "http://subtlepatterns.com/934/" description: "This is the third pattern called Dark Denim, but hey, we all love them!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/darkdenim3.png" author: "<a href=\"http://www.brandonjacoby.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/darkdenim3.zip" image: "http://subtlepatterns.com/patterns/darkdenim3.png" title: "Dark Denim 3" categories: ["dark", "denim"] image_dimensions: "420x326" , image_size: "255B" link: "http://subtlepatterns.com/white-brick-wall/" description: "If you’re sick of the fancy 3d, grunge and noisy patterns, take a look at this flat 2d brick wall." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_brick_wall.png" author: "<a href=\"http://listvetra.ru/\" target=\"_blank\">Listvetra</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_brick_wall.zip" image: "http://subtlepatterns.com/patterns/white_brick_wall.png" title: "White Brick Wall" categories: ["brick", "light", "wall"] image_dimensions: "24x16" , image_size: "5K" link: "http://subtlepatterns.com/fabric-plaid/" description: "You know you can’t get enough of these linen-fabric-y patterns." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fabric_plaid.png" author: "<a href=\"http://twitter.com/jbasoo\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fabric_plaid.zip" image: "http://subtlepatterns.com/patterns/fabric_plaid.png" title: "Fabric (Plaid)" categories: ["fabric", "light", "plaid"] image_dimensions: "200x200" , image_size: "146B" link: "http://subtlepatterns.com/merely-cubed/" description: "Tiny, tiny 3D cubes. Reminds me of the good old pattern from k10k." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/merely_cubed.png" author: "<a href=\"http://www.etiennerallion.fr\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/merely_cubed.zip" image: "http://subtlepatterns.com/patterns/merely_cubed.png" title: "Merely Cubed" categories: ["3d", "light"] image_dimensions: "16x16" , image_size: "54K" link: "http://subtlepatterns.com/iron-grip/" description: "Sounds like something from World of Warcraft. Has to be good." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/irongrip.png" author: "<a href=\"http://www.tonykinard.net\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/irongrip.zip" image: "http://subtlepatterns.com/patterns/irongrip.png" title: "Iron Grip" categories: ["dark", "grip", "iron"] image_dimensions: "300x301" , image_size: "847B" link: "http://subtlepatterns.com/starring/" description: "If you need stars, this is the one to get." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/starring.png" author: "<a href=\"http://logosmile.net/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/starring.zip" image: "http://subtlepatterns.com/patterns/starring.png" title: "Starring" categories: ["dark", "star", "stars"] image_dimensions: "35x39" , image_size: "1K" link: "http://subtlepatterns.com/pineapple-cut/" description: "I love the movie Pineapple Express, and I’m also liking this Pineapple right here." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pineapplecut.png" author: "<a href=\"http://audeemirza.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pineapplecut.zip" image: "http://subtlepatterns.com/patterns/pineapplecut.png" title: "Pineapple Cut" categories: ["light"] image_dimensions: "36x62" , image_size: "13K" link: "http://subtlepatterns.com/grilled-noise/" description: "You could get a bit dizzy from this one, but it might come in handy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grilled.png" author: "<a href=\"http://30.nl\" target=\"_blank\">D<NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grilled.zip" image: "http://subtlepatterns.com/patterns/grilled.png" title: "Grilled noise" categories: ["dizzy", "light"] image_dimensions: "170x180" , image_size: "2K" link: "http://subtlepatterns.com/foggy-birds/" description: "Hey, you never know when you’ll need a bird-pattern, right?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/foggy_birds.png" author: "<a href=\"http://buttonpresser.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/foggy_birds.zip" image: "http://subtlepatterns.com/patterns/foggy_birds.png" title: "Foggy Birds" categories: ["bird", "light"] image_dimensions: "206x206" , image_size: "39K" link: "http://subtlepatterns.com/groovepaper/" description: "With a name like this, it has to be hot. Diagonal lines in light shades." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/groovepaper.png" author: "<a href=\"http://graphicriver.net/user/krispdesigns\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/groovepaper.zip" image: "http://subtlepatterns.com/patterns/groovepaper.png" title: "Groovepaper" categories: ["diagonal", "light"] image_dimensions: "300x300" , image_size: "277B" link: "http://subtlepatterns.com/nami/" description: "Not sure if this is related to the Nami you get in Google image search, but hey, it’s nice!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/nami.png" author: "<a href=\"http://30.nl\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/nami.zip" image: "http://subtlepatterns.com/patterns/nami.png" title: "<NAME>" categories: ["anime", "asian", "dark"] image_dimensions: "16x16" , image_size: "154B" link: "http://subtlepatterns.com/medic-packaging-foil/" description: "8 by 8 pixels, and just what the title says." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/foil.png" author: "<a href=\"http://be.net/pixilated\" target=\"_blank\">pixilated</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/foil.zip" image: "http://subtlepatterns.com/patterns/foil.png" title: "Medic Packaging Foil" categories: ["foil", "light", "medic", "paper"] image_dimensions: "8x8" , image_size: "30K" link: "http://subtlepatterns.com/white-paperboard/" description: "Could be paper, could be a polaroid frame – up to you!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_paperboard.png" author: "Chaos" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_paperboard.zip" image: "http://subtlepatterns.com/patterns/white_paperboard.png" title: "White Paperboard" categories: ["light", "paper", "paperboard", "polaroid"] image_dimensions: "256x252" , image_size: "20K" link: "http://subtlepatterns.com/dark-denim-2/" description: "Thin lines, noise and texture creates this crisp dark denim pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/denim.png" author: "<a href=\"http://slootenweb.nl\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/denim.zip" image: "http://subtlepatterns.com/patterns/denim.png" title: "Dark Denim" categories: ["dark", "denim"] image_dimensions: "135x135" , image_size: "101K" link: "http://subtlepatterns.com/wood-pattern/" description: "One of the few “full color” patterns here, but this one was just too good to pass up." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wood_pattern.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wood_pattern.zip" image: "http://subtlepatterns.com/patterns/wood_pattern.png" title: "Wood pattern" categories: ["light", "wood"] image_dimensions: "203x317" , image_size: "28K" link: "http://subtlepatterns.com/white-plaster/" description: "Sweet and subtle white plaster with hints of noise and grunge." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_plaster.png" author: "<a href=\"http://aurer.co.uk\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_plaster.zip" image: "http://subtlepatterns.com/patterns/white_plaster.png" title: "White plaster" categories: ["light"] image_dimensions: "300x300" , image_size: "9K" link: "http://subtlepatterns.com/white-diamond/" description: "To celebrate the new feature, we need some sparkling diamonds." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/whitediamond.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/whitediamond.zip" image: "http://subtlepatterns.com/patterns/whitediamond.png" title: "White Diamond" categories: ["diamond", "light", "triangle"] image_dimensions: "128x224" , image_size: "81K" link: "http://subtlepatterns.com/broken-noise/" description: "Beautiful dark noise pattern with some dust and grunge." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/broken_noise.png" author: "<a href=\"http://vincentklaiber.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/broken_noise.zip" image: "http://subtlepatterns.com/patterns/broken_noise.png" title: "Broken noise" categories: ["broken", "dark", "grunge", "noise"] image_dimensions: "476x476" , image_size: "153B" link: "http://subtlepatterns.com/gun-metal/" description: "With a name this awesome, how can I go wrong?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gun_metal.png" author: "<a href=\"http://www.zigzain.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gun_metal.zip" image: "http://subtlepatterns.com/patterns/gun_metal.png" title: "Gun metal" categories: ["dark", "gun", "metal"] image_dimensions: "10x10" , image_size: "221B" link: "http://subtlepatterns.com/fake-brick/" description: "Black, simple, elegant & useful." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fake_brick.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fake_brick.zip" image: "http://subtlepatterns.com/patterns/fake_brick.png" title: "Fake brick" categories: ["dark", "dots"] image_dimensions: "76x76" , image_size: "295B" link: "http://subtlepatterns.com/candyhole/" description: "It’s a hole, in a pattern. On your website. Dig it!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/candyhole.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/candyhole.zip" image: "http://subtlepatterns.com/patterns/candyhole.png" title: "Candyhole" categories: ["hole", "light"] image_dimensions: "25x25" , image_size: "50K" link: "http://subtlepatterns.com/ravenna/" description: "I guess this is inspired by the city of Ravenna in Italy and it’s stone walls." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ravenna.png" author: "<a href=\"http://sentel.co\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ravenna.zip" image: "http://subtlepatterns.com/patterns/ravenna.png" title: "Ravenna" categories: ["light", "stone", "stones", "wall"] image_dimensions: "387x201" , image_size: "235B" link: "http://subtlepatterns.com/small-crackle-bright/" description: "Light gray pattern with an almost wall tile-like appearance." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/small-crackle-bright.png" author: "<a href=\"http://www.markustinner.ch\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/small-crackle-bright.zip" image: "http://subtlepatterns.com/patterns/small-crackle-bright.png" title: "Small crackle bright" categories: ["light"] image_dimensions: "14x14" , image_size: "29K" link: "http://subtlepatterns.com/nasty-fabric/" description: "Nasty or not, it’s a nice pattern that tiles. Like they all do." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/nasty_fabric.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/nasty_fabric.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/nasty_fabric.png" title: "Nasty Fabric" categories: ["light"] image_dimensions: "198x200" , image_size: "997B" link: "http://subtlepatterns.com/diagonal-waves/" description: "It has waves, so make sure you don’t get sea sickness." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagonal_waves.png" author: "<a href=\"http://coolpatterns.net\" target=\"_blank\">CoolPatterns.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonal_waves.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonal_waves.png" title: "Diagonal Waves" categories: ["light"] image_dimensions: "38x38" , image_size: "10K" link: "http://subtlepatterns.com/otis-redding/" description: "<NAME> was an American soul singer-songwriter, record producer, arranger, and talent scout. So you know." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/otis_redding.png" author: "<a href=\"http://thomasmyrman.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/otis_redding.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/otis_redding.png" title: "Otis Redding" categories: ["light"] image_dimensions: "100x100" , image_size: "10K" link: "http://subtlepatterns.com/billie-holiday/" description: "No relation to the band, but damn it’s subtle!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/billie_holiday.png" author: "<a href=\"http://thomasmyrman.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/billie_holiday.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/billie_holiday.png" title: "Billie Holiday" categories: ["light"] image_dimensions: "100x100" , image_size: "196B" link: "http://subtlepatterns.com/az-subtle/" description: "The A – Z of Subtle? Up to you." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/az_subtle.png" author: "<a href=\"http://www.azmind.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/az_subtle.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/az_subtle.png" title: "AZ Subtle" categories: ["light"] image_dimensions: "100x100" , image_size: "21K" link: "http://subtlepatterns.com/wild-oliva/" description: "Wild Oliva or Oliva Wilde? Darker than the others, sort of a medium dark pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wild_oliva.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wild_oliva.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wild_oliva.png" title: "Wild Oliva" categories: ["dark"] image_dimensions: "198x200" , image_size: "16K" link: "http://subtlepatterns.com/stressed-linen/" description: "We have some linen patterns here, but none that are stressed. Until now." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/stressed_linen.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stressed_linen.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stressed_linen.png" title: "Stressed Linen" categories: ["dark"] image_dimensions: "256x256" , image_size: "116K" link: "http://subtlepatterns.com/navy/" description: "It was called Navy Blue, but I made it dark. You know, the way I like it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/navy_blue.png" author: "<a href=\"http://ultranotch.com/\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/navy_blue.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/navy_blue.png" title: "Navy" categories: ["dark"] image_dimensions: "600x385" , image_size: "106B" link: "http://subtlepatterns.com/simple-horizontal-light/" description: "Some times you just need the simplest thing." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/shl.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shl.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shl.png" title: "Simple Horizontal Light" categories: ["light"] image_dimensions: "4x4" , image_size: "661B" link: "http://subtlepatterns.com/cream_dust/" description: "I love cream! 50x50px and lovely in all the good ways." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cream_dust.png" author: "<a href=\"http://thomasmyrman.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cream_dust.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cream_dust.png" title: "Cream Dust" categories: ["light"] image_dimensions: "50x50" , link: "http://subtlepatterns.com/slash-it/" description: "I have no idea what this is, but it’s tiny and it tiles. Whey!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/slash_it.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\">Venam</a>" download: "/patterns/slash_it.zip" image: "/patterns/slash_it.png" title: "Slash it" categories: ["dark"] , link: "http://subtlepatterns.com/simple-dashed/" description: "Tiny lines going both ways – not the way you think, silly." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/simple_dashed.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\"><NAME></a>" download: "/patterns/simple_dashed.zip" image: "/patterns/simple_dashed.png" title: "Simple Dashed" categories: ["dark"] , link: "http://subtlepatterns.com/moulin/" description: "No relation to Moulin Rouge, but still sexy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/moulin.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\"><NAME></a>" download: "/patterns/moulin.zip" image: "/patterns/moulin.png" title: "Moulin" categories: ["dark"] , link: "http://subtlepatterns.com/dark-exa/" description: "Looks a bit like little bugs, but they are harmless." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_exa.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\"><NAME></a>" download: "/patterns/dark_exa.zip" image: "/patterns/dark_exa.png" title: "Dark Exa" categories: ["dark"] , link: "http://subtlepatterns.com/dark-dotted-2/" description: "Dark dots never go out of fashion, do they? Nope." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_dotted2.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\"><NAME></a>" download: "/patterns/dark_dotted2.zip" image: "/patterns/dark_dotted2.png" title: "Dark Dotted 2" categories: ["dark", "dots"] , image_size: "191B" link: "http://subtlepatterns.com/graphy/" description: "Looks like a technical drawing board, small squares forming a nice grid." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/graphy.png" author: "<a href=\"http://www.wearepixel8.com\" target=\"_blank\">We Are Pixel8</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/graphy.zip" image: "http://subtlepatterns.com/patterns/graphy.png" title: "Graphy" categories: ["grid", "light", "maths"] image_dimensions: "80x160" , image_size: "861B" link: "http://subtlepatterns.com/connected/" description: "White circles connecting on a light gray background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/connect.png" author: "<a href=\"http://pixxel.co/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/connect.zip" image: "http://subtlepatterns.com/patterns/connect.png" title: "Connected" categories: ["connection", "dots", "light"] image_dimensions: "160x160" , image_size: "36K" link: "http://subtlepatterns.com/old-wall/" description: "Old concrete wall in light shades." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/old_wall.png" author: "<a href=\"http://twitter.com/simek\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/old_wall.zip" image: "http://subtlepatterns.com/patterns/old_wall.png" title: "Old wall" categories: ["concrete", "light", "sement", "wall"] image_dimensions: "300x300" , image_size: "1K" link: "http://subtlepatterns.com/light-grey-floral-motif/" description: "Lovely light gray floral motif with some subtle shades." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_grey_floral_motif.png" author: "<a href=\"http://www.graphicswall.com/\" target=\"_blank\">GraphicsWall</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_grey_floral_motif.zip" image: "http://subtlepatterns.com/patterns/light_grey_floral_motif.png" title: "Light Grey Floral Motif" categories: ["floral", "gray", "light"] image_dimensions: "32x56" , image_size: "3K" link: "http://subtlepatterns.com/3px-tile/" description: "Tiny dark square tiles with varied color tones." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/px_by_Gre3g.png" author: "<a href=\"http://gre3g.livejournal.com\" target=\"_blank\">G<NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/px_by_Gre3g.zip" image: "http://subtlepatterns.com/patterns/px_by_Gre3g.png" title: "3px tile" categories: ["dark", "square", "tile"] image_dimensions: "100x100" , image_size: "276K" link: "http://subtlepatterns.com/rice-paper-2/" description: "One can never have too few rice paper patterns, so here is one more." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ricepaper2.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ricepaper2.zip" image: "http://subtlepatterns.com/patterns/ricepaper2.png" title: "Rice paper 2" categories: ["light", "paper", "rice"] image_dimensions: "485x485" , image_size: "130K" link: "http://subtlepatterns.com/rice-paper/" description: "Scanned some rice paper and tiled it up for you. Enjoy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ricepaper.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ricepaper.zip" image: "http://subtlepatterns.com/patterns/ricepaper.png" title: "Rice paper" categories: ["light", "paper", "rice"] image_dimensions: "500x500" , image_size: "1K" link: "http://subtlepatterns.com/diagmonds/" description: "Love the style on this one, very fresh. Diagonal diamond pattern. Get it?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagmonds.png" author: "<a href=\"http://www.flickr.com/photos/ins\" target=\"_blank\">INS</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagmonds.zip" image: "http://subtlepatterns.com/patterns/diagmonds.png" title: "Diagmonds" categories: ["dark", "diamond"] image_dimensions: "141x142" , image_size: "46K" link: "http://subtlepatterns.com/polonez-pattern-2/" description: "Wtf, a car pattern?! Can it be subtle? I say yes!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/polonez_car.png" author: "<a href=\"http://designcocktails.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/polonez_car.zip" image: "http://subtlepatterns.com/patterns/polonez_car.png" title: "Polonez Pattern" categories: ["car", "light"] image_dimensions: "300x300" , image_size: "1K" link: "http://subtlepatterns.com/polonez-pattern/" description: "Repeating squares overlapping." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/plaid.png" author: "<a href=\"http://buttonpresser.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/plaid.zip" image: "http://subtlepatterns.com/patterns/plaid.png" title: "My Little Plaid" categories: ["geometry", "light"] image_dimensions: "54x54" , image_size: "430B" link: "http://subtlepatterns.com/axiom-pattern/" description: "Not even 1kb, but very stylish. Gray thin lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/struckaxiom.png" author: "<a href=\"http://www.struckaxiom.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/struckaxiom.zip" image: "http://subtlepatterns.com/patterns/struckaxiom.png" title: "Axiom Pattern" categories: ["diagonal", "light", "stripes"] image_dimensions: "81x81" , image_size: "149B" link: "http://subtlepatterns.com/zig-zag/" description: "So tiny, just 7 by 7 pixels – but still so sexy. Ah yes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/zigzag.png" author: "<a href=\"http://www.behance.net/dmpr0\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/zigzag.zip" image: "http://subtlepatterns.com/patterns/zigzag.png" title: "Zig Zag" categories: ["dark", "embossed"] image_dimensions: "10x10" , image_size: "1K" link: "http://subtlepatterns.com/carbon-fibre-big/" description: "Bigger is better, right? So here you have some large Carbon fibre." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/carbon_fibre_big.png" author: "<a href=\"http://factorio.us/\" target=\"_blank\">Factorio.us Collective</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/carbon_fibre_big.zip" image: "http://subtlepatterns.com/patterns/carbon_fibre_big.png" title: "Carbon Fibre Big" categories: ["dark"] image_dimensions: "20x22" , image_size: "1K" link: "http://subtlepatterns.com/batthern/" description: "Some times simple really is what you need, and this could fit you well." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/batthern.png" author: "<a href=\"http://factorio.us/\" target=\"_blank\">Factorio.us Collective</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/batthern.zip" image: "http://subtlepatterns.com/patterns/batthern.png" title: "Batthern" categories: ["light"] image_dimensions: "100x99" , image_size: "406B" link: "http://subtlepatterns.com/checkered-pattern/" description: "Simple gray checkered lines, in light tones." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/checkered_pattern.png" author: "<a href=\"http://designcocktails.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/checkered_pattern.zip" image: "http://subtlepatterns.com/patterns/checkered_pattern.png" title: "Checkered Pattern" categories: ["light", "lines"] image_dimensions: "72x72" , image_size: "131K" link: "http://subtlepatterns.com/dark-wood/" description: "A beautiful dark wood pattern, superbly tiled." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_wood.png" author: "<a href=\"http://www.oaadesigns.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_wood.zip" image: "http://subtlepatterns.com/patterns/dark_wood.png" title: "Dark wood" categories: ["dark"] image_dimensions: "512x512" , image_size: "741B" link: "http://subtlepatterns.com/soft-kill/" description: "Pattern #100! A black classic knit-looking pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/soft_kill.png" author: "<a href=\"http://www.factorio.us\" target=\"_blank\">Factorio.us Collective</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/soft_kill.zip" image: "http://subtlepatterns.com/patterns/soft_kill.png" title: "Soft kill" categories: ["dark"] image_dimensions: "28x48" , image_size: "401B" link: "http://subtlepatterns.com/elegant-grid/" description: "This is a hot one. Small, sharp and unique." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/elegant_grid.png" author: "<a href=\"http://www.graphicswall.com\" target=\"_blank\">GraphicsWall</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/elegant_grid.zip" image: "http://subtlepatterns.com/patterns/elegant_grid.png" title: "Elegant Grid" categories: ["light"] image_dimensions: "16x28" , image_size: "36K" link: "http://subtlepatterns.com/xv/" description: "Floral patterns will never go out of style, so enjoy this one." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/xv.png" author: "<a href=\"http://www.oddfur.com\" target=\"_blank\">Lasma</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/xv.zip" image: "http://subtlepatterns.com/patterns/xv.png" title: "Xv" categories: ["light"] image_dimensions: "294x235" , image_size: "66K" link: "http://subtlepatterns.com/rough-cloth/" description: "More tactile goodness. This time in the form of some rough cloth." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/roughcloth.png" author: "<a href=\"http://twitter.com/simek\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/roughcloth.zip" image: "http://subtlepatterns.com/patterns/roughcloth.png" title: "Rough Cloth" categories: ["light"] image_dimensions: "320x320" , image_size: "228B" link: "http://subtlepatterns.com/little-knobs/" description: "White little knobs, coming in at 10x10px. Sweet!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/littleknobs.png" author: "<a href=\"http://www.freepx.net\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/littleknobs.zip" image: "http://subtlepatterns.com/patterns/littleknobs.png" title: "Little knobs" categories: ["light"] image_dimensions: "10x10" , image_size: "5K" link: "http://subtlepatterns.com/dotnoise-light-grey/" description: "Sort of like the back of a wooden board. Light, subtle and stylish just the way we like it!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/bgnoise_lg.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bgnoise_lg.zip" image: "http://subtlepatterns.com/patterns/bgnoise_lg.png" title: "Dotnoise light grey" categories: ["light"] image_dimensions: "100x100" , image_size: "207B" link: "http://subtlepatterns.com/dark-circles/" description: "People seem to enjoy dark patterns, so here is one with some circles." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_circles.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_circles.zip" image: "http://subtlepatterns.com/patterns/dark_circles.png" title: "Dark circles" categories: ["dark"] image_dimensions: "10x12" , image_size: "42K" link: "http://subtlepatterns.com/light-aluminum/" description: "Used correctly, this could be nice. Used in a bad way, all Hell will break loose." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_alu.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_alu.zip" image: "http://subtlepatterns.com/patterns/light_alu.png" title: "Light aluminum" categories: ["light"] image_dimensions: "282x282" , image_size: "552B" link: "http://subtlepatterns.com/squares/" description: "Dark, square, clean and tidy. What more can you ask for?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/squares.png" author: "<a href=\"http://www.toshtak.com/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/squares.zip" image: "http://subtlepatterns.com/patterns/squares.png" title: "Squares" categories: ["dark"] image_dimensions: "32x32" , image_size: "129K" link: "http://subtlepatterns.com/felt/" description: "Got some felt in my mailbox today, so I scanned it for you to use." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/felt.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/felt.zip" image: "http://subtlepatterns.com/patterns/felt.png" title: "Felt" categories: ["light"] image_dimensions: "500x466" , image_size: "2K" link: "http://subtlepatterns.com/transparent-square-tiles/" description: "The first pattern on here using opacity. Try it on a site with a colored background, or even using mixed colors." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/square_bg.png" author: "<a href=\"http://nspady.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/square_bg.zip" image: "http://subtlepatterns.com/patterns/square_bg.png" title: "Transparent Square Tiles" categories: ["light"] image_dimensions: "252x230" , image_size: "418B" link: "http://subtlepatterns.com/paven/" description: "A subtle shadowed checkered pattern. Increase the lightness for even more subtle sexyness." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paven.png" author: "<a href=\"http://emailcoder.net\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paven.zip" image: "http://subtlepatterns.com/patterns/paven.png" title: "Paven" categories: ["light"] image_dimensions: "20x20" , image_size: "34K" link: "http://subtlepatterns.com/stucco/" description: "A nice and simple gray stucco material. Great on it’s own, or as a base for a new pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/stucco.png" author: "<a href=\"http://twitter.com/#!/simek\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stucco.zip" image: "http://subtlepatterns.com/patterns/stucco.png" title: "Stucco" categories: ["light"] image_dimensions: "250x249" , image_size: "21K" link: "http://subtlepatterns.com/r-i-p-steve-jobs/" description: "He influenced us all. “Don’t be sad because it’s over. Smile because it happened.” - Dr. Seuss" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rip_jobs.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rip_jobs.zip" image: "http://subtlepatterns.com/patterns/rip_jobs.png" title: "R.I.P Steve Jobs" categories: ["light"] image_dimensions: "200x200" , image_size: "1K" link: "http://subtlepatterns.com/woven/" description: "Can’t believe we don’t have this in the collection already! Slick woven pattern with crisp details." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/woven.png" author: "<a href=\"http://www.maxthemes.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/woven.zip" image: "http://subtlepatterns.com/patterns/woven.png" title: "Woven" categories: ["dark"] image_dimensions: "42x42" , image_size: "5K" link: "http://subtlepatterns.com/washi/" description: "Washi (和紙?) is a type of paper made in Japan. Here’s the pattern for you!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/washi.png" author: "<a href=\"http://www.sweetstudio.co.uk\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/washi.zip" image: "http://subtlepatterns.com/patterns/washi.png" title: "Washi" categories: ["light"] image_dimensions: "100x100" , image_size: "418B" link: "http://subtlepatterns.com/real-carbon-fibre/" description: "Carbon fibre is never out of fashion, so here is one more style for you." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/real_cf.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/real_cf.zip" image: "http://subtlepatterns.com/patterns/real_cf.png" title: "Real Carbon Fibre" categories: ["dark"] image_dimensions: "56x56" , image_size: "1K" link: "http://subtlepatterns.com/gold-scale/" description: "More Japanese-inspired patterns, Gold Scales this time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gold_scale.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gold_scale.zip" image: "http://subtlepatterns.com/patterns/gold_scale.png" title: "Gold Scale" categories: ["light"] image_dimensions: "25x25" , image_size: "1K" link: "http://subtlepatterns.com/elastoplast/" description: "A fun looking elastoplast/band-aid pattern. A hint of orange tone in this one." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/elastoplast.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/elastoplast.zip" image: "http://subtlepatterns.com/patterns/elastoplast.png" title: "Elastoplast" categories: ["light"] image_dimensions: "37x37" , image_size: "1K" link: "http://subtlepatterns.com/checkered-light-emboss/" description: "Sort of like the Photoshop transparent background, but better!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_checkered_tiles.png" author: "<a href=\"http://twitter.com/misterparker\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_checkered_tiles.zip" image: "http://subtlepatterns.com/patterns/light_checkered_tiles.png" title: "Checkered light emboss" categories: ["light"] image_dimensions: "60x60" , image_size: "200K" link: "http://subtlepatterns.com/cardboard/" description: "A good starting point for a cardboard pattern. This would work well in a variety of colors." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cardboard.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cardboard.zip" image: "http://subtlepatterns.com/patterns/cardboard.png" title: "Cardboard" categories: ["light"] image_dimensions: "600x600" , image_size: "15K" link: "http://subtlepatterns.com/type/" description: "The perfect pattern for all your blogs about type, or type related matters." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/type.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/type.zip" image: "http://subtlepatterns.com/patterns/type.png" title: "Type" categories: ["dark"] image_dimensions: "200x200" , image_size: "278B" link: "http://subtlepatterns.com/mbossed/" description: "Embossed lines and squares with subtle highlights." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/small_tiles.png" author: "<a href=\"http://twitter.com/misterparker\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/small_tiles.zip" image: "http://subtlepatterns.com/patterns/small_tiles.png" title: "MBossed" categories: ["light"] image_dimensions: "26x26" , image_size: "279B" link: "http://subtlepatterns.com/black-scales/" description: "Same as Silver Scales, but in black – turn your site in to a dragon with this great scale pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_scales.png" author: "<a href=\"http://twitter.com/misterparker\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_scales.zip" image: "http://subtlepatterns.com/patterns/black_scales.png" title: "Black Scales" categories: ["dark"] image_dimensions: "40x40" , image_size: "289B" link: "http://subtlepatterns.com/silver-scales/" description: "Turn your site in to a dragon with this great scale pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/silver_scales.png" author: "<a href=\"http://twitter.com/misterparker\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/silver_scales.zip" image: "http://subtlepatterns.com/patterns/silver_scales.png" title: "Silver Scales" categories: ["light"] image_dimensions: "40x40" , image_size: "5K" link: "http://subtlepatterns.com/polaroid/" description: "Smooth Polaroid pattern with a light blue tint." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/polaroid.png" author: "<a href=\"http://danielbeaton.tumblr.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/polaroid.zip" image: "http://subtlepatterns.com/patterns/polaroid.png" title: "Polaroid" categories: ["light"] image_dimensions: "58x36" , image_size: "247B" link: "http://subtlepatterns.com/circles/" description: "One more sharp little tile for you. Subtle circles this time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/circles.png" author: "<a href=\"http://www.blunia.com/\" target=\"_blank\">Blunia</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/circles.zip" image: "http://subtlepatterns.com/patterns/circles.png" title: "Circles" categories: ["light"] image_dimensions: "16x12" , image_size: "2K" link: "http://subtlepatterns.com/diamonds-are-forever/" description: "Sharp diamond pattern. A small 24x18px tile." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diamonds.png" author: "<a href=\"http://imaketees.co.uk\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diamonds.zip" image: "http://subtlepatterns.com/patterns/diamonds.png" title: "Diamonds Are Forever" categories: ["light"] image_dimensions: "24x18" , image_size: "8K" link: "http://subtlepatterns.com/diagonal-noise/" description: "A simple but elegant classic. Every collection needs one of these." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagonal-noise.png" author: "<a href=\"http://ChristopherBurton.net\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonal-noise.zip" image: "http://subtlepatterns.com/patterns/diagonal-noise.png" title: "Diagonal Noise" categories: ["light"] image_dimensions: "100x100" , image_size: "30K" link: "http://subtlepatterns.com/noise-pattern-with-subtle-cross-lines/" description: "More bright luxury. This is a bit larger than fancy deboss, and with a bit more noise." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noise_pattern_with_crosslines.png" author: "<a href=\"http://visztpeter.me\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noise_pattern_with_crosslines.zip" image: "http://subtlepatterns.com/patterns/noise_pattern_with_crosslines.png" title: "Noise pattern with subtle cross lines" categories: [] image_dimensions: "240x240" , image_size: "265B" link: "http://subtlepatterns.com/fancy-deboss/" description: "Luxury pattern, looking like it came right out of Paris." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fancy_deboss.png" author: "<a href=\"http://danielbeaton.tumblr.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fancy_deboss.zip" image: "http://subtlepatterns.com/patterns/fancy_deboss.png" title: "Fancy Deboss" categories: ["light"] image_dimensions: "18x13" , image_size: "40K" link: "http://subtlepatterns.com/pool-table/" description: "This makes me wanna shoot some pool! Sweet green pool table pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pool_table.png" author: "<a href=\"http://caveman.chlova.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pool_table.zip" image: "http://subtlepatterns.com/patterns/pool_table.png" title: "Pool Table" categories: ["color", "dark"] image_dimensions: "256x256" , image_size: "5K" link: "http://subtlepatterns.com/dark-brick-wall/" description: "Black brick wall pattern. Brick your site up!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_brick_wall.png" author: "<a href=\"http://alexparker.me\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_brick_wall.zip" image: "http://subtlepatterns.com/patterns/dark_brick_wall.png" title: "Dark Brick Wall" categories: ["dark"] image_dimensions: "96x96" , image_size: "723B" link: "http://subtlepatterns.com/cubes/" description: "This reminds me of Game Cube. A nice light 3D cube pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cubes.png" author: "<a href=\"http://www.experimint.nl\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cubes.zip" image: "http://subtlepatterns.com/patterns/cubes.png" title: "Cubes" categories: ["light"] image_dimensions: "67x100" , image_size: "5K" link: "http://subtlepatterns.com/white-texture/" description: "Not the most creative name, but it’s a good all-purpose light background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_texture.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_texture.zip" image: "http://subtlepatterns.com/patterns/white_texture.png" title: "White Texture" categories: ["light"] image_dimensions: "102x102" , image_size: "72K" link: "http://subtlepatterns.com/black-leather/" description: "You were craving for more leather, so I whipped this up by scanning a leather jacket." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_leather.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_leather.zip" image: "http://subtlepatterns.com/patterns/dark_leather.png" title: "Dark leather" categories: ["dark"] image_dimensions: "398x484" , image_size: "5K" link: "http://subtlepatterns.com/robots/" description: "And some more testing, this time with Seamless Studio . It’s Robots FFS!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/robots.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/robots.zip" image: "http://subtlepatterns.com/patterns/robots.png" title: "Robots" categories: ["dark"] image_dimensions: "200x200" , image_size: "5K" link: "http://subtlepatterns.com/mirrored-squares/" description: "Did some testing with Repper Pro tonight, and this gray mid-tone pattern came out." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/mirrored_squares.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/mirrored_squares.zip" image: "http://subtlepatterns.com/patterns/mirrored_squares.png" title: "Mirrored Squares" categories: ["dark"] image_dimensions: "166x166" , image_size: "10K" link: "http://subtlepatterns.com/dark-mosaic/" description: "Small dots with minor circles spread across to form a nice mosaic." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_mosaic.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_mosaic.zip" image: "http://subtlepatterns.com/patterns/dark_mosaic.png" title: "Dark Mosaic" categories: ["dark"] image_dimensions: "300x295" , image_size: "224B" link: "http://subtlepatterns.com/project-papper/" description: "Light square grid pattern, great for a “DIY projects” sort of website, maybe?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/project_papper.png" author: "<a href=\"http://www.fotografiaetc.com.br/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/project_papper.zip" image: "http://subtlepatterns.com/patterns/project_papper.png" title: "Project Papper" categories: ["light"] image_dimensions: "105x105" , image_size: "31K" link: "http://subtlepatterns.com/inflicted/" description: "Dark squares with some virus-looking dots in the grid." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/inflicted.png" author: "<a href=\"http://www.inflicted.nl\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/inflicted.zip" image: "http://subtlepatterns.com/patterns/inflicted.png" title: "Inflicted" categories: ["dark"] image_dimensions: "240x240" , image_size: "116B" link: "http://subtlepatterns.com/small-crosses/" description: "Sharp pixel pattern looking like some sort of fabric." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/crosses.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/crosses.zip" image: "http://subtlepatterns.com/patterns/crosses.png" title: "Small Crosses" categories: ["light"] image_dimensions: "10x10" , image_size: "9K" link: "http://subtlepatterns.com/soft-circle-scales/" description: "Japanese looking fish scale pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/soft_circle_scales.png" author: "<a href=\"http://iansoper.com\" title=\"<NAME>\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/soft_circle_scales.zip" image: "http://subtlepatterns.com/patterns/soft_circle_scales.png" title: "Soft Circle Scales" categories: ["light"] image_dimensions: "256x56" , image_size: "60K" link: "http://subtlepatterns.com/crissxcross/" description: "Dark pattern with some nice diagonal stitched lines crossing over." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/crissXcross.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/crissXcross.zip" image: "http://subtlepatterns.com/patterns/crissXcross.png" title: "crissXcross" categories: ["dark"] image_dimensions: "512x512" , image_size: "85K" link: "http://subtlepatterns.com/whitey/" description: "A white version of the very popular linen pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/whitey.png" author: "<a href=\"http://www.turkhitbox.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/whitey.zip" image: "http://subtlepatterns.com/patterns/whitey.png" title: "Whitey" categories: ["light"] image_dimensions: "654x654" , image_size: "42K" link: "http://subtlepatterns.com/green-dust-scratches/" description: "Snap! It’s a pattern, and it’s not grayscale! Of course you can always change the color in Photoshop." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/green_dust_scratch.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/green_dust_scratch.zip" image: "http://subtlepatterns.com/patterns/green_dust_scratch.png" title: "Green Dust & Scratches" categories: ["light"] image_dimensions: "296x300" , image_size: "635B" link: "http://subtlepatterns.com/carbon-fibre-v2/" description: "One more updated pattern. Not really carbon fibre, but it’s the most popular pattern, so I’ll give you an extra choice." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/carbon_fibre_v2.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/carbon_fibre_v2.zip" image: "http://subtlepatterns.com/patterns/carbon_fibre_v2.png" title: "Carbon fibre v2" categories: ["dark"] image_dimensions: "32x36" , image_size: "137K" link: "http://subtlepatterns.com/black-linen-2/" description: "A new take on the black linen pattern. Softer this time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_linen_v2.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_linen_v2.zip" image: "http://subtlepatterns.com/patterns/black_linen_v2.png" title: "Black linen 2" categories: ["dark"] image_dimensions: "640x640" , image_size: "1004B" link: "http://subtlepatterns.com/darth-stripe/" description: "A very slick dark rubber grip pattern, sort of like the grip on a camera." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rubber_grip.png" author: "<a href=\"http://be.net/pixilated\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rubber_grip.zip" image: "http://subtlepatterns.com/patterns/rubber_grip.png" title: "Rubber grip" categories: ["dark"] image_dimensions: "5x20" , image_size: "218K" link: "http://subtlepatterns.com/darth-stripe-2/" description: "Diagonal lines with a lot of texture to them." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/darth_stripe.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/darth_stripe.zip" image: "http://subtlepatterns.com/patterns/darth_stripe.png" title: "Darth Stripe" categories: ["dark"] image_dimensions: "511x511" , image_size: "71K" link: "http://subtlepatterns.com/subtle-orange-emboss/" description: "A hint or orange color, and some crossed & embossed lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_orange_emboss.png" author: "<a href=\"http://www.depcore.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_orange_emboss.zip" image: "http://subtlepatterns.com/patterns/subtle_orange_emboss.png" title: "Subtle orange emboss" categories: ["light"] image_dimensions: "497x249" , image_size: "225K" link: "http://subtlepatterns.com/soft-wallpaper/" description: "Coming in at 666x666px, this is an evil big pattern, but nice and soft at the same time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/soft_wallpaper.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/soft_wallpaper.zip" image: "http://subtlepatterns.com/patterns/soft_wallpaper.png" title: "Soft Wallpaper" categories: ["light"] image_dimensions: "666x666" , image_size: "60K" link: "http://subtlepatterns.com/concrete-wall-3/" description: "All good things are 3, so I give you the third in my little concrete wall series." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/concrete_wall_3.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/concrete_wall_3.zip" image: "http://subtlepatterns.com/patterns/concrete_wall_3.png" title: "Concrete wall 3" categories: ["light"] image_dimensions: "400x299" , image_size: "38K" link: "http://subtlepatterns.com/green-fibers/" description: "The Green fibers pattern will work very well in grayscale as well." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/green-fibers.png" author: "<a href=\"http://www.matteodicapua.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/green-fibers.zip" image: "http://subtlepatterns.com/patterns/green-fibers.png" title: "Green Fibers" categories: ["dark"] image_dimensions: "200x200" , image_size: "14K" link: "http://subtlepatterns.com/subtle-freckles/" description: "This shit is so subtle we’re talking 1% opacity. Get your squint on!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_freckles.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_freckles.zip" image: "http://subtlepatterns.com/patterns/subtle_freckles.png" title: "Subtle freckles" categories: ["light"] image_dimensions: "198x198" , image_size: "40K" link: "http://subtlepatterns.com/bright-squares/" description: "It’s Okay to be square! A nice light gray pattern with random squares." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/bright_squares.png" author: "<a href=\"http://twitter.com/dwaseem\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bright_squares.zip" image: "http://subtlepatterns.com/patterns/bright_squares.png" title: "Bright Squares" categories: ["light"] image_dimensions: "297x297" , image_size: "1K" link: "http://subtlepatterns.com/green-gobbler/" description: "Luxurious looking pattern (for a t-shirt maybe?) with a hint of green." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/green_gobbler.png" author: "<a href=\"http://www.simonmeek.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/green_gobbler.zip" image: "http://subtlepatterns.com/patterns/green_gobbler.png" title: "Green gobbler" categories: ["light"] image_dimensions: "39x39" , image_size: "23K" link: "http://subtlepatterns.com/beige-paper/" description: "This was submitted in a beige color, hence the name. Now it’s a gray paper pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/beige_paper.png" author: "<a href=\"http://twitter.com/phenix_h_k\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/beige_paper.zip" image: "http://subtlepatterns.com/patterns/beige_paper.png" title: "Beige paper" categories: ["light"] image_dimensions: "200x200" , image_size: "106K" link: "http://subtlepatterns.com/grunge-wall/" description: "Light gray grunge wall with a nice texture overlay." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grunge_wall.png" author: "<a href=\"http://www.depcore.pl\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grunge_wall.zip" image: "http://subtlepatterns.com/patterns/grunge_wall.png" title: "Grunge wall" categories: ["light"] image_dimensions: "500x375" , image_size: "272K" link: "http://subtlepatterns.com/concrete-wall-2/" description: "A light gray wall or floor (you decide) of concrete." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/concrete_wall_2.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/concrete_wall_2.zip" image: "http://subtlepatterns.com/patterns/concrete_wall_2.png" title: "Concrete wall 2" categories: ["concrete", "light"] image_dimensions: "597x545" , image_size: "173K" link: "http://subtlepatterns.com/concrete-wall/" description: "Dark blue concrete wall with some small dust spots." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/concrete_wall.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/concrete_wall.zip" image: "http://subtlepatterns.com/patterns/concrete_wall.png" title: "Concrete wall" categories: ["dark"] image_dimensions: "520x520" , image_size: "1K" link: "http://subtlepatterns.com/wavecut/" description: "If you like it a bit trippy, this wave pattern might be for you." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wavecut.png" author: "<a href=\"http://iansoper.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wavecut.zip" image: "http://subtlepatterns.com/patterns/wavecut.png" title: "WaveCut" categories: ["light"] image_dimensions: "162x15" , image_size: "131K" link: "http://subtlepatterns.com/little-pluses/" description: "Subtle grunge and many little pluses on top." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/little_pluses.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/little_pluses.zip" image: "http://subtlepatterns.com/patterns/little_pluses.png" title: "Little pluses" categories: ["light"] image_dimensions: "300x300" , image_size: "2K" link: "http://subtlepatterns.com/vichy/" description: "This one could be the shirt of a golf player. Angled lines in different thicknesses." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/vichy.png" author: "<a href=\"http://www.olivierpineda.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/vichy.zip" image: "http://subtlepatterns.com/patterns/vichy.png" title: "Vichy" categories: ["light"] image_dimensions: "70x70" , image_size: "8K" link: "http://subtlepatterns.com/random-grey-variations/" description: "Stefan is hard at work, this time with a funky pattern of squares." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/random_grey_variations.png" author: "<a href=\"http://www.MentalWardDesign.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/random_grey_variations.zip" image: "http://subtlepatterns.com/patterns/random_grey_variations.png" title: "Random Grey Variations" categories: ["dark"] image_dimensions: "200x200" , image_size: "10K" link: "http://subtlepatterns.com/brushed-alum/" description: "A light brushed aluminum pattern for your pleasure." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/brushed_alu.png" author: "<a href=\"http://www.MentalWardDesign.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/brushed_alu.zip" image: "http://subtlepatterns.com/patterns/brushed_alu.png" title: "Brushed Alum" categories: ["aluminum", "light"] image_dimensions: "400x400" , image_size: "89K" link: "http://subtlepatterns.com/brushed-alum-dark/" description: "Because I love dark patterns, here is Brushed Alum in a dark coating." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/brushed_alu_dark.png" author: "<a href=\"http://www.MentalWardDesign.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/brushed_alu_dark.zip" image: "http://subtlepatterns.com/patterns/brushed_alu_dark.png" title: "Brushed Alum Dark" categories: ["dark", "square"] image_dimensions: "400x400" , image_size: "82K" link: "http://subtlepatterns.com/black-linen/" description: "In the spirit of WWDC 2011, here is a dark iOS inspired linen pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black-Linen.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black-Linen.zip" image: "http://subtlepatterns.com/patterns/black-Linen.png" title: "Black Linen" categories: ["dark"] image_dimensions: "482x490" , image_size: "16K" link: "http://subtlepatterns.com/padded/" description: "A beautiful dark padded pattern, like an old classic sofa." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/padded.png" author: "<a href=\"http://papertank.co.uk\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/padded.zip" image: "http://subtlepatterns.com/patterns/padded.png" title: "Padded" categories: ["dark"] image_dimensions: "160x160" , image_size: "26K" link: "http://subtlepatterns.com/light-honeycomb/" description: "Light honeycomb pattern made up of the classic hexagon shape." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_honeycomb.png" author: "<a href=\"http://about.me/federicca\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_honeycomb.zip" image: "http://subtlepatterns.com/patterns/light_honeycomb.png" title: "Light Honeycomb" categories: ["light"] image_dimensions: "270x289" , image_size: "93K" link: "http://subtlepatterns.com/black-mamba/" description: "The name alone is awesome, but so is this sweet dark pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/blackmamba.png" author: "<a href=\"http://about.me/federicca\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blackmamba.zip" image: "http://subtlepatterns.com/patterns/blackmamba.png" title: "Black Mamba" categories: ["dark"] image_dimensions: "500x500" , image_size: "79K" link: "http://subtlepatterns.com/black-paper/" description: "Black paper texture, based on two different images." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_paper.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a> based on textures from <a href=\"http://www.designkindle.com/2011/03/03/vintage-paper-textures-vol-1/\" target=\"_blank\">Design Kindle</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_paper.zip" image: "http://subtlepatterns.com/patterns/black_paper.png" title: "Black paper" categories: ["dark"] image_dimensions: "400x400" , image_size: "353B" link: "http://subtlepatterns.com/always-grey/" description: "Crossing lines with a subtle emboss effect on a dark background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/always_grey.png" author: "<a href=\"http://www.facebook.com/stefanaleksic88\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/always_grey.zip" image: "http://subtlepatterns.com/patterns/always_grey.png" title: "Always Grey" categories: ["dark"] image_dimensions: "35x35" , image_size: "7K" link: "http://subtlepatterns.com/double-lined/" description: "Horizontal and vertical lines on a light gray background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/double_lined.png" author: "<a href=\"http://www.depcore.pl\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/double_lined.zip" image: "http://subtlepatterns.com/patterns/double_lined.png" title: "Double lined" categories: ["light"] image_dimensions: "150x64" , image_size: "614K" link: "http://subtlepatterns.com/wood/" description: "Dark wooden pattern, given the subtle treatment." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wood_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a> based on texture from <a href=\"http://cloaks.deviantart.com/\" target=\"_blank\">Cloaks</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wood_1.zip" image: "http://subtlepatterns.com/patterns/wood_1.png" title: "Wood" categories: ["dark"] image_dimensions: "700x700" , image_size: "1015B" link: "http://subtlepatterns.com/cross-stripes/" description: "Nice and simple crossed lines in dark gray tones." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/crossed_stripes.png" author: "<a href=\"http://www.facebook.com/stefanaleksic88\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/crossed_stripes.zip" image: "http://subtlepatterns.com/patterns/crossed_stripes.png" title: "Cross Stripes" categories: ["dark"] image_dimensions: "6x6" , image_size: "20K" link: "http://subtlepatterns.com/noisy/" description: "Looks a bit like concrete with subtle specs spread around the pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noisy.png" author: "<a href=\"http://anticdesign.info\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy.zip" image: "http://subtlepatterns.com/patterns/noisy.png" title: "Noisy" categories: ["light", "noise"] image_dimensions: "300x300" , image_size: "47K" link: "http://subtlepatterns.com/old-mathematics/" description: "This one takes you back to math class. Classic mathematic board underlay." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/old_mathematics.png" author: "<a href=\"http://emailcoder.net/\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/old_mathematics.zip" image: "http://subtlepatterns.com/patterns/old_mathematics.png" title: "Old Mathematics" categories: ["blue", "grid", "light", "mathematic"] image_dimensions: "200x200" , image_size: "100K" link: "http://subtlepatterns.com/rocky-wall/" description: "High detail stone wall with minor cracks and specks." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rockywall.png" author: "<a href=\"http://projecteightyfive.com/\" target=\"_blank\">Projecteightyfive</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rockywall.zip" image: "http://subtlepatterns.com/patterns/rockywall.png" title: "Rocky wall" categories: ["light", "rock", "wall"] image_dimensions: "500x500" , image_size: "1K" link: "http://subtlepatterns.com/dark-stripes/" description: "Very dark pattern with some noise and 45 degree lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_stripes.png" author: "<a href=\"http://www.facebook.com/stefanaleksic88\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_stripes.zip" image: "http://subtlepatterns.com/patterns/dark_stripes.png" title: "Dark stripes" categories: ["dark", "stripes"] image_dimensions: "50x50" , image_size: "6K" link: "http://subtlepatterns.com/handmade-paper/" description: "White hand made paper pattern with small bumps." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/handmadepaper.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/handmadepaper.zip" image: "http://subtlepatterns.com/patterns/handmadepaper.png" title: "Handmade paper" categories: ["light", "paper"] image_dimensions: "100x100" , image_size: "537B" link: "http://subtlepatterns.com/pinstripe/" description: "Light gray pattern with a thin pinstripe." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pinstripe.png" author: "<a href=\"http://extrast.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pinstripe.zip" image: "http://subtlepatterns.com/patterns/pinstripe.png" title: "Pinstripe" categories: ["gray", "light", "pinstripe"] image_dimensions: "50x500" , image_size: "45K" link: "http://subtlepatterns.com/wine-cork/" description: "Wine cork texture based off a scanned corkboard." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cork_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cork_1.zip" image: "http://subtlepatterns.com/patterns/cork_1.png" title: "Wine Cork" categories: ["cork", "light"] image_dimensions: "300x300" , image_size: "85K" link: "http://subtlepatterns.com/bedge-grunge/" description: "A large (588x375px) sand colored pattern for your ever growing collection. Shrink at will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/bedge_grunge.png" author: "<a href=\"http://www.tapein.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bedge_grunge.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bedge_grunge.png" title: "Bedge grunge" categories: ["light"] image_dimensions: "588x375" , image_size: "24K" link: "http://subtlepatterns.com/noisy-net/" description: "Little x’es, noise and all the stuff you like. Dark like a Monday, with a hint of blue." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noisy_net.png" author: "<a href=\"http://twitter.com/_mcrdl\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy_net.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy_net.png" title: "Noisy Net" categories: ["dark", "noise"] image_dimensions: "200x200" , image_size: "53K" link: "http://subtlepatterns.com/grid/" description: "There are quite a few grid patterns, but this one is a super tiny grid with some dust for good measure." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grid.png" author: "<a href=\"http://www.werk.sk\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grid.png" title: "Grid" categories: ["grid", "light"] image_dimensions: "310x310" , image_size: "202B" link: "http://subtlepatterns.com/straws/" description: "Super detailed 16×16 tile that forms a beautiful pattern of straws." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/straws.png" author: "<a href=\"http://evaluto.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/straws.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/straws.png" title: "Straws" categories: ["light"] image_dimensions: "16x16" , image_size: "32K" link: "http://subtlepatterns.com/cardboard-flat/" description: "Not a flat you live inside, like in the UK – but a flat piece of cardboard." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cardboard_flat.png" author: "Appleshadow" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cardboard_flat.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cardboard_flat.png" title: "Cardboard Flat" categories: ["light"] image_dimensions: "256x256" , image_size: "32K" link: "http://subtlepatterns.com/noisy-grid/" description: "This is a grid, only it’s noisy. You know. Reminds you of those printed grids you draw on." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noisy_grid.png" author: "<a href=\"http://www.vectorpile.com\" target=\"_blank\">Vectorpile.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy_grid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy_grid.png" title: "Noisy Grid" categories: ["grid", "light"] image_dimensions: "150x150" , image_size: "2K" link: "http://subtlepatterns.com/office/" description: "I guess this one is inspired by an office. A dark office." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/office.png" author: "<a href=\"http://www.andresrigo.com\" target=\"_blank\"><NAME>.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/office.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/office.png" title: "Office" categories: ["dark"] image_dimensions: "70x70" , image_size: "44K" link: "http://subtlepatterns.com/subtle-grey/" description: "The Grid. A digital frontier. I tried to picture clusters of information as they traveled through the computer." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grey.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grey.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grey.png" title: "Subtle Grey" categories: ["light"] image_dimensions: "397x322" , image_size: "218B" link: "http://subtlepatterns.com/hexabump/" description: "Hexagonal dark 3D pattern, what more can you ask for?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/hexabump.png" author: "<a href=\"http://spom.me\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/hexabump.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/hexabump.png" title: "Hexabump" categories: ["dark"] image_dimensions: "19x33" , image_size: "134K" link: "http://subtlepatterns.com/shattered/" description: "A large pattern with funky shapes and form. An original. Sort of origami-ish." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/shattered.png" author: "<a href=\"http://luukvanbaars.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shattered.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shattered.png" title: "Shattered" categories: ["light", "origami"] image_dimensions: "500x500" , image_size: "32K" link: "http://subtlepatterns.com/paper-3/" description: "Light gray paper pattern with small traces of fibre and some dust." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper_3.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_3.zip" image: "http://subtlepatterns.com/patterns/paper_3.png" title: "Paper 3" categories: ["light", "paper"] image_dimensions: "276x276" , image_size: "9K" link: "http://subtlepatterns.com/dark-denim/" description: "A dark denim looking pattern. 145×145 pixels." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_denim.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_denim.zip" image: "http://subtlepatterns.com/patterns/black_denim.png" title: "Dark denim" categories: ["dark"] image_dimensions: "145x145" , image_size: "74K" link: "http://subtlepatterns.com/smooth-wall/" description: "Some rectangles, a bit of dust and grunge, plus a hint of concrete." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/smooth_wall.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/smooth_wall.zip" image: "http://subtlepatterns.com/patterns/smooth_wall.png" title: "Smooth Wall" categories: ["light"] image_dimensions: "358x358" , image_size: "622B" link: "http://subtlepatterns.com/131/" description: "Never out of fashion and so much hotter than the 45º everyone knows, here is a sweet 60º line pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/60degree_gray.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/60degree_gray.zip" image: "http://subtlepatterns.com/patterns/60degree_gray.png" title: "60º lines" categories: ["light"] image_dimensions: "31x31" , image_size: "141K" link: "http://subtlepatterns.com/exclusive-paper/" description: "Exclusive looking paper pattern with small dust particles and 45 degree strokes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/exclusive_paper.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/exclusive_paper.zip" image: "http://subtlepatterns.com/patterns/exclusive_paper.png" title: "Exclusive paper" categories: ["light"] image_dimensions: "560x420" , image_size: "43K" link: "http://subtlepatterns.com/paper-2/" description: "New paper pattern with a slightly organic feel to it, using some thin threads." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper_2.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_2.zip" image: "http://subtlepatterns.com/patterns/paper_2.png" title: "Paper 2" categories: ["light"] image_dimensions: "280x280" , image_size: "17K" link: "http://subtlepatterns.com/white-sand/" description: "Same as gray sand but lighter. A sandy pattern with small light dots, and some angled strokes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_sand.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_sand.zip" image: "http://subtlepatterns.com/patterns/white_sand.png" title: "White sand" categories: ["light"] image_dimensions: "211x211" , image_size: "16K" link: "http://subtlepatterns.com/gray-sand/" description: "A dark gray, sandy pattern with small light dots, and some angled strokes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gray_sand.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gray_sand.zip" image: "http://subtlepatterns.com/patterns/gray_sand.png" title: "Gray sand" categories: ["dark"] image_dimensions: "211x211" , image_size: "82K" link: "http://subtlepatterns.com/paper-1/" description: "A slightly grainy paper pattern with small horisontal and vertical strokes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_1.zip" image: "http://subtlepatterns.com/patterns/paper_1.png" title: "Paper 1" categories: ["light"] image_dimensions: "400x400" , image_size: "75K" link: "http://subtlepatterns.com/leather-1/" description: "A leather pattern with a hint of yellow." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/leather_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/leather_1.zip" image: "http://subtlepatterns.com/patterns/leather_1.png" title: "Leather 1" categories: ["light"] image_dimensions: "300x300" , image_size: "133B" link: "http://subtlepatterns.com/white-carbon/" description: "Same as the black version, but now in shades of gray. Very subtle and fine grained." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_carbon.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_carbon.zip" image: "http://subtlepatterns.com/patterns/white_carbon.png" title: "White carbon" categories: ["light"] image_dimensions: "8x8" , image_size: "99K" link: "http://subtlepatterns.com/fabric-1/" description: "Semi light fabric pattern made out of random pixles in shades of gray." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fabric_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fabric_1.zip" image: "http://subtlepatterns.com/patterns/fabric_1.png" title: "Fabric 1" categories: ["light"] image_dimensions: "400x400" , image_size: "117B" link: "http://subtlepatterns.com/micro-carbon/" description: "Three shades of gray makes this pattern look like a small carbon fibre surface. Great readability even for small fonts." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/micro_carbon.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/micro_carbon.zip" image: "http://subtlepatterns.com/patterns/micro_carbon.png" title: "Micro carbon" categories: ["dark"] image_dimensions: "4x4" , image_size: "1K" link: "http://subtlepatterns.com/tactile-noise/" description: "A heavy dark gray base, some subtle noise and a 45 degree grid makes this look like a pattern with a tactile feel to it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tactile_noise.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tactile_noise.zip" image: "http://subtlepatterns.com/patterns/tactile_noise.png" title: "Tactile noise" categories: ["dark"] image_dimensions: "48x48" , image_size: "142B" link: "http://subtlepatterns.com/carbon-fibre-2/" description: "A dark pattern made out of 3×3 circles and a 1px shadow. This works well as a carbon texture or background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/carbon_fibre.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/carbon_fibre.zip" image: "http://subtlepatterns.com/patterns/carbon_fibre.png" title: "Carbon fibre" categories: ["dark"] image_dimensions: "24x22" , image_size: "78K" link: "http://subtlepatterns.com/awesome-pattern/" description: "Medium gray fabric pattern with 45 degree lines going across." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/45degreee_fabric.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/45degreee_fabric.zip" image: "http://subtlepatterns.com/patterns/45degreee_fabric.png" title: "45 degree fabric" categories: ["light"] image_dimensions: "315x315" , image_size: "138B" link: "http://subtlepatterns.com/subtle-carbon/" description: "There are many carbon patterns, but this one is tiny." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_carbon.png" author: "<a href=\"http://www.designova.net\" target=\"_blank\">Designova</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_carbon.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_carbon.png" title: "Subtle Carbon" categories: ["carbon", "dark"] image_dimensions: "18x15" , image_size: "4K" link: "http://subtlepatterns.com/swirl/" description: "The name tells you it has curves. Oh yes it does!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/swirl.png" author: "<a href=\"http://peterchondesign.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/swirl.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/swirl.png" title: "Swirl" categories: ["light", "swirl"] image_dimensions: "200x200" , image_size: "424B" link: "http://subtlepatterns.com/back-pattern/" description: "Pixel by pixel, sharp and clean. Very light pattern with clear lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/back_pattern.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/back_pattern.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/back_pattern.png" title: "Back pattern" categories: ["light"] image_dimensions: "28x28" , image_size: "470B" link: "http://subtlepatterns.com/translucent-fibres/" description: "The file was named striped lens, but hey – Translucent Fibres works too." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/striped_lens.png" author: "<a href=\"http://fleeting_days.livejournal.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/striped_lens.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/striped_lens.png" title: "Translucent Fibres" categories: ["light"] image_dimensions: "16x16" , image_size: "141B" link: "http://subtlepatterns.com/skeletal-weave/" description: "Imagine you zoomed in 1000X on some fabric. But then it turned out to be a skeleton!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/skelatal_weave.png" author: "<a href=\"http://fleeting_days.livejournal.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/skelatal_weave.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/skelatal_weave.png" title: "Skeletal Weave" categories: ["light"] image_dimensions: "25x25" , image_size: "191B" link: "http://subtlepatterns.com/black-twill/" description: "Trippy little gradients at an angle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_twill.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_twill.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_twill.png" title: "Black Twill" categories: ["dark"] image_dimensions: "14x14" , image_size: "150K" link: "http://subtlepatterns.com/asfalt/" description: "A very dark asfalt pattern based off of a photo taken with my iPhone. If you want to tweak it, I put the PSD here (a hint lighter, maybe?)." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/asfalt.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/asfalt.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/asfalt.png" title: "Asfalt" categories: ["asfalt", "dark"] image_dimensions: "466x349" , image_size: "199B" link: "http://subtlepatterns.com/subtle-surface/" description: "Super subtle indeed, a medium gray pattern with tiny dots in a grid." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_surface.png" author: "<a href=\"http://www.designova.net\" target=\"_blank\">Designova</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_surface.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_surface.png" title: "Subtle Surface" categories: ["gray", "light"] image_dimensions: "16x8" , image_size: "99K" link: "http://subtlepatterns.com/retina-wood/" description: "I’m not going to use the word Retina for all the new patterns, but it just felt right for this one. Huge wood pattern for ya’ll." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/retina_wood.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retina_wood.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retina_wood.png" title: "Retina Wood" categories: ["light", "retina", "wood"] image_dimensions: "512x512" , image_size: "1K" link: "http://subtlepatterns.com/subtle-dots/" description: "As simple and subtle as it get’s, but sometimes that’s just what you want." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_dots.png" author: "<a href=\"http://www.designova.net\" target=\"_blank\">Design<NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_dots.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_dots.png" title: "Subtle Dots" categories: ["dots", "light"] image_dimensions: "27x15" , image_size: "89K" link: "http://subtlepatterns.com/dust/" description: "Another one bites the dust! Boyah." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dust.png" author: "<a href=\"http://www.werk.sk\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dust.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dust.png" title: "Dust" categories: ["light"] image_dimensions: "400x300" , image_size: "1K" link: "http://subtlepatterns.com/use-your-illusion/" description: "A dark one with geometric shapes and dotted lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/use_your_illusion.png" author: "<a href=\"http://www.mohawkstudios.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/use_your_illusion.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/use_your_illusion.png" title: "Use Your Illusion" categories: ["dark"] image_dimensions: "54x58" , image_size: "17K" link: "http://subtlepatterns.com/retina-dust/" description: "First pattern tailor made for Retina, with many more to come. All the old ones are upscaled, in case you want to re-download." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/retina_dust.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retina_dust.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retina_dust.png" title: "Retina dust" categories: ["light", "retina"] image_dimensions: "200x200" , image_size: "8K" link: "http://subtlepatterns.com/gray-lines/" description: "Some more diagonal lines and noise, because you know you want it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_noise_diagonal.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_noise_diagonal.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_noise_diagonal.png" title: "Gray lines" categories: ["diagonal", "light", "noise"] image_dimensions: "150x150" , image_size: "2K" link: "http://subtlepatterns.com/noise-lines/" description: "Lovely pattern with some good looking non-random-noise-lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noise_lines.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noise_lines.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noise_lines.png" title: "Noise lines" categories: ["diagonal", "light", "noise"] image_dimensions: "60x59" , image_size: "139B" link: "http://subtlepatterns.com/pyramid/" description: "Could remind you a bit of those squares in Super Mario Bros, yeh?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pyramid.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pyramid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pyramid.png" title: "Pyramid" categories: ["light"] image_dimensions: "16x16" , image_size: "4K" link: "http://subtlepatterns.com/retro-intro/" description: "A slightly more textured pattern, medium gray. A bit like a potato sack?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/retro_intro.png" author: "<a href=\"http://www.twitter.com/Creartinc\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retro_intro.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retro_intro.png" title: "Retro Intro" categories: ["light", "textured"] image_dimensions: "109x109" , image_size: "240B" link: "http://subtlepatterns.com/tiny-grid/" description: "You know, tiny and sharp. I’m sure you’ll find a use for it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tiny_grid.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tiny_grid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tiny_grid.png" title: "Tiny Grid" categories: ["grid", "light"] image_dimensions: "26x26" , image_size: "33K" link: "http://subtlepatterns.com/textured-stripes/" description: "A lovely light gray pattern with stripes and a dash of noise." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/textured_stripes.png" author: "<a href=\"http://tiled-bg.blogspot.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/textured_stripes.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/textured_stripes.png" title: "Textured Stripes" categories: ["light"] image_dimensions: "256x256" , image_size: "27K" link: "http://subtlepatterns.com/strange-bullseyes/" description: "This is indeed a bit strange, but here’s to the crazy ones!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/strange_bullseyes.png" author: "<a href=\"http://cwbuecheler.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/strange_bullseyes.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/strange_bullseyes.png" title: "Strange Bullseyes" categories: ["light"] image_dimensions: "300x300" , image_size: "22K" link: "http://subtlepatterns.com/low-contrast-linen/" description: "A smooth mid-tone gray, or low contrast if you will, linen pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/low_contrast_linen.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/low_contrast_linen.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/low_contrast_linen.png" title: "Low Contrast Linen" categories: ["dark"] image_dimensions: "256x256" , image_size: "56K" link: "http://subtlepatterns.com/egg-shell/" description: "It’s an egg, in the form of a pattern. This really is 2012." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/egg_shell.png" author: "<a href=\"http://phoenixweiss.me\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/egg_shell.zip" image: "http://subtlepatterns.com/patterns/egg_shell.png" title: "Egg Shell" categories: ["light"] image_dimensions: "256x256" , image_size: "142K" link: "http://subtlepatterns.com/clean-gray-paper/" description: "On a large canvas you can see it tiling, but used on smaller areas it’s beautiful." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/extra_clean_paper.png" author: "<a href=\"http://phoenixweiss.me\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/extra_clean_paper.zip" image: "http://subtlepatterns.com/patterns/extra_clean_paper.png" title: "Clean gray paper" categories: ["light"] image_dimensions: "512x512" , image_size: "443B" link: "http://subtlepatterns.com/norwegian-rose/" description: "I’m not going to lie – if you submit something with the words Norwegian and Rose in it, it’s likely I’ll publish it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/norwegian_rose.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/norwegian_rose.zip" image: "http://subtlepatterns.com/patterns/norwegian_rose.png" title: "Norwegian Rose" categories: ["light", "rose"] image_dimensions: "48x48" , image_size: "291B" link: "http://subtlepatterns.com/subtlenet/" description: "You can never get enough of these tiny pixel patterns with sharp lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtlenet2.png" author: "<a href=\"http://www.designova.net\" target=\"_blank\">Designova</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtlenet2.zip" image: "http://subtlepatterns.com/patterns/subtlenet2.png" title: "SubtleNet" categories: ["light"] image_dimensions: "60x60" , image_size: "32K" link: "http://subtlepatterns.com/dirty-old-black-shirt/" description: "Used in small doses, this could be a nice subtle pattern. Used on a large surface, it’s dirty!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dirty_old_shirt.png" author: "<a href=\"https://twitter.com/#!/PaulReulat\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dirty_old_shirt.zip" image: "http://subtlepatterns.com/patterns/dirty_old_shirt.png" title: "Dirty old black shirt" categories: ["dark"] image_dimensions: "250x250" , image_size: "71K" link: "http://subtlepatterns.com/redox-02/" description: "After 1 comes 2, same but different. You get the idea." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/redox_02.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/redox_02.zip" image: "http://subtlepatterns.com/patterns/redox_02.png" title: "Redox 02" categories: ["light"] image_dimensions: "600x340" , image_size: "88K" link: "http://subtlepatterns.com/redox-01/" description: "Bright gray tones with a hint of some metal surface." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/redox_01.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/redox_01.zip" image: "http://subtlepatterns.com/patterns/redox_01.png" title: "Redox 01" categories: ["light"] image_dimensions: "600x375" , image_size: "51K" link: "http://subtlepatterns.com/skin-side-up/" description: "White fabric looking texture with some nice random wave features." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/skin_side_up.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\"><NAME>mers</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/skin_side_up.zip" image: "http://subtlepatterns.com/patterns/skin_side_up.png" title: "Skin Side Up" categories: ["light"] image_dimensions: "320x360" , image_size: "211K" link: "http://subtlepatterns.com/solid/" description: "A mid-tone gray patterns with some cement looking texture." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/solid.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/solid.zip" image: "http://subtlepatterns.com/patterns/solid.png" title: "Solid" categories: ["cement", "light"] image_dimensions: "500x500" , image_size: "297B" link: "http://subtlepatterns.com/stitched-wool/" description: "I love these crisp, tiny, super subtle patterns." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/stitched_wool.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stitched_wool.zip" image: "http://subtlepatterns.com/patterns/stitched_wool.png" title: "Stitched Wool" categories: ["light"] image_dimensions: "224x128" , image_size: "50K" link: "http://subtlepatterns.com/crisp-paper-ruffles/" description: "Sort of reminds me of those old house wallpapers." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/crisp_paper_ruffles.png" author: "<a href=\"http://www.ayonnette.blogspot.com\" target=\"_blank\">Tish</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/crisp_paper_ruffles.zip" image: "http://subtlepatterns.com/patterns/crisp_paper_ruffles.png" title: "Crisp Paper Ruffles" categories: ["light"] image_dimensions: "481x500" , image_size: "1K" link: "http://subtlepatterns.com/white-linen/" description: "Dead simple but beautiful horizontal line pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/linen.png" author: "<a href=\"http://fabianschultz.de/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/linen.zip" image: "http://subtlepatterns.com/patterns/linen.png" title: "White Linen" categories: ["light"] image_dimensions: "400x300" , image_size: "122B" link: "http://subtlepatterns.com/polyester-lite/" description: "A tiny polyester pixel pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/polyester_lite.png" author: "<a href=\"http://dribbble.com/jeremyelder\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/polyester_lite.zip" image: "http://subtlepatterns.com/patterns/polyester_lite.png" title: "Polyester Lite" categories: ["light"] image_dimensions: "17x22" , image_size: "131K" link: "http://subtlepatterns.com/light-paper-fibers/" description: "More in the paper realm, this time with fibers." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/lightpaperfibers.png" author: "<a href=\"http://www.jorgefuentes.net\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/lightpaperfibers.zip" image: "http://subtlepatterns.com/patterns/lightpaperfibers.png" title: "Light paper fibers" categories: ["light"] image_dimensions: "500x300" , image_size: "98K" link: "http://subtlepatterns.com/natural-paper/" description: "You know I’m a sucker for these. Well crafted paper pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/natural_paper.png" author: "<NAME>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/natural_paper.zip" image: "http://subtlepatterns.com/patterns/natural_paper.png" title: "Natural Paper" categories: ["light"] image_dimensions: "523x384" , image_size: "47K" link: "http://subtlepatterns.com/burried/" description: "Have you wondered about how it feels to be buried alive? Here is the pattern for it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/burried.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/burried.zip" image: "http://subtlepatterns.com/patterns/burried.png" title: "Burried" categories: ["dark", "mud"] image_dimensions: "350x350" , image_size: "44K" link: "http://subtlepatterns.com/rebel/" description: "Not the Rebel alliance, but a dark textured pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rebel.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rebel.zip" image: "http://subtlepatterns.com/patterns/rebel.png" title: "Rebel" categories: ["dark"] image_dimensions: "320x360" , image_size: "7K" link: "http://subtlepatterns.com/assault/" description: "Dark, crisp and sort of muddy this one." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/assault.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/assault.zip" image: "http://subtlepatterns.com/patterns/assault.png" title: "Assault" categories: ["dark"] image_dimensions: "154x196" , image_size: "146B" link: "http://subtlepatterns.com/absurdity/" description: "Bit of a strange name on this one, but still nice. Tiny gray square things." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/absurdidad.png" author: "<a href=\"http://saveder.blogspot.mx/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/absurdidad.zip" image: "http://subtlepatterns.com/patterns/absurdidad.png" title: "Absurdity" categories: ["light"] image_dimensions: "4x4" , image_size: "103B" link: "http://subtlepatterns.com/white-carbonfiber/" description: "More carbon fiber for your collections. This time in white or semi-dark gray." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_carbonfiber.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_carbonfiber.zip" image: "http://subtlepatterns.com/patterns/white_carbonfiber.png" title: "White Carbonfiber" categories: ["carbon", "light"] image_dimensions: "4x4" , image_size: "1K" link: "http://subtlepatterns.com/white-bed-sheet/" description: "Nothing like a clean set of bed sheets, huh?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_bed_sheet.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_bed_sheet.zip" image: "http://subtlepatterns.com/patterns/white_bed_sheet.png" title: "White Bed Sheet" categories: ["light"] image_dimensions: "54x54" , image_size: "24K" link: "http://subtlepatterns.com/skewed-print/" description: "An interesting dark spotted pattern at an angle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/skewed_print.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/skewed_print.zip" image: "http://subtlepatterns.com/patterns/skewed_print.png" title: "Skewed print" categories: ["dark"] image_dimensions: "330x320" , image_size: "31K" link: "http://subtlepatterns.com/dark-wall/" description: "Just to prove my point, here is a slightly modified dark version." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_wall.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_wall.zip" image: "http://subtlepatterns.com/patterns/dark_wall.png" title: "Dark Wall" categories: ["dark"] image_dimensions: "300x300" , image_size: "47K" link: "http://subtlepatterns.com/wall-4-light/" description: "I’m starting to think I have a concrete wall fetish." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wall4.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wall4.zip" image: "http://subtlepatterns.com/patterns/wall4.png" title: "Wall #4 Light" categories: ["light"] image_dimensions: "300x300" , image_size: "395B" link: "http://subtlepatterns.com/escheresque/" description: "Cubes as far as your eyes can see. You know, because they tile." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/escheresque.png" author: "<a href=\"http://dribbble.com/janmeeus\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/escheresque.zip" image: "http://subtlepatterns.com/patterns/escheresque.png" title: "Escheresque" categories: ["light"] image_dimensions: "46x29" , image_size: "209B" link: "http://subtlepatterns.com/climpek/" description: "Small gradient crosses inside 45 degree boxes, or bigger crosses if you will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/climpek.png" author: "<a href=\"http://blugraphic.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/climpek.zip" image: "http://subtlepatterns.com/patterns/climpek.png" title: "Climpek" categories: ["light"] image_dimensions: "44x44" , image_size: "154B" link: "http://subtlepatterns.com/nistri/" description: "No idea what Nistri means, but it’s a crisp little pattern nonetheless." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/nistri.png" author: "<a href=\"http://reitermark.us/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/nistri.zip" image: "http://subtlepatterns.com/patterns//nistri.png" title: "Nistri" categories: ["light"] image_dimensions: "38x38" , image_size: "242K" link: "http://subtlepatterns.com/white-wall/" description: "A huge one at 800x600px. Made from a photo I took going home after work." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_wall.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">At<NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_wall.zip" image: "http://subtlepatterns.com/patterns/white_wall.png" title: "White wall" categories: ["light", "wall"] image_dimensions: "800x600" , image_size: "390B" link: "http://subtlepatterns.com/the-black-mamba/" description: "Super dark, crisp and detailed. And a Kill Bill reference." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_mamba.png" author: "<a href=\"http://graphicriver.net/user/graphcoder?ref=graphcoder\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_mamba.zip" image: "http://subtlepatterns.com/patterns/black_mamba.png" title: "The Black Mamba" categories: ["dark"] image_dimensions: "192x192" , image_size: "8K" link: "http://subtlepatterns.com/diamond-upholstery/" description: "A re-make of the Gradient Squares pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diamond_upholstery.png" author: "<a href=\"http://hellogrid.com\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diamond_upholstery.zip" image: "http://subtlepatterns.com/patterns/diamond_upholstery.png" title: "Diamond Upholstery" categories: ["diamond", "light"] image_dimensions: "200x200" , image_size: "179B" link: "http://subtlepatterns.com/corrugation/" description: "The act or state of corrugating or of being corrugated, a wrinkle; fold; furrow; ridge." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/corrugation.png" author: "<a href=\"http://graphicriver.net/user/Naf_Naf?ref=Naf_Naf\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/corrugation.zip" image: "http://subtlepatterns.com/patterns/corrugation.png" title: "Corrugation" categories: ["light"] image_dimensions: "8x5" , image_size: "479B" link: "http://subtlepatterns.com/reticular-tissue/" description: "Tiny and crisp, just the way it should be." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/reticular_tissue.png" author: "<a href=\"http://graphicriver.net/user/Naf_Naf?ref=Naf_Naf\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/reticular_tissue.zip" image: "http://subtlepatterns.com/patterns/reticular_tissue.png" title: "Reticular Tissue" categories: ["light"] image_dimensions: "25x25" , image_size: "408B" link: "http://subtlepatterns.com/lyonnette/" description: "Small crosses with round edges. Quite cute." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/lyonnette.png" author: "<a href=\"http://www.ayonnette.blogspot.com\" target=\"_blank\">Tish</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/lyonnette.zip" image: "http://subtlepatterns.com/patterns/lyonnette.png" title: "Lyonnette" categories: ["light"] image_dimensions: "90x90" , image_size: "21K" link: "http://subtlepatterns.com/light-toast/" description: "Has nothing to do with toast, but it’s nice and subtle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_toast.png" author: "<a href=\"https://twitter.com/#!/pippinlee\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_toast.zip" image: "http://subtlepatterns.com/patterns/light_toast.png" title: "Light Toast" categories: ["light", "noise"] image_dimensions: "200x200" , image_size: "24K" link: "http://subtlepatterns.com/txture/" description: "Dark, lines, noise, tactile. You get the drift." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/txture.png" author: "<a href=\"http://designchomp.com/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/txture.zip" image: "http://subtlepatterns.com/patterns/txture.png" title: "Txture" categories: ["dark"] image_dimensions: "400x300" , image_size: "6K" link: "http://subtlepatterns.com/gray-floral/" description: "Floral patterns might not be the hottest thing right now, but you never know when you need it!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/greyfloral.png" author: "<a href=\"http://laurenharrison.org\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/greyfloral.zip" image: "http://subtlepatterns.com/patterns/greyfloral.png" title: "Gray Floral" categories: ["floral", "light"] image_dimensions: "150x124" , image_size: "85B" link: "http://subtlepatterns.com/brilliant/" description: "This is so subtle you need to bring your magnifier!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/brillant.png" author: "<a href=\"http://saveder.blogspot.mx/\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/brillant.zip" image: "http://subtlepatterns.com/patterns/brillant.png" title: "Brilliant" categories: ["light", "subtle"] image_dimensions: "3x3" , image_size: "1K" link: "http://subtlepatterns.com/subtle-stripes/" description: "Vertical lines with a bumpy yet crisp feel to it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_stripes.png" author: "<a href=\"http://cargocollective.com/raasa\" target=\"_blank\">Raasa</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_stripes.zip" image: "http://subtlepatterns.com/patterns/subtle_stripes.png" title: "Subtle stripes" categories: ["light", "stripes"] image_dimensions: "40x40" , image_size: "86K" link: "http://subtlepatterns.com/cartographer/" description: "A topographic map like this has actually been requested a few times, so here you go!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cartographer.png" author: "<a href=\"http://sam.feyaerts.me\" target=\"_blank\"><NAME></a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cartographer.zip" image: "http://subtlepatterns.com/patterns/cartographer.png" title: "Cartographer" categories: ["cartographer", "dark", "topography"] image_dimensions: "500x499" ]
true
window.SUBTLEPATTERNS = [ link: "http://subtlepatterns.com/squairy/" description: "Super tiny dots and all sorts of great stuff." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/squairy_light.png" author: "PI:NAME:<NAME>END_PI" download: "/patterns/squairy_light.zip" image: "/patterns/squairy_light.png" title: "Squairy" categories: ["light"] , link: "http://subtlepatterns.com/binding-light/" description: "Light gray version of the Binding pattern. A bit like fabric." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/binding_light.png" author: "PI:NAME:<NAME>END_PI" download: "/patterns/binding_light.zip" image: "/patterns/binding_light.png" title: "Binding light" categories: ["light"] , link: "http://subtlepatterns.com/binding-dark/" description: "This works great as-is, or you can tone it down even more." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/binding_dark.png" author: "PI:NAME:<NAME>END_PI" download: "/patterns/binding_dark.zip" image: "/patterns/binding_dark.png" title: "Binding dark" categories: ["dark"] , link: "http://subtlepatterns.com/ps-neutral/" description: "This one is so simple, yet so good. And you know it. Has to be in the collection." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ps_neutral.png" author: "<a href=\"http://www.gluszczenko.com\" target=\"_blank\">Gluszczenko</a>" download: "/patterns/ps_neutral.zip" image: "/patterns/ps_neutral.png" title: "PS Neutral" categories: ["light"] , link: "http://subtlepatterns.com/wave-grind/" description: "Submitted by DomainsInfo – wtf, right? But hey, a free pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wavegrid.png" author: "<a href=\"http://www.domainsinfo.org/\" target=\"_blank\">DomainsInfo</a>" download: "/patterns/wavegrid.zip" image: "/patterns/wavegrid.png" title: "Wave Grind" categories: ["light"] , link: "http://subtlepatterns.com/textured-paper/" description: "You know I love paper patterns. Here is one from PI:NAME:<NAME>END_PI. Say thank you!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/textured_paper.png" author: "<a href=\"http://stephen.io\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "/patterns/textured_paper.zip" image: "/patterns/textured_paper.png" title: "Textured Paper" categories: ["light", "paper"] , link: "http://subtlepatterns.com/grey-washed-wall/" description: "This is a semi-dark pattern, sort of linen-y." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grey_wash_wall.png" author: "<a href=\"http://www.sagive.co.il\" target=\"_blank\">Sagive SEO</a>" download: "/patterns/grey_wash_wall.zip" image: "/patterns/grey_wash_wall.png" title: "Grey Washed Wall" categories: ["dark", "linen"] , link: "http://subtlepatterns.com/p6/" description: "And finally, number 6. Enjoy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/p6.png" author: "<a href=\"http://www.epictextures.com/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "/patterns/p6.zip" image: "/patterns/p6.png" title: "P6" categories: ["light"] , link: "http://subtlepatterns.com/p5/" description: "Number five from the same submitter, makes my job easy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/p5.png" author: "<a href=\"http://www.epictextures.com/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "/patterns/p5.zip" image: "/patterns/p5.png" title: "P5" categories: ["light"] , link: "http://subtlepatterns.com/p4/" description: "I skipped number 3, cause it wasn’t all that great. Sorry." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/p4.png" author: "<a href=\"http://www.epictextures.com/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "/patterns/p4.zip" image: "/patterns/p4.png" title: "P4" categories: ["light"] , image_size: "493B" link: "http://subtlepatterns.com/escheresque-dark/" description: "A comeback for you, the populare Escheresque now in black." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/escheresque_ste.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/escheresque_ste.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/escheresque_ste.png" title: "Escheresque dark" categories: ["dark"] image_dimensions: "46x29" , image_size: "278B" link: "http://subtlepatterns.com/%d0%b2lack-lozenge/" description: "Not the most subtle one, but a nice pattern still." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_lozenge.png" author: "<a href=\"http://www.listvetra.ru\" target=\"_blank\">ListPI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_lozenge.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_lozenge.png" title: "Вlack lozenge" categories: ["dark"] image_dimensions: "38x38" , image_size: "3K" link: "http://subtlepatterns.com/kinda-jean/" description: "A nice one indeed, but I got a feeling we have it already? If you spot a copy, let me know on Twitter ." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/kindajean.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Graphiste.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/kindajean.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/kindajean.png" title: "KindPI:NAME:<NAME>END_PI Jean" categories: ["light"] image_dimensions: "147x147" , image_size: "72K" link: "http://subtlepatterns.com/paper-fibers/" description: "Just what the name says, paper fibers. Always good to have." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper_fibers.png" author: "<a href=\"http://about.me/heliodor\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_fibers.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_fibers.png" title: "Paper Fibers" categories: ["light"] image_dimensions: "410x410" , image_size: "128B" link: "http://subtlepatterns.com/dark-fish-skin/" description: "It almost looks a bit blurry, but then again so are fishes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_fish_skin.png" author: "<a href=\"http://www.petrsulc.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_fish_skin.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_fish_skin.png" title: "Dark Fish Skin" categories: ["dark"] image_dimensions: "6x12" , image_size: "600B" link: "http://subtlepatterns.com/maze-white/" description: "Just like the black maze, only in light gray. Duh." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pw_maze_white.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">PePI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pw_maze_white.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pw_maze_white.png" title: "Maze white" categories: ["light"] image_dimensions: "46x23" , image_size: "600B" link: "http://subtlepatterns.com/maze-black/" description: "Classy little maze for you, in two colors even." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pw_maze_black.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Peax.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pw_maze_black.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pw_maze_black.png" title: "Maze black" categories: ["dark"] image_dimensions: "46x23" , image_size: "137B" link: "http://subtlepatterns.com/satin-weave/" description: "Super simple but very nice indeed. Gray with vertical stripes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/satinweave.png" author: "<a href=\"http://www.merxplat.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/satinweave.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/satinweave.png" title: "Satin weave" categories: ["light"] image_dimensions: "24x12" , image_size: "266B" link: "http://subtlepatterns.com/ecailles/" description: "Almost like little fish shells, or dragon skin." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ecailles.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Graphiste.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ecailles.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ecailles.png" title: "Ecailles" categories: ["light"] image_dimensions: "48x20" , image_size: "82K" link: "http://subtlepatterns.com/subtle-grunge/" description: "A heavy hitter at 400x400px, but lovely still." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_grunge.png" author: "<a href=\"http://breezi.com\" target=\"_blank\">Breezi.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_grunge.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_grunge.png" title: "Subtle grunge" categories: ["light"] image_dimensions: "400x400" , image_size: "11K" link: "http://subtlepatterns.com/honey-im-subtle/" description: "First off in 2013, a mid-gray hexagon pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/honey_im_subtle.png" author: "<a href=\"http://www.blof.dk\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/honey_im_subtle.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/honey_im_subtle.png" title: "Honey I’m subtle" categories: ["hexagon", "light"] image_dimensions: "179x132" , image_size: "13K" link: "http://subtlepatterns.com/grey-jean/" description: "Yummy, this is one good looking pattern. Grab it!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gray_jean.png" author: "<a href=\"http://mr.pn\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gray_jean.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gray_jean.png" title: "Grey Jean" categories: ["light"] image_dimensions: "150x150" , image_size: "75K" link: "http://subtlepatterns.com/lined-paper-2/" description: "I know there already is one here, but shit – this is sexy!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/linedpaper.png" author: "<a href=\"http://www.tight.no\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/linedpaper.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/linedpaper.png" title: "Lined paper" categories: ["light"] image_dimensions: "412x300" , image_size: "39K" link: "http://subtlepatterns.com/blach-orchid/" description: "Blach is the new Black." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/blackorchid.png" author: "<a href=\"http://www.hybridixstudio.com\" target=\"_blank\">Hybridixstudio.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blackorchid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blackorchid.png" title: "Blach Orchid" categories: ["dark"] image_dimensions: "300x300" , image_size: "10K" link: "http://subtlepatterns.com/white-wall-2/" description: "A new one called white wall, not by me this time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_wall2.png" author: "<a href=\"https://corabbit.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_wall2.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_wall2.png" title: "White wall 2" categories: ["light"] image_dimensions: "150x150" , image_size: "279B" link: "http://subtlepatterns.com/diagonales-decalees/" description: "Sounds French. Some 3D square diagonals, that’s all you need to know." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagonales_decalees.png" author: "<a href=\"http://www.peax-webdesign.com\" target=\"_blank\">Graphiste.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonales_decalees.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonales_decalees.png" title: "Diagonales decalées" categories: ["light"] image_dimensions: "144x48" , image_size: "12K" link: "http://subtlepatterns.com/cream-paper/" description: "Submitted in a cream color, but you know how I like it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/creampaper.png" author: "<a href=\"http://www.strick9design.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/creampaper.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/creampaper.png" title: "Cream paper" categories: ["light"] image_dimensions: "158x144" , image_size: "19K" link: "http://subtlepatterns.com/debut-dark/" description: "Same classic 45 degree pattern with class, dark version." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/debut_dark.png" author: "<a href=\"http://lukemcdonald.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/debut_dark.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/debut_dark.png" title: "Debut dark" categories: ["dark"] image_dimensions: "200x200" , image_size: "18K" link: "http://subtlepatterns.com/debut-light/" description: "Classic 45 degree pattern with class, light version." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/debut_light.png" author: "<a href=\"http://lukemcdonald.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/debut_light.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/debut_light.png" title: "Debut light" categories: ["light"] image_dimensions: "200x200" , image_size: "9K" link: "http://subtlepatterns.com/twinkle-twinkle/" description: "A very dark spotted twinkle pattern for you twinkle needs." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/twinkle_twinkle.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/twinkle_twinkle.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/twinkle_twinkle.png" title: "Twinkle Twinkle" categories: ["dark"] image_dimensions: "360x300" , image_size: "2K" link: "http://subtlepatterns.com/tapestry/" description: "Tiny and subtle. What’s not to love?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tapestry_pattern.png" author: "<a href=\"http://www.pixeden.com\" target=\"_blank\">Pixeden</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tapestry_pattern.zip" image: "http://subtlepatterns.com/patterns/tapestry_pattern.png" title: "Tapestry" categories: ["light"] image_dimensions: "72x61" , image_size: "3K" link: "http://subtlepatterns.com/psychedelic/" description: "Geometric triangles seem to be quite hot these days." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/psychedelic_pattern.png" author: "<a href=\"http://www.pixeden.com\" target=\"_blank\">Pixeden</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/psychedelic_pattern.zip" image: "http://subtlepatterns.com/patterns/psychedelic_pattern.png" title: "Psychedelic" categories: ["light"] image_dimensions: "84x72" , image_size: "2K" link: "http://subtlepatterns.com/triangles-2/" description: "Sharp but soft triangles in light shades of gray." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/triangles_pattern.png" author: "<a href=\"http://www.pixeden.com\" target=\"_blank\">Pixeden</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/triangles_pattern.zip" image: "http://subtlepatterns.com/patterns/triangles_pattern.png" title: "Triangles" categories: ["light"] image_dimensions: "72x72" , image_size: "125B" link: "http://subtlepatterns.com/flower-trail/" description: "Sharp pixel pattern, just like the good old days." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/flowertrail.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/flowertrail.zip" image: "http://subtlepatterns.com/patterns/flowertrail.png" title: "Flower Trail" categories: ["flower", "light"] image_dimensions: "16x16" , image_size: "41K" link: "http://subtlepatterns.com/scribble-light/" description: "A bit like smudged paint or some sort of steel, here is scribble light." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/scribble_light.png" author: "<a href=\"http://thelovelyfox.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/scribble_light.zip" image: "http://subtlepatterns.com/patterns/scribble_light.png" title: "Scribble Light" categories: ["light"] image_dimensions: "304x306" , image_size: "76K" link: "http://subtlepatterns.com/clean-textile/" description: "A nice light textile pattern for your kit." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/clean_textile.png" author: "N8rx" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/clean_textile.zip" image: "http://subtlepatterns.com/patterns/clean_textile.png" title: "Clean Textile" categories: ["light", "textile"] image_dimensions: "420x420" , image_size: "11K" link: "http://subtlepatterns.com/gplay/" description: "A playful triangle pattern with different shades of gray." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gplaypattern.png" author: "<a href=\"http://dhesign.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gplaypattern.zip" image: "http://subtlepatterns.com/patterns/gplaypattern.png" title: "GPlay" categories: ["light"] image_dimensions: "188x178" , image_size: "235B" link: "http://subtlepatterns.com/weave/" description: "Medium gray pattern with small strokes to give a weave effect." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/weave.png" author: "<a href=\"http://wellterned.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/weave.zip" image: "http://subtlepatterns.com/patterns/weave.png" title: "Weave" categories: ["light"] image_dimensions: "35x31" , image_size: "165B" link: "http://subtlepatterns.com/embossed-paper/" description: "One more from Badhon, sharp horizontal lines making an embossed paper feeling." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/embossed_paper.png" author: "<a href=\"http://graphicriver.net/user/graphcoder?ref=graphcoder\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/embossed_paper.zip" image: "http://subtlepatterns.com/patterns/embossed_paper.png" title: "Embossed Paper" categories: ["light"] image_dimensions: "8x10" , image_size: "176B" link: "http://subtlepatterns.com/graphcoders-lil-fiber/" description: "Tiny little fibers making a soft and sweet look." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/lil_fiber.png" author: "<a href=\"http://graphicriver.net/user/graphcoder?ref=graphcoder\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/lil_fiber.zip" image: "http://subtlepatterns.com/patterns/lil_fiber.png" title: "Graphcoders Lil Fiber" categories: ["light"] image_dimensions: "21x35" , image_size: "6K" link: "http://subtlepatterns.com/white-tiles/" description: "A nice and simple white rotated tile pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_tiles.png" author: "<a href=\"http://www.anotherone.fr/\" target=\"_blank\">Another One.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_tiles.zip" image: "http://subtlepatterns.com/patterns/white_tiles.png" title: "White tiles" categories: ["light"] image_dimensions: "800x250" , image_size: "33K" link: "http://subtlepatterns.com/tex2res5/" description: "Number 5 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res5.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res5.zip" image: "http://subtlepatterns.com/patterns/tex2res5.png" title: "Tex2res5" categories: ["light"] image_dimensions: "500x500" , image_size: "92K" link: "http://subtlepatterns.com/tex2res3/" description: "Number 4 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res3.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res3.zip" image: "http://subtlepatterns.com/patterns/tex2res3.png" title: "Tex2res3" categories: ["light"] image_dimensions: "500x500" , image_size: "94K" link: "http://subtlepatterns.com/tex2res1/" description: "Number 3 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res1.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res1.zip" image: "http://subtlepatterns.com/patterns/tex2res1.png" title: "Tex2res1" categories: ["light"] image_dimensions: "500x500" , image_size: "130K" link: "http://subtlepatterns.com/tex2res2/" description: "Number 2 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res2.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res2.zip" image: "http://subtlepatterns.com/patterns/tex2res2.png" title: "Tex2res2" categories: ["light"] image_dimensions: "500x500" , image_size: "151K" link: "http://subtlepatterns.com/tex2res4/" description: "Number 1 in a series of 5 beautiful patterns. Can be found in colors on the submitters website." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tex2res4.png" author: "<a href=\"http://joxadesign.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tex2res4.zip" image: "http://subtlepatterns.com/patterns/tex2res4.png" title: "Tex2res4" categories: ["dark"] image_dimensions: "500x500" , image_size: "813B" link: "http://subtlepatterns.com/arches/" description: "One more in the line of patterns inspired by the Japanese/asian styles. Smooth." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/arches.png" author: "<a href=\"http://www.webdesigncreare.co.uk/\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/arches.zip" image: "http://subtlepatterns.com/patterns/arches.png" title: "Arches" categories: [] image_dimensions: "103x23" , image_size: "141B" link: "http://subtlepatterns.com/shine-caro/" description: "It’s like shine dotted’s sister, only rotated 45 degrees." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/shinecaro.png" author: "<a href=\"http://www.mediumidee.de\" target=\"_blank\">mediumidee.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shinecaro.zip" image: "http://subtlepatterns.com/patterns/shinecaro.png" title: "Shine Caro" categories: ["light", "shiny"] image_dimensions: "9x9" , image_size: "97B" link: "http://subtlepatterns.com/shine-dotted/" description: "Tiny shiny dots all over your screen." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/shinedotted.png" author: "<a href=\"http://www.mediumidee.de\" target=\"_blank\">mediumidee.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shinedotted.zip" image: "http://subtlepatterns.com/patterns/shinedotted.png" title: "Shine dotted" categories: ["dotted", "light"] image_dimensions: "6x5" , image_size: "19K" link: "http://subtlepatterns.com/worn-dots/" description: "These dots are already worn for you, so you don’t have to." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/worn_dots.png" author: "<a href=\"http://mattmcdaniel.me\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/worn_dots.zip" image: "http://subtlepatterns.com/patterns/worn_dots.png" title: "Worn Dots" categories: ["dots", "light"] image_dimensions: "200x200" , image_size: "24K" link: "http://subtlepatterns.com/light-mesh/" description: "Love me some light mesh on a Monday. Sharp." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/lghtmesh.png" author: "<a href=\"http://dribbble.com/bastienwilmotte\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/lghtmesh.zip" image: "http://subtlepatterns.com/patterns/lghtmesh.png" title: "Light Mesh" categories: ["light"] image_dimensions: "256x256" , image_size: "13K" link: "http://subtlepatterns.com/hexellence/" description: "Detailed but still subtle and quite original. Lovely gray shades." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/hexellence.png" author: "<a href=\"http://www.webdesigncreare.co.uk\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/hexellence.zip" image: "http://subtlepatterns.com/patterns/hexellence.png" title: "Hexellence" categories: ["geometric", "light"] image_dimensions: "150x173" , image_size: "21K" link: "http://subtlepatterns.com/dark-tire/" description: "Dark, crisp and subtle. Tiny black lines on top of some noise." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_Tire.png" author: "<a href=\"http://dribbble.com/bastienwilmotte\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_Tire.zip" image: "http://subtlepatterns.com/patterns/dark_Tire.png" title: "Dark Tire" categories: ["dark", "tire"] image_dimensions: "250x250" , image_size: "6K" link: "http://subtlepatterns.com/first-aid-kit/" description: "No, not the band but the pattern. Simple squares in gray tones, of course." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/first_aid_kit.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/first_aid_kit.zip" image: "http://subtlepatterns.com/patterns/first_aid_kit.png" title: "First Aid Kit" categories: ["light"] image_dimensions: "99x99" , image_size: "327B" link: "http://subtlepatterns.com/wide-rectangles/" description: "Simple wide squares with a small indent. Fit’s all." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wide_rectangles.png" author: "<a href=\"http://www.petrsulc.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wide_rectangles.zip" image: "http://subtlepatterns.com/patterns/wide_rectangles.png" title: "Wide rectangles" categories: ["light"] image_dimensions: "32x14" , image_size: "69K" link: "http://subtlepatterns.com/french-stucco/" description: "Fabric-ish patterns are close to my heart. French Stucco to the rescue." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/frenchstucco.png" author: "<a href=\"http://cwbuecheler.com/\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/frenchstucco.zip" image: "http://subtlepatterns.com/patterns/frenchstucco.png" title: "French Stucco" categories: ["light"] image_dimensions: "400x355" , image_size: "13K" link: "http://subtlepatterns.com/light-wool/" description: "Submitted as a black pattern, I made it light and a few steps more subtle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_wool.png" author: "<a href=\"http://www.tall.me.uk\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_wool.zip" image: "http://subtlepatterns.com/patterns/light_wool.png" title: "Light wool" categories: ["light", "wool"] image_dimensions: "190x191" , image_size: "48K" link: "http://subtlepatterns.com/gradient-squares/" description: "It’s big, it’s gradient – and they are square." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gradient_squares.png" author: "<a href=\"http://www.brankic1979.com\" target=\"_blank\">BrPI:NAME:<NAME>END_PI1PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gradient_squares.zip" image: "http://subtlepatterns.com/patterns/gradient_squares.png" title: "Gradient Squares" categories: ["gradient", "light", "square"] image_dimensions: "202x202" , image_size: "38K" link: "http://subtlepatterns.com/rough-diagonal/" description: "The classic 45 degree diagonal line pattern, done right." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rough_diagonal.png" author: "<a href=\"http://jorickvanhees.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rough_diagonal.zip" image: "http://subtlepatterns.com/patterns/rough_diagonal.png" title: "Rough diagonal" categories: ["diagonal", "light"] image_dimensions: "256x256" , image_size: "495B" link: "http://subtlepatterns.com/kuji/" description: "An interesting and original pattern from JPI:NAME:<NAME>END_PI." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/kuji.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/kuji.zip" image: "http://subtlepatterns.com/patterns/kuji.png" title: "Kuji" categories: ["kuji", "light"] image_dimensions: "30x30" , image_size: "241B" link: "http://subtlepatterns.com/little-triangles/" description: "The basic shapes never get old. Simple triangle pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/little_triangles.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/little_triangles.zip" image: "http://subtlepatterns.com/patterns/little_triangles.png" title: "Little triangles" categories: ["light", "triangle"] image_dimensions: "10x11" , image_size: "186B" link: "http://subtlepatterns.com/diamond-eyes/" description: "Everyone loves a diamond, right? Make your site sparkle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/daimond_eyes.png" author: "<a href=\"http://ajtroxell.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/daimond_eyes.zip" image: "http://subtlepatterns.com/patterns/daimond_eyes.png" title: "Diamond Eyes" categories: ["diamond", "light"] image_dimensions: "33x25" , image_size: "8K" link: "http://subtlepatterns.com/arabesque/" description: "Intricate pattern with arab influences." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/arab_tile.png" author: "<a href=\"http://www.twitter.com/davidsancar\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/arab_tile.zip" image: "http://subtlepatterns.com/patterns/arab_tile.png" title: "Arabesque" categories: ["arab", "light"] image_dimensions: "110x110" , image_size: "314B" link: "http://subtlepatterns.com/white-wave/" description: "Light and tiny just the way you like it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_wave.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_wave.zip" image: "http://subtlepatterns.com/patterns/white_wave.png" title: "White Wave" categories: ["light", "wave"] image_dimensions: "23x12" , image_size: "1K" link: "http://subtlepatterns.com/diagonal-striped-brick/" description: "Might not be super subtle, but quite original in it’s form." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagonal_striped_brick.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonal_striped_brick.zip" image: "http://subtlepatterns.com/patterns/diagonal_striped_brick.png" title: "Diagonal Striped Brick" categories: ["light"] image_dimensions: "150x150" , image_size: "217K" link: "http://subtlepatterns.com/purty-wood/" description: "You know you love wood patterns, so here’s one more." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/purty_wood.png" author: "<a href=\"http://www.purtypixels.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/purty_wood.zip" image: "http://subtlepatterns.com/patterns/purty_wood.png" title: "Purty Wood" categories: ["light", "wood"] image_dimensions: "400x400" , image_size: "412B" link: "http://subtlepatterns.com/vaio-pattern/" description: "I’m guessing this is related to the Sony Vaio? It’s a nice pattern no matter where it’s from." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/vaio_hard_edge.png" author: "<a href=\"http://www.zigzain.com\" target=\"_blank\">ZPI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/vaio_hard_edge.zip" image: "http://subtlepatterns.com/patterns/vaio_hard_edge.png" title: "Vaio" categories: ["light", "sony", "vaio"] image_dimensions: "37x28" , image_size: "123B" link: "http://subtlepatterns.com/stacked-circles/" description: "A simple circle. That’s all it takes. This one is even transparent, for those who like that." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/stacked_circles.png" author: "<a href=\"http://www.960development.com\" target=\"_blank\">Saqib.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stacked_circles.zip" image: "http://subtlepatterns.com/patterns/stacked_circles.png" title: "Stacked Circles" categories: ["circle", "light", "tiny"] image_dimensions: "9x9" , image_size: "102B" link: "http://subtlepatterns.com/outlets/" description: "Just 4x8px, but still so stylish!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/outlets.png" author: "<a href=\"http://michalchovanec.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/outlets.zip" image: "http://subtlepatterns.com/patterns/outlets.png" title: "Outlets" categories: ["dark", "tiny"] image_dimensions: "4x8" , image_size: "41K" link: "http://subtlepatterns.com/light-sketch/" description: "Nice and gray, just the way I like it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/furley_bg.png" author: "<a href=\"http://dankruse.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/furley_bg.zip" image: "http://subtlepatterns.com/patterns/furley_bg.png" title: "Light Sketch" categories: ["light"] image_dimensions: "600x600" , image_size: "126B" link: "http://subtlepatterns.com/tasky/" description: "Your eyes can trip a bit from looking at this – use it wisely." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tasky_pattern.png" author: "<a href=\"http://michalchovanec.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tasky_pattern.zip" image: "http://subtlepatterns.com/patterns/tasky_pattern.png" title: "Tasky" categories: ["dark", "zigzag"] image_dimensions: "10x10" , image_size: "58K" link: "http://subtlepatterns.com/pinstriped-suit/" description: "Just like your old suit, all striped and smooth." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pinstriped_suit.png" author: "<a href=\"http://www.alexberkowitz.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pinstriped_suit.zip" image: "http://subtlepatterns.com/patterns/pinstriped_suit.png" title: "Pinstriped Suit" categories: ["dark", "suit"] image_dimensions: "400x333" , image_size: "240B" link: "http://subtlepatterns.com/blizzard/" description: "This is so subtle I hope you can see it! Tweak at will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/blizzard.png" author: "<a href=\"http://www.alexandrenaud.fr\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blizzard.zip" image: "http://subtlepatterns.com/patterns/blizzard.png" title: "Blizzard" categories: ["blizzard", "light"] image_dimensions: "25x25" , image_size: "1K" link: "http://subtlepatterns.com/bo-play/" description: "Inspired by the B&O Play , I had to make this pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/bo_play_pattern.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bo_play_pattern.zip" image: "http://subtlepatterns.com/patterns/bo_play_pattern.png" title: "BO Play" categories: ["bo", "carbon", "dark", "play"] image_dimensions: "42x22" , image_size: "152K" link: "http://subtlepatterns.com/farmer/" description: "Farmer could be some sort of fabric pattern, with a hint of green." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/farmer.png" author: "<a href=\"http://fabianschultz.de\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/farmer.zip" image: "http://subtlepatterns.com/patterns/farmer.png" title: "Farmer" categories: ["farmer", "light", "paper"] image_dimensions: "349x349" , image_size: "83K" link: "http://subtlepatterns.com/paper/" description: "Nicely crafted paper pattern, all though a bit on the large side (500x593px)." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper.png" author: "<a href=\"http://timeproduction.ru\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper.zip" image: "http://subtlepatterns.com/patterns/paper.png" title: "Paper" categories: ["light", "paper"] image_dimensions: "500x593" , image_size: "167K" link: "http://subtlepatterns.com/tileable-wood/" description: "Not so subtle, and the name is obvious – these tilable wood patterns are very useful." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tileable_wood_texture.png" author: "<a href=\"http://elemisfreebies.com/\" target=\"_blank\">Elemis.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tileable_wood_texture.zip" image: "http://subtlepatterns.com/patterns/tileable_wood_texture.png" title: "Tileable wood" categories: ["light", "wood"] image_dimensions: "400x317" , image_size: "25K" link: "http://subtlepatterns.com/vintage-speckles/" description: "Lovely pattern with splattered vintage speckles." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/vintage_speckles.png" author: "<a href=\"http://simpleasmilk.co.uk\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/vintage_speckles.zip" image: "http://subtlepatterns.com/patterns/vintage_speckles.png" title: "Vintage Speckles" categories: ["light", "vintage"] image_dimensions: "400x300" , image_size: "463B" link: "http://subtlepatterns.com/quilt/" description: "Not sure what this is, but it looks good!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/quilt.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/quilt.zip" image: "http://subtlepatterns.com/patterns/quilt.png" title: "Quilt" categories: ["light", "quilt"] image_dimensions: "25x24" , image_size: "139K" link: "http://subtlepatterns.com/large-leather/" description: "More leather, and this time it’s bigger! You know, in case you need that." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/large_leather.png" author: "<a href=\"http://elemisfreebies.com/\" target=\"_blank\">Elemis.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/large_leather.zip" image: "http://subtlepatterns.com/patterns/large_leather.png" title: "Large leather" categories: ["leather", "light"] image_dimensions: "400x343" , image_size: "108B" link: "http://subtlepatterns.com/dark-dot/" description: "That’s what it is, a dark dot. Or sort of carbon-ish looking." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_dotted.png" author: "<a href=\"http://dribbble.com/bscsystem\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_dotted.zip" image: "http://subtlepatterns.com/patterns/dark_dotted.png" title: "Dark dot" categories: ["dark"] image_dimensions: "5x5" , image_size: "4K" link: "http://subtlepatterns.com/grid-noise/" description: "Crossing lines on a light background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grid_noise.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grid_noise.zip" image: "http://subtlepatterns.com/patterns/grid_noise.png" title: "Grid noise" categories: ["light"] image_dimensions: "98x98" , image_size: "1K" link: "http://subtlepatterns.com/argyle/" description: "Classy golf-pants pattern, or crossed stripes if you will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/argyle.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/argyle.zip" image: "http://subtlepatterns.com/patterns/argyle.png" title: "Argyle" categories: ["dark"] image_dimensions: "106x96" , image_size: "6K" link: "http://subtlepatterns.com/grey-sandbag/" description: "A bit strange this one, but nice at the same time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grey_sandbag.png" author: "<a href=\"http://www.diogosilva.net\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grey_sandbag.zip" image: "http://subtlepatterns.com/patterns/grey_sandbag.png" title: "Grey Sandbag" categories: ["light", "sandbag"] image_dimensions: "100x98" , image_size: "52K" link: "http://subtlepatterns.com/white-leather-2/" description: "I took the liberty of using Dmitry’s pattern and made a version without perforation." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_leather.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">AtPI:NAME:<NAME>END_PI Mo</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_leather.zip" image: "http://subtlepatterns.com/patterns/white_leather.png" title: "White leather" categories: ["leather", "light"] image_dimensions: "300x300" , image_size: "92K" link: "http://subtlepatterns.com/ice-age/" description: "I asked Gjermund if he could make a pattern for us – result!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ice_age.png" author: "<a href=\"http://tight.no\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ice_age.zip" image: "http://subtlepatterns.com/patterns/ice_age.png" title: "Ice age" categories: ["ice", "light", "snow"] image_dimensions: "400x400" , image_size: "55K" link: "http://subtlepatterns.com/perforated-white-leather/" description: "A bit of scratched up grayness. Always good." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/perforated_white_leather.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/perforated_white_leather.zip" image: "http://subtlepatterns.com/patterns/perforated_white_leather.png" title: "Perforated White Leather" categories: ["leather", "light"] image_dimensions: "300x300" , image_size: "7K" link: "http://subtlepatterns.com/church/" description: "I have no idea what PI:NAME:<NAME>END_PI means by this name, but hey – it’s hot." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/chruch.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/chruch.zip" image: "http://subtlepatterns.com/patterns/chruch.png" title: "Church" categories: ["light"] image_dimensions: "100x100" , image_size: "82K" link: "http://subtlepatterns.com/old-husks/" description: "A bit of scratched up grayness. Always good." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/husk.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/husk.zip" image: "http://subtlepatterns.com/patterns/husk.png" title: "Old husks" categories: ["brushed", "light"] image_dimensions: "500x500" , image_size: "379B" link: "http://subtlepatterns.com/cutcube/" description: "Cubes, geometry, 3D. What’s not to love?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cutcube.png" author: "<a href=\"http://cubecolour.co.uk\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cutcube.zip" image: "http://subtlepatterns.com/patterns/cutcube.png" title: "Cutcube" categories: ["3d", "cube", "light"] image_dimensions: "20x36" , image_size: "91K" link: "http://subtlepatterns.com/snow/" description: "Real snow that tiles, not easy. This is not perfect, but an attempt." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/snow.png" author: "<a href=\"http://www.atlemo.com/\" target=\"_blank\">AtPI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/snow.zip" image: "http://subtlepatterns.com/patterns/snow.png" title: "Snow" categories: ["light", "snow"] image_dimensions: "500x500" , image_size: "25K" link: "http://subtlepatterns.com/cross-scratches/" description: "Subtle scratches on a light gray background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cross_scratches.png" author: "<a href=\"http://www.ovcharov.me/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cross_scratches.zip" image: "http://subtlepatterns.com/patterns/cross_scratches.png" title: "Cross scratches" categories: ["light", "scratch"] image_dimensions: "256x256" , image_size: "403B" link: "http://subtlepatterns.com/subtle-zebra-3d/" description: "It’s a subtle zebra, in 3D. Oh yes!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_zebra_3d.png" author: "<a href=\"http://www.miketheindian.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_zebra_3d.zip" image: "http://subtlepatterns.com/patterns/subtle_zebra_3d.png" title: "Subtle Zebra 3D" categories: ["3d", "light"] image_dimensions: "121x38" , image_size: "494B" link: "http://subtlepatterns.com/fake-luxury/" description: "Fake or not, it’s quite luxurious." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fake_luxury.png" author: "<a href=\"http://www.factorio.us\" target=\"_blank\">Factorio.us Collective</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fake_luxury.zip" image: "http://subtlepatterns.com/patterns/fake_luxury.png" title: "Fake luxury" categories: ["light"] image_dimensions: "16x26" , image_size: "817B" link: "http://subtlepatterns.com/dark-geometric/" description: "Continuing the geometric trend, here is one more." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_geometric.png" author: "<a href=\"http://www.miketheindian.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_geometric.zip" image: "http://subtlepatterns.com/patterns/dark_geometric.png" title: "Dark Geometric" categories: ["dark", "geometric"] image_dimensions: "70x70" , image_size: "5K" link: "http://subtlepatterns.com/blu-stripes/" description: "Very simple, very blu(e). Subtle and nice." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/blu_stripes.png" author: "<a href=\"http://twitter.com/iamsebj\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blu_stripes.zip" image: "http://subtlepatterns.com/patterns/blu_stripes.png" title: "Blu Stripes" categories: ["blue", "light", "stripes"] image_dimensions: "100x100" , image_size: "128K" link: "http://subtlepatterns.com/texturetastic-gray/" description: "This ladies and gentlemen, is texturetastic! Love it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/texturetastic_gray.png" author: "<a href=\"http://www.adampickering.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/texturetastic_gray.zip" image: "http://subtlepatterns.com/patterns/texturetastic_gray.png" title: "Texturetastic Gray" categories: ["fabric", "light", "tactile"] image_dimensions: "476x476" , image_size: "220B" link: "http://subtlepatterns.com/soft-pad/" description: "Bumps, highlight and shadows – all good things." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/soft_pad.png" author: "<a href=\"http://ow.ly/8v3IG\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/soft_pad.zip" image: "http://subtlepatterns.com/patterns/soft_pad.png" title: "Soft Pad" categories: ["light"] image_dimensions: "8x8" , image_size: "8K" link: "http://subtlepatterns.com/classy-fabric/" description: "This is lovely, just the right amount of subtle noise, lines and textures." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/classy_fabric.png" author: "<a href=\"http://www.purtypixels.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/classy_fabric.zip" image: "http://subtlepatterns.com/patterns/classy_fabric.png" title: "Classy Fabric" categories: ["classy", "dark", "fabric"] image_dimensions: "102x102" , image_size: "911B" link: "http://subtlepatterns.com/hixs-evolution/" description: "Quite some heavy depth and shadows here, but might work well on some mobile apps?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/hixs_pattern_evolution.png" author: "<a href=\"http://www.hybridixstudio.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/hixs_pattern_evolution.zip" image: "http://subtlepatterns.com/patterns/hixs_pattern_evolution.png" title: "HIXS Evolution" categories: ["dark", "hexagon", "hixs"] image_dimensions: "35x34" , image_size: "2K" link: "http://subtlepatterns.com/subtle-dark-vertical/" description: "Classic vertical lines, in all it’s subtlety." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dvsup.png" author: "<a href=\"http://tirl.tk/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dvsup.zip" image: "http://subtlepatterns.com/patterns/dvsup.png" title: "Subtle Dark Vertical" categories: ["dark", "lines", "vertical"] image_dimensions: "40x40" , image_size: "225B" link: "http://subtlepatterns.com/grid-me/" description: "Nice little grid. Would work great as a base on top of some other patterns." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gridme.png" author: "<a href=\"http://www.gobigbang.nl\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gridme.zip" image: "http://subtlepatterns.com/patterns/gridme.png" title: "Grid Me" categories: ["grid", "light"] image_dimensions: "50x50" , image_size: "2K" link: "http://subtlepatterns.com/knitted-netting/" description: "A bit like some carbon, or knitted netting if you will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/knitted-netting.png" author: "<a href=\"http://graphicriver.net/user/Naf_Naf?ref=Naf_Naf\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/knitted-netting.zip" image: "http://subtlepatterns.com/patterns/knitted-netting.png" title: "Knitted Netting" categories: ["carbon", "light", "netting"] image_dimensions: "8x8" , image_size: "166B" link: "http://subtlepatterns.com/dark-matter/" description: "The name is totally random, but hey, it sounds good?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_matter.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_matter.zip" image: "http://subtlepatterns.com/patterns/dark_matter.png" title: "Dark matter" categories: ["dark", "noise", "pixles"] image_dimensions: "7x7" , image_size: "783B" link: "http://subtlepatterns.com/black-thread/" description: "Geometric lines are always hot, and this pattern is no exception." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_thread.png" author: "<a href=\"http://listvetra.ru/\" target=\"_blank\">ListPI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_thread.zip" image: "http://subtlepatterns.com/patterns/black_thread.png" title: "Black Thread" categories: ["dark", "geometry"] image_dimensions: "49x28" , image_size: "173K" link: "http://subtlepatterns.com/vertical-cloth/" description: "You just can’t get enough of the fabric patterns, so here is one more for your collection." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/vertical_cloth.png" author: "<a href=\"http://dribbble.com/krisp\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/vertical_cloth.zip" image: "http://subtlepatterns.com/patterns/vertical_cloth.png" title: "Vertical cloth" categories: ["cloth", "dark", "fabric", "lines"] image_dimensions: "399x400" , image_size: "22K" link: "http://subtlepatterns.com/934/" description: "This is the third pattern called Dark Denim, but hey, we all love them!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/darkdenim3.png" author: "<a href=\"http://www.brandonjacoby.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/darkdenim3.zip" image: "http://subtlepatterns.com/patterns/darkdenim3.png" title: "Dark Denim 3" categories: ["dark", "denim"] image_dimensions: "420x326" , image_size: "255B" link: "http://subtlepatterns.com/white-brick-wall/" description: "If you’re sick of the fancy 3d, grunge and noisy patterns, take a look at this flat 2d brick wall." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_brick_wall.png" author: "<a href=\"http://listvetra.ru/\" target=\"_blank\">Listvetra</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_brick_wall.zip" image: "http://subtlepatterns.com/patterns/white_brick_wall.png" title: "White Brick Wall" categories: ["brick", "light", "wall"] image_dimensions: "24x16" , image_size: "5K" link: "http://subtlepatterns.com/fabric-plaid/" description: "You know you can’t get enough of these linen-fabric-y patterns." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fabric_plaid.png" author: "<a href=\"http://twitter.com/jbasoo\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fabric_plaid.zip" image: "http://subtlepatterns.com/patterns/fabric_plaid.png" title: "Fabric (Plaid)" categories: ["fabric", "light", "plaid"] image_dimensions: "200x200" , image_size: "146B" link: "http://subtlepatterns.com/merely-cubed/" description: "Tiny, tiny 3D cubes. Reminds me of the good old pattern from k10k." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/merely_cubed.png" author: "<a href=\"http://www.etiennerallion.fr\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/merely_cubed.zip" image: "http://subtlepatterns.com/patterns/merely_cubed.png" title: "Merely Cubed" categories: ["3d", "light"] image_dimensions: "16x16" , image_size: "54K" link: "http://subtlepatterns.com/iron-grip/" description: "Sounds like something from World of Warcraft. Has to be good." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/irongrip.png" author: "<a href=\"http://www.tonykinard.net\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/irongrip.zip" image: "http://subtlepatterns.com/patterns/irongrip.png" title: "Iron Grip" categories: ["dark", "grip", "iron"] image_dimensions: "300x301" , image_size: "847B" link: "http://subtlepatterns.com/starring/" description: "If you need stars, this is the one to get." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/starring.png" author: "<a href=\"http://logosmile.net/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/starring.zip" image: "http://subtlepatterns.com/patterns/starring.png" title: "Starring" categories: ["dark", "star", "stars"] image_dimensions: "35x39" , image_size: "1K" link: "http://subtlepatterns.com/pineapple-cut/" description: "I love the movie Pineapple Express, and I’m also liking this Pineapple right here." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pineapplecut.png" author: "<a href=\"http://audeemirza.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pineapplecut.zip" image: "http://subtlepatterns.com/patterns/pineapplecut.png" title: "Pineapple Cut" categories: ["light"] image_dimensions: "36x62" , image_size: "13K" link: "http://subtlepatterns.com/grilled-noise/" description: "You could get a bit dizzy from this one, but it might come in handy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grilled.png" author: "<a href=\"http://30.nl\" target=\"_blank\">DPI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grilled.zip" image: "http://subtlepatterns.com/patterns/grilled.png" title: "Grilled noise" categories: ["dizzy", "light"] image_dimensions: "170x180" , image_size: "2K" link: "http://subtlepatterns.com/foggy-birds/" description: "Hey, you never know when you’ll need a bird-pattern, right?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/foggy_birds.png" author: "<a href=\"http://buttonpresser.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/foggy_birds.zip" image: "http://subtlepatterns.com/patterns/foggy_birds.png" title: "Foggy Birds" categories: ["bird", "light"] image_dimensions: "206x206" , image_size: "39K" link: "http://subtlepatterns.com/groovepaper/" description: "With a name like this, it has to be hot. Diagonal lines in light shades." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/groovepaper.png" author: "<a href=\"http://graphicriver.net/user/krispdesigns\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/groovepaper.zip" image: "http://subtlepatterns.com/patterns/groovepaper.png" title: "Groovepaper" categories: ["diagonal", "light"] image_dimensions: "300x300" , image_size: "277B" link: "http://subtlepatterns.com/nami/" description: "Not sure if this is related to the Nami you get in Google image search, but hey, it’s nice!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/nami.png" author: "<a href=\"http://30.nl\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/nami.zip" image: "http://subtlepatterns.com/patterns/nami.png" title: "PI:NAME:<NAME>END_PI" categories: ["anime", "asian", "dark"] image_dimensions: "16x16" , image_size: "154B" link: "http://subtlepatterns.com/medic-packaging-foil/" description: "8 by 8 pixels, and just what the title says." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/foil.png" author: "<a href=\"http://be.net/pixilated\" target=\"_blank\">pixilated</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/foil.zip" image: "http://subtlepatterns.com/patterns/foil.png" title: "Medic Packaging Foil" categories: ["foil", "light", "medic", "paper"] image_dimensions: "8x8" , image_size: "30K" link: "http://subtlepatterns.com/white-paperboard/" description: "Could be paper, could be a polaroid frame – up to you!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_paperboard.png" author: "Chaos" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_paperboard.zip" image: "http://subtlepatterns.com/patterns/white_paperboard.png" title: "White Paperboard" categories: ["light", "paper", "paperboard", "polaroid"] image_dimensions: "256x252" , image_size: "20K" link: "http://subtlepatterns.com/dark-denim-2/" description: "Thin lines, noise and texture creates this crisp dark denim pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/denim.png" author: "<a href=\"http://slootenweb.nl\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/denim.zip" image: "http://subtlepatterns.com/patterns/denim.png" title: "Dark Denim" categories: ["dark", "denim"] image_dimensions: "135x135" , image_size: "101K" link: "http://subtlepatterns.com/wood-pattern/" description: "One of the few “full color” patterns here, but this one was just too good to pass up." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wood_pattern.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wood_pattern.zip" image: "http://subtlepatterns.com/patterns/wood_pattern.png" title: "Wood pattern" categories: ["light", "wood"] image_dimensions: "203x317" , image_size: "28K" link: "http://subtlepatterns.com/white-plaster/" description: "Sweet and subtle white plaster with hints of noise and grunge." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_plaster.png" author: "<a href=\"http://aurer.co.uk\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_plaster.zip" image: "http://subtlepatterns.com/patterns/white_plaster.png" title: "White plaster" categories: ["light"] image_dimensions: "300x300" , image_size: "9K" link: "http://subtlepatterns.com/white-diamond/" description: "To celebrate the new feature, we need some sparkling diamonds." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/whitediamond.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/whitediamond.zip" image: "http://subtlepatterns.com/patterns/whitediamond.png" title: "White Diamond" categories: ["diamond", "light", "triangle"] image_dimensions: "128x224" , image_size: "81K" link: "http://subtlepatterns.com/broken-noise/" description: "Beautiful dark noise pattern with some dust and grunge." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/broken_noise.png" author: "<a href=\"http://vincentklaiber.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/broken_noise.zip" image: "http://subtlepatterns.com/patterns/broken_noise.png" title: "Broken noise" categories: ["broken", "dark", "grunge", "noise"] image_dimensions: "476x476" , image_size: "153B" link: "http://subtlepatterns.com/gun-metal/" description: "With a name this awesome, how can I go wrong?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gun_metal.png" author: "<a href=\"http://www.zigzain.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gun_metal.zip" image: "http://subtlepatterns.com/patterns/gun_metal.png" title: "Gun metal" categories: ["dark", "gun", "metal"] image_dimensions: "10x10" , image_size: "221B" link: "http://subtlepatterns.com/fake-brick/" description: "Black, simple, elegant & useful." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fake_brick.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fake_brick.zip" image: "http://subtlepatterns.com/patterns/fake_brick.png" title: "Fake brick" categories: ["dark", "dots"] image_dimensions: "76x76" , image_size: "295B" link: "http://subtlepatterns.com/candyhole/" description: "It’s a hole, in a pattern. On your website. Dig it!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/candyhole.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/candyhole.zip" image: "http://subtlepatterns.com/patterns/candyhole.png" title: "Candyhole" categories: ["hole", "light"] image_dimensions: "25x25" , image_size: "50K" link: "http://subtlepatterns.com/ravenna/" description: "I guess this is inspired by the city of Ravenna in Italy and it’s stone walls." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ravenna.png" author: "<a href=\"http://sentel.co\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ravenna.zip" image: "http://subtlepatterns.com/patterns/ravenna.png" title: "Ravenna" categories: ["light", "stone", "stones", "wall"] image_dimensions: "387x201" , image_size: "235B" link: "http://subtlepatterns.com/small-crackle-bright/" description: "Light gray pattern with an almost wall tile-like appearance." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/small-crackle-bright.png" author: "<a href=\"http://www.markustinner.ch\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/small-crackle-bright.zip" image: "http://subtlepatterns.com/patterns/small-crackle-bright.png" title: "Small crackle bright" categories: ["light"] image_dimensions: "14x14" , image_size: "29K" link: "http://subtlepatterns.com/nasty-fabric/" description: "Nasty or not, it’s a nice pattern that tiles. Like they all do." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/nasty_fabric.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/nasty_fabric.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/nasty_fabric.png" title: "Nasty Fabric" categories: ["light"] image_dimensions: "198x200" , image_size: "997B" link: "http://subtlepatterns.com/diagonal-waves/" description: "It has waves, so make sure you don’t get sea sickness." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagonal_waves.png" author: "<a href=\"http://coolpatterns.net\" target=\"_blank\">CoolPatterns.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonal_waves.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonal_waves.png" title: "Diagonal Waves" categories: ["light"] image_dimensions: "38x38" , image_size: "10K" link: "http://subtlepatterns.com/otis-redding/" description: "PI:NAME:<NAME>END_PI was an American soul singer-songwriter, record producer, arranger, and talent scout. So you know." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/otis_redding.png" author: "<a href=\"http://thomasmyrman.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/otis_redding.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/otis_redding.png" title: "Otis Redding" categories: ["light"] image_dimensions: "100x100" , image_size: "10K" link: "http://subtlepatterns.com/billie-holiday/" description: "No relation to the band, but damn it’s subtle!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/billie_holiday.png" author: "<a href=\"http://thomasmyrman.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/billie_holiday.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/billie_holiday.png" title: "Billie Holiday" categories: ["light"] image_dimensions: "100x100" , image_size: "196B" link: "http://subtlepatterns.com/az-subtle/" description: "The A – Z of Subtle? Up to you." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/az_subtle.png" author: "<a href=\"http://www.azmind.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/az_subtle.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/az_subtle.png" title: "AZ Subtle" categories: ["light"] image_dimensions: "100x100" , image_size: "21K" link: "http://subtlepatterns.com/wild-oliva/" description: "Wild Oliva or Oliva Wilde? Darker than the others, sort of a medium dark pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wild_oliva.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wild_oliva.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wild_oliva.png" title: "Wild Oliva" categories: ["dark"] image_dimensions: "198x200" , image_size: "16K" link: "http://subtlepatterns.com/stressed-linen/" description: "We have some linen patterns here, but none that are stressed. Until now." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/stressed_linen.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stressed_linen.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stressed_linen.png" title: "Stressed Linen" categories: ["dark"] image_dimensions: "256x256" , image_size: "116K" link: "http://subtlepatterns.com/navy/" description: "It was called Navy Blue, but I made it dark. You know, the way I like it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/navy_blue.png" author: "<a href=\"http://ultranotch.com/\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/navy_blue.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/navy_blue.png" title: "Navy" categories: ["dark"] image_dimensions: "600x385" , image_size: "106B" link: "http://subtlepatterns.com/simple-horizontal-light/" description: "Some times you just need the simplest thing." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/shl.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shl.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shl.png" title: "Simple Horizontal Light" categories: ["light"] image_dimensions: "4x4" , image_size: "661B" link: "http://subtlepatterns.com/cream_dust/" description: "I love cream! 50x50px and lovely in all the good ways." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cream_dust.png" author: "<a href=\"http://thomasmyrman.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cream_dust.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cream_dust.png" title: "Cream Dust" categories: ["light"] image_dimensions: "50x50" , link: "http://subtlepatterns.com/slash-it/" description: "I have no idea what this is, but it’s tiny and it tiles. Whey!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/slash_it.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\">Venam</a>" download: "/patterns/slash_it.zip" image: "/patterns/slash_it.png" title: "Slash it" categories: ["dark"] , link: "http://subtlepatterns.com/simple-dashed/" description: "Tiny lines going both ways – not the way you think, silly." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/simple_dashed.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "/patterns/simple_dashed.zip" image: "/patterns/simple_dashed.png" title: "Simple Dashed" categories: ["dark"] , link: "http://subtlepatterns.com/moulin/" description: "No relation to Moulin Rouge, but still sexy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/moulin.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "/patterns/moulin.zip" image: "/patterns/moulin.png" title: "Moulin" categories: ["dark"] , link: "http://subtlepatterns.com/dark-exa/" description: "Looks a bit like little bugs, but they are harmless." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_exa.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "/patterns/dark_exa.zip" image: "/patterns/dark_exa.png" title: "Dark Exa" categories: ["dark"] , link: "http://subtlepatterns.com/dark-dotted-2/" description: "Dark dots never go out of fashion, do they? Nope." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_dotted2.png" author: "<a href=\"http://venam.1.ai\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "/patterns/dark_dotted2.zip" image: "/patterns/dark_dotted2.png" title: "Dark Dotted 2" categories: ["dark", "dots"] , image_size: "191B" link: "http://subtlepatterns.com/graphy/" description: "Looks like a technical drawing board, small squares forming a nice grid." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/graphy.png" author: "<a href=\"http://www.wearepixel8.com\" target=\"_blank\">We Are Pixel8</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/graphy.zip" image: "http://subtlepatterns.com/patterns/graphy.png" title: "Graphy" categories: ["grid", "light", "maths"] image_dimensions: "80x160" , image_size: "861B" link: "http://subtlepatterns.com/connected/" description: "White circles connecting on a light gray background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/connect.png" author: "<a href=\"http://pixxel.co/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/connect.zip" image: "http://subtlepatterns.com/patterns/connect.png" title: "Connected" categories: ["connection", "dots", "light"] image_dimensions: "160x160" , image_size: "36K" link: "http://subtlepatterns.com/old-wall/" description: "Old concrete wall in light shades." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/old_wall.png" author: "<a href=\"http://twitter.com/simek\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/old_wall.zip" image: "http://subtlepatterns.com/patterns/old_wall.png" title: "Old wall" categories: ["concrete", "light", "sement", "wall"] image_dimensions: "300x300" , image_size: "1K" link: "http://subtlepatterns.com/light-grey-floral-motif/" description: "Lovely light gray floral motif with some subtle shades." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_grey_floral_motif.png" author: "<a href=\"http://www.graphicswall.com/\" target=\"_blank\">GraphicsWall</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_grey_floral_motif.zip" image: "http://subtlepatterns.com/patterns/light_grey_floral_motif.png" title: "Light Grey Floral Motif" categories: ["floral", "gray", "light"] image_dimensions: "32x56" , image_size: "3K" link: "http://subtlepatterns.com/3px-tile/" description: "Tiny dark square tiles with varied color tones." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/px_by_Gre3g.png" author: "<a href=\"http://gre3g.livejournal.com\" target=\"_blank\">GPI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/px_by_Gre3g.zip" image: "http://subtlepatterns.com/patterns/px_by_Gre3g.png" title: "3px tile" categories: ["dark", "square", "tile"] image_dimensions: "100x100" , image_size: "276K" link: "http://subtlepatterns.com/rice-paper-2/" description: "One can never have too few rice paper patterns, so here is one more." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ricepaper2.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ricepaper2.zip" image: "http://subtlepatterns.com/patterns/ricepaper2.png" title: "Rice paper 2" categories: ["light", "paper", "rice"] image_dimensions: "485x485" , image_size: "130K" link: "http://subtlepatterns.com/rice-paper/" description: "Scanned some rice paper and tiled it up for you. Enjoy." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/ricepaper.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/ricepaper.zip" image: "http://subtlepatterns.com/patterns/ricepaper.png" title: "Rice paper" categories: ["light", "paper", "rice"] image_dimensions: "500x500" , image_size: "1K" link: "http://subtlepatterns.com/diagmonds/" description: "Love the style on this one, very fresh. Diagonal diamond pattern. Get it?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagmonds.png" author: "<a href=\"http://www.flickr.com/photos/ins\" target=\"_blank\">INS</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagmonds.zip" image: "http://subtlepatterns.com/patterns/diagmonds.png" title: "Diagmonds" categories: ["dark", "diamond"] image_dimensions: "141x142" , image_size: "46K" link: "http://subtlepatterns.com/polonez-pattern-2/" description: "Wtf, a car pattern?! Can it be subtle? I say yes!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/polonez_car.png" author: "<a href=\"http://designcocktails.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/polonez_car.zip" image: "http://subtlepatterns.com/patterns/polonez_car.png" title: "Polonez Pattern" categories: ["car", "light"] image_dimensions: "300x300" , image_size: "1K" link: "http://subtlepatterns.com/polonez-pattern/" description: "Repeating squares overlapping." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/plaid.png" author: "<a href=\"http://buttonpresser.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/plaid.zip" image: "http://subtlepatterns.com/patterns/plaid.png" title: "My Little Plaid" categories: ["geometry", "light"] image_dimensions: "54x54" , image_size: "430B" link: "http://subtlepatterns.com/axiom-pattern/" description: "Not even 1kb, but very stylish. Gray thin lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/struckaxiom.png" author: "<a href=\"http://www.struckaxiom.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/struckaxiom.zip" image: "http://subtlepatterns.com/patterns/struckaxiom.png" title: "Axiom Pattern" categories: ["diagonal", "light", "stripes"] image_dimensions: "81x81" , image_size: "149B" link: "http://subtlepatterns.com/zig-zag/" description: "So tiny, just 7 by 7 pixels – but still so sexy. Ah yes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/zigzag.png" author: "<a href=\"http://www.behance.net/dmpr0\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/zigzag.zip" image: "http://subtlepatterns.com/patterns/zigzag.png" title: "Zig Zag" categories: ["dark", "embossed"] image_dimensions: "10x10" , image_size: "1K" link: "http://subtlepatterns.com/carbon-fibre-big/" description: "Bigger is better, right? So here you have some large Carbon fibre." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/carbon_fibre_big.png" author: "<a href=\"http://factorio.us/\" target=\"_blank\">Factorio.us Collective</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/carbon_fibre_big.zip" image: "http://subtlepatterns.com/patterns/carbon_fibre_big.png" title: "Carbon Fibre Big" categories: ["dark"] image_dimensions: "20x22" , image_size: "1K" link: "http://subtlepatterns.com/batthern/" description: "Some times simple really is what you need, and this could fit you well." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/batthern.png" author: "<a href=\"http://factorio.us/\" target=\"_blank\">Factorio.us Collective</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/batthern.zip" image: "http://subtlepatterns.com/patterns/batthern.png" title: "Batthern" categories: ["light"] image_dimensions: "100x99" , image_size: "406B" link: "http://subtlepatterns.com/checkered-pattern/" description: "Simple gray checkered lines, in light tones." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/checkered_pattern.png" author: "<a href=\"http://designcocktails.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/checkered_pattern.zip" image: "http://subtlepatterns.com/patterns/checkered_pattern.png" title: "Checkered Pattern" categories: ["light", "lines"] image_dimensions: "72x72" , image_size: "131K" link: "http://subtlepatterns.com/dark-wood/" description: "A beautiful dark wood pattern, superbly tiled." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_wood.png" author: "<a href=\"http://www.oaadesigns.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_wood.zip" image: "http://subtlepatterns.com/patterns/dark_wood.png" title: "Dark wood" categories: ["dark"] image_dimensions: "512x512" , image_size: "741B" link: "http://subtlepatterns.com/soft-kill/" description: "Pattern #100! A black classic knit-looking pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/soft_kill.png" author: "<a href=\"http://www.factorio.us\" target=\"_blank\">Factorio.us Collective</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/soft_kill.zip" image: "http://subtlepatterns.com/patterns/soft_kill.png" title: "Soft kill" categories: ["dark"] image_dimensions: "28x48" , image_size: "401B" link: "http://subtlepatterns.com/elegant-grid/" description: "This is a hot one. Small, sharp and unique." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/elegant_grid.png" author: "<a href=\"http://www.graphicswall.com\" target=\"_blank\">GraphicsWall</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/elegant_grid.zip" image: "http://subtlepatterns.com/patterns/elegant_grid.png" title: "Elegant Grid" categories: ["light"] image_dimensions: "16x28" , image_size: "36K" link: "http://subtlepatterns.com/xv/" description: "Floral patterns will never go out of style, so enjoy this one." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/xv.png" author: "<a href=\"http://www.oddfur.com\" target=\"_blank\">Lasma</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/xv.zip" image: "http://subtlepatterns.com/patterns/xv.png" title: "Xv" categories: ["light"] image_dimensions: "294x235" , image_size: "66K" link: "http://subtlepatterns.com/rough-cloth/" description: "More tactile goodness. This time in the form of some rough cloth." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/roughcloth.png" author: "<a href=\"http://twitter.com/simek\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/roughcloth.zip" image: "http://subtlepatterns.com/patterns/roughcloth.png" title: "Rough Cloth" categories: ["light"] image_dimensions: "320x320" , image_size: "228B" link: "http://subtlepatterns.com/little-knobs/" description: "White little knobs, coming in at 10x10px. Sweet!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/littleknobs.png" author: "<a href=\"http://www.freepx.net\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/littleknobs.zip" image: "http://subtlepatterns.com/patterns/littleknobs.png" title: "Little knobs" categories: ["light"] image_dimensions: "10x10" , image_size: "5K" link: "http://subtlepatterns.com/dotnoise-light-grey/" description: "Sort of like the back of a wooden board. Light, subtle and stylish just the way we like it!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/bgnoise_lg.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bgnoise_lg.zip" image: "http://subtlepatterns.com/patterns/bgnoise_lg.png" title: "Dotnoise light grey" categories: ["light"] image_dimensions: "100x100" , image_size: "207B" link: "http://subtlepatterns.com/dark-circles/" description: "People seem to enjoy dark patterns, so here is one with some circles." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_circles.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_circles.zip" image: "http://subtlepatterns.com/patterns/dark_circles.png" title: "Dark circles" categories: ["dark"] image_dimensions: "10x12" , image_size: "42K" link: "http://subtlepatterns.com/light-aluminum/" description: "Used correctly, this could be nice. Used in a bad way, all Hell will break loose." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_alu.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_alu.zip" image: "http://subtlepatterns.com/patterns/light_alu.png" title: "Light aluminum" categories: ["light"] image_dimensions: "282x282" , image_size: "552B" link: "http://subtlepatterns.com/squares/" description: "Dark, square, clean and tidy. What more can you ask for?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/squares.png" author: "<a href=\"http://www.toshtak.com/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/squares.zip" image: "http://subtlepatterns.com/patterns/squares.png" title: "Squares" categories: ["dark"] image_dimensions: "32x32" , image_size: "129K" link: "http://subtlepatterns.com/felt/" description: "Got some felt in my mailbox today, so I scanned it for you to use." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/felt.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/felt.zip" image: "http://subtlepatterns.com/patterns/felt.png" title: "Felt" categories: ["light"] image_dimensions: "500x466" , image_size: "2K" link: "http://subtlepatterns.com/transparent-square-tiles/" description: "The first pattern on here using opacity. Try it on a site with a colored background, or even using mixed colors." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/square_bg.png" author: "<a href=\"http://nspady.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/square_bg.zip" image: "http://subtlepatterns.com/patterns/square_bg.png" title: "Transparent Square Tiles" categories: ["light"] image_dimensions: "252x230" , image_size: "418B" link: "http://subtlepatterns.com/paven/" description: "A subtle shadowed checkered pattern. Increase the lightness for even more subtle sexyness." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paven.png" author: "<a href=\"http://emailcoder.net\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paven.zip" image: "http://subtlepatterns.com/patterns/paven.png" title: "Paven" categories: ["light"] image_dimensions: "20x20" , image_size: "34K" link: "http://subtlepatterns.com/stucco/" description: "A nice and simple gray stucco material. Great on it’s own, or as a base for a new pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/stucco.png" author: "<a href=\"http://twitter.com/#!/simek\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stucco.zip" image: "http://subtlepatterns.com/patterns/stucco.png" title: "Stucco" categories: ["light"] image_dimensions: "250x249" , image_size: "21K" link: "http://subtlepatterns.com/r-i-p-steve-jobs/" description: "He influenced us all. “Don’t be sad because it’s over. Smile because it happened.” - Dr. Seuss" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rip_jobs.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rip_jobs.zip" image: "http://subtlepatterns.com/patterns/rip_jobs.png" title: "R.I.P Steve Jobs" categories: ["light"] image_dimensions: "200x200" , image_size: "1K" link: "http://subtlepatterns.com/woven/" description: "Can’t believe we don’t have this in the collection already! Slick woven pattern with crisp details." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/woven.png" author: "<a href=\"http://www.maxthemes.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/woven.zip" image: "http://subtlepatterns.com/patterns/woven.png" title: "Woven" categories: ["dark"] image_dimensions: "42x42" , image_size: "5K" link: "http://subtlepatterns.com/washi/" description: "Washi (和紙?) is a type of paper made in Japan. Here’s the pattern for you!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/washi.png" author: "<a href=\"http://www.sweetstudio.co.uk\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/washi.zip" image: "http://subtlepatterns.com/patterns/washi.png" title: "Washi" categories: ["light"] image_dimensions: "100x100" , image_size: "418B" link: "http://subtlepatterns.com/real-carbon-fibre/" description: "Carbon fibre is never out of fashion, so here is one more style for you." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/real_cf.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/real_cf.zip" image: "http://subtlepatterns.com/patterns/real_cf.png" title: "Real Carbon Fibre" categories: ["dark"] image_dimensions: "56x56" , image_size: "1K" link: "http://subtlepatterns.com/gold-scale/" description: "More Japanese-inspired patterns, Gold Scales this time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gold_scale.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gold_scale.zip" image: "http://subtlepatterns.com/patterns/gold_scale.png" title: "Gold Scale" categories: ["light"] image_dimensions: "25x25" , image_size: "1K" link: "http://subtlepatterns.com/elastoplast/" description: "A fun looking elastoplast/band-aid pattern. A hint of orange tone in this one." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/elastoplast.png" author: "<a href=\"http://joshgreendesign.com/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/elastoplast.zip" image: "http://subtlepatterns.com/patterns/elastoplast.png" title: "Elastoplast" categories: ["light"] image_dimensions: "37x37" , image_size: "1K" link: "http://subtlepatterns.com/checkered-light-emboss/" description: "Sort of like the Photoshop transparent background, but better!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_checkered_tiles.png" author: "<a href=\"http://twitter.com/misterparker\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_checkered_tiles.zip" image: "http://subtlepatterns.com/patterns/light_checkered_tiles.png" title: "Checkered light emboss" categories: ["light"] image_dimensions: "60x60" , image_size: "200K" link: "http://subtlepatterns.com/cardboard/" description: "A good starting point for a cardboard pattern. This would work well in a variety of colors." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cardboard.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cardboard.zip" image: "http://subtlepatterns.com/patterns/cardboard.png" title: "Cardboard" categories: ["light"] image_dimensions: "600x600" , image_size: "15K" link: "http://subtlepatterns.com/type/" description: "The perfect pattern for all your blogs about type, or type related matters." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/type.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/type.zip" image: "http://subtlepatterns.com/patterns/type.png" title: "Type" categories: ["dark"] image_dimensions: "200x200" , image_size: "278B" link: "http://subtlepatterns.com/mbossed/" description: "Embossed lines and squares with subtle highlights." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/small_tiles.png" author: "<a href=\"http://twitter.com/misterparker\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/small_tiles.zip" image: "http://subtlepatterns.com/patterns/small_tiles.png" title: "MBossed" categories: ["light"] image_dimensions: "26x26" , image_size: "279B" link: "http://subtlepatterns.com/black-scales/" description: "Same as Silver Scales, but in black – turn your site in to a dragon with this great scale pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_scales.png" author: "<a href=\"http://twitter.com/misterparker\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_scales.zip" image: "http://subtlepatterns.com/patterns/black_scales.png" title: "Black Scales" categories: ["dark"] image_dimensions: "40x40" , image_size: "289B" link: "http://subtlepatterns.com/silver-scales/" description: "Turn your site in to a dragon with this great scale pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/silver_scales.png" author: "<a href=\"http://twitter.com/misterparker\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/silver_scales.zip" image: "http://subtlepatterns.com/patterns/silver_scales.png" title: "Silver Scales" categories: ["light"] image_dimensions: "40x40" , image_size: "5K" link: "http://subtlepatterns.com/polaroid/" description: "Smooth Polaroid pattern with a light blue tint." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/polaroid.png" author: "<a href=\"http://danielbeaton.tumblr.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/polaroid.zip" image: "http://subtlepatterns.com/patterns/polaroid.png" title: "Polaroid" categories: ["light"] image_dimensions: "58x36" , image_size: "247B" link: "http://subtlepatterns.com/circles/" description: "One more sharp little tile for you. Subtle circles this time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/circles.png" author: "<a href=\"http://www.blunia.com/\" target=\"_blank\">Blunia</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/circles.zip" image: "http://subtlepatterns.com/patterns/circles.png" title: "Circles" categories: ["light"] image_dimensions: "16x12" , image_size: "2K" link: "http://subtlepatterns.com/diamonds-are-forever/" description: "Sharp diamond pattern. A small 24x18px tile." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diamonds.png" author: "<a href=\"http://imaketees.co.uk\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diamonds.zip" image: "http://subtlepatterns.com/patterns/diamonds.png" title: "Diamonds Are Forever" categories: ["light"] image_dimensions: "24x18" , image_size: "8K" link: "http://subtlepatterns.com/diagonal-noise/" description: "A simple but elegant classic. Every collection needs one of these." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diagonal-noise.png" author: "<a href=\"http://ChristopherBurton.net\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diagonal-noise.zip" image: "http://subtlepatterns.com/patterns/diagonal-noise.png" title: "Diagonal Noise" categories: ["light"] image_dimensions: "100x100" , image_size: "30K" link: "http://subtlepatterns.com/noise-pattern-with-subtle-cross-lines/" description: "More bright luxury. This is a bit larger than fancy deboss, and with a bit more noise." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noise_pattern_with_crosslines.png" author: "<a href=\"http://visztpeter.me\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noise_pattern_with_crosslines.zip" image: "http://subtlepatterns.com/patterns/noise_pattern_with_crosslines.png" title: "Noise pattern with subtle cross lines" categories: [] image_dimensions: "240x240" , image_size: "265B" link: "http://subtlepatterns.com/fancy-deboss/" description: "Luxury pattern, looking like it came right out of Paris." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fancy_deboss.png" author: "<a href=\"http://danielbeaton.tumblr.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fancy_deboss.zip" image: "http://subtlepatterns.com/patterns/fancy_deboss.png" title: "Fancy Deboss" categories: ["light"] image_dimensions: "18x13" , image_size: "40K" link: "http://subtlepatterns.com/pool-table/" description: "This makes me wanna shoot some pool! Sweet green pool table pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pool_table.png" author: "<a href=\"http://caveman.chlova.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pool_table.zip" image: "http://subtlepatterns.com/patterns/pool_table.png" title: "Pool Table" categories: ["color", "dark"] image_dimensions: "256x256" , image_size: "5K" link: "http://subtlepatterns.com/dark-brick-wall/" description: "Black brick wall pattern. Brick your site up!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_brick_wall.png" author: "<a href=\"http://alexparker.me\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_brick_wall.zip" image: "http://subtlepatterns.com/patterns/dark_brick_wall.png" title: "Dark Brick Wall" categories: ["dark"] image_dimensions: "96x96" , image_size: "723B" link: "http://subtlepatterns.com/cubes/" description: "This reminds me of Game Cube. A nice light 3D cube pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cubes.png" author: "<a href=\"http://www.experimint.nl\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cubes.zip" image: "http://subtlepatterns.com/patterns/cubes.png" title: "Cubes" categories: ["light"] image_dimensions: "67x100" , image_size: "5K" link: "http://subtlepatterns.com/white-texture/" description: "Not the most creative name, but it’s a good all-purpose light background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_texture.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_texture.zip" image: "http://subtlepatterns.com/patterns/white_texture.png" title: "White Texture" categories: ["light"] image_dimensions: "102x102" , image_size: "72K" link: "http://subtlepatterns.com/black-leather/" description: "You were craving for more leather, so I whipped this up by scanning a leather jacket." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_leather.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_leather.zip" image: "http://subtlepatterns.com/patterns/dark_leather.png" title: "Dark leather" categories: ["dark"] image_dimensions: "398x484" , image_size: "5K" link: "http://subtlepatterns.com/robots/" description: "And some more testing, this time with Seamless Studio . It’s Robots FFS!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/robots.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/robots.zip" image: "http://subtlepatterns.com/patterns/robots.png" title: "Robots" categories: ["dark"] image_dimensions: "200x200" , image_size: "5K" link: "http://subtlepatterns.com/mirrored-squares/" description: "Did some testing with Repper Pro tonight, and this gray mid-tone pattern came out." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/mirrored_squares.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/mirrored_squares.zip" image: "http://subtlepatterns.com/patterns/mirrored_squares.png" title: "Mirrored Squares" categories: ["dark"] image_dimensions: "166x166" , image_size: "10K" link: "http://subtlepatterns.com/dark-mosaic/" description: "Small dots with minor circles spread across to form a nice mosaic." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_mosaic.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_mosaic.zip" image: "http://subtlepatterns.com/patterns/dark_mosaic.png" title: "Dark Mosaic" categories: ["dark"] image_dimensions: "300x295" , image_size: "224B" link: "http://subtlepatterns.com/project-papper/" description: "Light square grid pattern, great for a “DIY projects” sort of website, maybe?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/project_papper.png" author: "<a href=\"http://www.fotografiaetc.com.br/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/project_papper.zip" image: "http://subtlepatterns.com/patterns/project_papper.png" title: "Project Papper" categories: ["light"] image_dimensions: "105x105" , image_size: "31K" link: "http://subtlepatterns.com/inflicted/" description: "Dark squares with some virus-looking dots in the grid." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/inflicted.png" author: "<a href=\"http://www.inflicted.nl\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/inflicted.zip" image: "http://subtlepatterns.com/patterns/inflicted.png" title: "Inflicted" categories: ["dark"] image_dimensions: "240x240" , image_size: "116B" link: "http://subtlepatterns.com/small-crosses/" description: "Sharp pixel pattern looking like some sort of fabric." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/crosses.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/crosses.zip" image: "http://subtlepatterns.com/patterns/crosses.png" title: "Small Crosses" categories: ["light"] image_dimensions: "10x10" , image_size: "9K" link: "http://subtlepatterns.com/soft-circle-scales/" description: "Japanese looking fish scale pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/soft_circle_scales.png" author: "<a href=\"http://iansoper.com\" title=\"PI:NAME:<NAME>END_PI\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/soft_circle_scales.zip" image: "http://subtlepatterns.com/patterns/soft_circle_scales.png" title: "Soft Circle Scales" categories: ["light"] image_dimensions: "256x56" , image_size: "60K" link: "http://subtlepatterns.com/crissxcross/" description: "Dark pattern with some nice diagonal stitched lines crossing over." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/crissXcross.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/crissXcross.zip" image: "http://subtlepatterns.com/patterns/crissXcross.png" title: "crissXcross" categories: ["dark"] image_dimensions: "512x512" , image_size: "85K" link: "http://subtlepatterns.com/whitey/" description: "A white version of the very popular linen pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/whitey.png" author: "<a href=\"http://www.turkhitbox.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/whitey.zip" image: "http://subtlepatterns.com/patterns/whitey.png" title: "Whitey" categories: ["light"] image_dimensions: "654x654" , image_size: "42K" link: "http://subtlepatterns.com/green-dust-scratches/" description: "Snap! It’s a pattern, and it’s not grayscale! Of course you can always change the color in Photoshop." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/green_dust_scratch.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/green_dust_scratch.zip" image: "http://subtlepatterns.com/patterns/green_dust_scratch.png" title: "Green Dust & Scratches" categories: ["light"] image_dimensions: "296x300" , image_size: "635B" link: "http://subtlepatterns.com/carbon-fibre-v2/" description: "One more updated pattern. Not really carbon fibre, but it’s the most popular pattern, so I’ll give you an extra choice." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/carbon_fibre_v2.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/carbon_fibre_v2.zip" image: "http://subtlepatterns.com/patterns/carbon_fibre_v2.png" title: "Carbon fibre v2" categories: ["dark"] image_dimensions: "32x36" , image_size: "137K" link: "http://subtlepatterns.com/black-linen-2/" description: "A new take on the black linen pattern. Softer this time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_linen_v2.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_linen_v2.zip" image: "http://subtlepatterns.com/patterns/black_linen_v2.png" title: "Black linen 2" categories: ["dark"] image_dimensions: "640x640" , image_size: "1004B" link: "http://subtlepatterns.com/darth-stripe/" description: "A very slick dark rubber grip pattern, sort of like the grip on a camera." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rubber_grip.png" author: "<a href=\"http://be.net/pixilated\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rubber_grip.zip" image: "http://subtlepatterns.com/patterns/rubber_grip.png" title: "Rubber grip" categories: ["dark"] image_dimensions: "5x20" , image_size: "218K" link: "http://subtlepatterns.com/darth-stripe-2/" description: "Diagonal lines with a lot of texture to them." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/darth_stripe.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/darth_stripe.zip" image: "http://subtlepatterns.com/patterns/darth_stripe.png" title: "Darth Stripe" categories: ["dark"] image_dimensions: "511x511" , image_size: "71K" link: "http://subtlepatterns.com/subtle-orange-emboss/" description: "A hint or orange color, and some crossed & embossed lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_orange_emboss.png" author: "<a href=\"http://www.depcore.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_orange_emboss.zip" image: "http://subtlepatterns.com/patterns/subtle_orange_emboss.png" title: "Subtle orange emboss" categories: ["light"] image_dimensions: "497x249" , image_size: "225K" link: "http://subtlepatterns.com/soft-wallpaper/" description: "Coming in at 666x666px, this is an evil big pattern, but nice and soft at the same time." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/soft_wallpaper.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/soft_wallpaper.zip" image: "http://subtlepatterns.com/patterns/soft_wallpaper.png" title: "Soft Wallpaper" categories: ["light"] image_dimensions: "666x666" , image_size: "60K" link: "http://subtlepatterns.com/concrete-wall-3/" description: "All good things are 3, so I give you the third in my little concrete wall series." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/concrete_wall_3.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/concrete_wall_3.zip" image: "http://subtlepatterns.com/patterns/concrete_wall_3.png" title: "Concrete wall 3" categories: ["light"] image_dimensions: "400x299" , image_size: "38K" link: "http://subtlepatterns.com/green-fibers/" description: "The Green fibers pattern will work very well in grayscale as well." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/green-fibers.png" author: "<a href=\"http://www.matteodicapua.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/green-fibers.zip" image: "http://subtlepatterns.com/patterns/green-fibers.png" title: "Green Fibers" categories: ["dark"] image_dimensions: "200x200" , image_size: "14K" link: "http://subtlepatterns.com/subtle-freckles/" description: "This shit is so subtle we’re talking 1% opacity. Get your squint on!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_freckles.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_freckles.zip" image: "http://subtlepatterns.com/patterns/subtle_freckles.png" title: "Subtle freckles" categories: ["light"] image_dimensions: "198x198" , image_size: "40K" link: "http://subtlepatterns.com/bright-squares/" description: "It’s Okay to be square! A nice light gray pattern with random squares." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/bright_squares.png" author: "<a href=\"http://twitter.com/dwaseem\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bright_squares.zip" image: "http://subtlepatterns.com/patterns/bright_squares.png" title: "Bright Squares" categories: ["light"] image_dimensions: "297x297" , image_size: "1K" link: "http://subtlepatterns.com/green-gobbler/" description: "Luxurious looking pattern (for a t-shirt maybe?) with a hint of green." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/green_gobbler.png" author: "<a href=\"http://www.simonmeek.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/green_gobbler.zip" image: "http://subtlepatterns.com/patterns/green_gobbler.png" title: "Green gobbler" categories: ["light"] image_dimensions: "39x39" , image_size: "23K" link: "http://subtlepatterns.com/beige-paper/" description: "This was submitted in a beige color, hence the name. Now it’s a gray paper pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/beige_paper.png" author: "<a href=\"http://twitter.com/phenix_h_k\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/beige_paper.zip" image: "http://subtlepatterns.com/patterns/beige_paper.png" title: "Beige paper" categories: ["light"] image_dimensions: "200x200" , image_size: "106K" link: "http://subtlepatterns.com/grunge-wall/" description: "Light gray grunge wall with a nice texture overlay." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grunge_wall.png" author: "<a href=\"http://www.depcore.pl\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grunge_wall.zip" image: "http://subtlepatterns.com/patterns/grunge_wall.png" title: "Grunge wall" categories: ["light"] image_dimensions: "500x375" , image_size: "272K" link: "http://subtlepatterns.com/concrete-wall-2/" description: "A light gray wall or floor (you decide) of concrete." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/concrete_wall_2.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/concrete_wall_2.zip" image: "http://subtlepatterns.com/patterns/concrete_wall_2.png" title: "Concrete wall 2" categories: ["concrete", "light"] image_dimensions: "597x545" , image_size: "173K" link: "http://subtlepatterns.com/concrete-wall/" description: "Dark blue concrete wall with some small dust spots." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/concrete_wall.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/concrete_wall.zip" image: "http://subtlepatterns.com/patterns/concrete_wall.png" title: "Concrete wall" categories: ["dark"] image_dimensions: "520x520" , image_size: "1K" link: "http://subtlepatterns.com/wavecut/" description: "If you like it a bit trippy, this wave pattern might be for you." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wavecut.png" author: "<a href=\"http://iansoper.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wavecut.zip" image: "http://subtlepatterns.com/patterns/wavecut.png" title: "WaveCut" categories: ["light"] image_dimensions: "162x15" , image_size: "131K" link: "http://subtlepatterns.com/little-pluses/" description: "Subtle grunge and many little pluses on top." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/little_pluses.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/little_pluses.zip" image: "http://subtlepatterns.com/patterns/little_pluses.png" title: "Little pluses" categories: ["light"] image_dimensions: "300x300" , image_size: "2K" link: "http://subtlepatterns.com/vichy/" description: "This one could be the shirt of a golf player. Angled lines in different thicknesses." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/vichy.png" author: "<a href=\"http://www.olivierpineda.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/vichy.zip" image: "http://subtlepatterns.com/patterns/vichy.png" title: "Vichy" categories: ["light"] image_dimensions: "70x70" , image_size: "8K" link: "http://subtlepatterns.com/random-grey-variations/" description: "Stefan is hard at work, this time with a funky pattern of squares." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/random_grey_variations.png" author: "<a href=\"http://www.MentalWardDesign.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/random_grey_variations.zip" image: "http://subtlepatterns.com/patterns/random_grey_variations.png" title: "Random Grey Variations" categories: ["dark"] image_dimensions: "200x200" , image_size: "10K" link: "http://subtlepatterns.com/brushed-alum/" description: "A light brushed aluminum pattern for your pleasure." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/brushed_alu.png" author: "<a href=\"http://www.MentalWardDesign.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/brushed_alu.zip" image: "http://subtlepatterns.com/patterns/brushed_alu.png" title: "Brushed Alum" categories: ["aluminum", "light"] image_dimensions: "400x400" , image_size: "89K" link: "http://subtlepatterns.com/brushed-alum-dark/" description: "Because I love dark patterns, here is Brushed Alum in a dark coating." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/brushed_alu_dark.png" author: "<a href=\"http://www.MentalWardDesign.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/brushed_alu_dark.zip" image: "http://subtlepatterns.com/patterns/brushed_alu_dark.png" title: "Brushed Alum Dark" categories: ["dark", "square"] image_dimensions: "400x400" , image_size: "82K" link: "http://subtlepatterns.com/black-linen/" description: "In the spirit of WWDC 2011, here is a dark iOS inspired linen pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black-Linen.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black-Linen.zip" image: "http://subtlepatterns.com/patterns/black-Linen.png" title: "Black Linen" categories: ["dark"] image_dimensions: "482x490" , image_size: "16K" link: "http://subtlepatterns.com/padded/" description: "A beautiful dark padded pattern, like an old classic sofa." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/padded.png" author: "<a href=\"http://papertank.co.uk\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/padded.zip" image: "http://subtlepatterns.com/patterns/padded.png" title: "Padded" categories: ["dark"] image_dimensions: "160x160" , image_size: "26K" link: "http://subtlepatterns.com/light-honeycomb/" description: "Light honeycomb pattern made up of the classic hexagon shape." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_honeycomb.png" author: "<a href=\"http://about.me/federicca\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_honeycomb.zip" image: "http://subtlepatterns.com/patterns/light_honeycomb.png" title: "Light Honeycomb" categories: ["light"] image_dimensions: "270x289" , image_size: "93K" link: "http://subtlepatterns.com/black-mamba/" description: "The name alone is awesome, but so is this sweet dark pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/blackmamba.png" author: "<a href=\"http://about.me/federicca\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/blackmamba.zip" image: "http://subtlepatterns.com/patterns/blackmamba.png" title: "Black Mamba" categories: ["dark"] image_dimensions: "500x500" , image_size: "79K" link: "http://subtlepatterns.com/black-paper/" description: "Black paper texture, based on two different images." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_paper.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a> based on textures from <a href=\"http://www.designkindle.com/2011/03/03/vintage-paper-textures-vol-1/\" target=\"_blank\">Design Kindle</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_paper.zip" image: "http://subtlepatterns.com/patterns/black_paper.png" title: "Black paper" categories: ["dark"] image_dimensions: "400x400" , image_size: "353B" link: "http://subtlepatterns.com/always-grey/" description: "Crossing lines with a subtle emboss effect on a dark background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/always_grey.png" author: "<a href=\"http://www.facebook.com/stefanaleksic88\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/always_grey.zip" image: "http://subtlepatterns.com/patterns/always_grey.png" title: "Always Grey" categories: ["dark"] image_dimensions: "35x35" , image_size: "7K" link: "http://subtlepatterns.com/double-lined/" description: "Horizontal and vertical lines on a light gray background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/double_lined.png" author: "<a href=\"http://www.depcore.pl\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/double_lined.zip" image: "http://subtlepatterns.com/patterns/double_lined.png" title: "Double lined" categories: ["light"] image_dimensions: "150x64" , image_size: "614K" link: "http://subtlepatterns.com/wood/" description: "Dark wooden pattern, given the subtle treatment." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wood_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a> based on texture from <a href=\"http://cloaks.deviantart.com/\" target=\"_blank\">Cloaks</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wood_1.zip" image: "http://subtlepatterns.com/patterns/wood_1.png" title: "Wood" categories: ["dark"] image_dimensions: "700x700" , image_size: "1015B" link: "http://subtlepatterns.com/cross-stripes/" description: "Nice and simple crossed lines in dark gray tones." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/crossed_stripes.png" author: "<a href=\"http://www.facebook.com/stefanaleksic88\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/crossed_stripes.zip" image: "http://subtlepatterns.com/patterns/crossed_stripes.png" title: "Cross Stripes" categories: ["dark"] image_dimensions: "6x6" , image_size: "20K" link: "http://subtlepatterns.com/noisy/" description: "Looks a bit like concrete with subtle specs spread around the pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noisy.png" author: "<a href=\"http://anticdesign.info\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy.zip" image: "http://subtlepatterns.com/patterns/noisy.png" title: "Noisy" categories: ["light", "noise"] image_dimensions: "300x300" , image_size: "47K" link: "http://subtlepatterns.com/old-mathematics/" description: "This one takes you back to math class. Classic mathematic board underlay." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/old_mathematics.png" author: "<a href=\"http://emailcoder.net/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/old_mathematics.zip" image: "http://subtlepatterns.com/patterns/old_mathematics.png" title: "Old Mathematics" categories: ["blue", "grid", "light", "mathematic"] image_dimensions: "200x200" , image_size: "100K" link: "http://subtlepatterns.com/rocky-wall/" description: "High detail stone wall with minor cracks and specks." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rockywall.png" author: "<a href=\"http://projecteightyfive.com/\" target=\"_blank\">Projecteightyfive</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rockywall.zip" image: "http://subtlepatterns.com/patterns/rockywall.png" title: "Rocky wall" categories: ["light", "rock", "wall"] image_dimensions: "500x500" , image_size: "1K" link: "http://subtlepatterns.com/dark-stripes/" description: "Very dark pattern with some noise and 45 degree lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_stripes.png" author: "<a href=\"http://www.facebook.com/stefanaleksic88\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_stripes.zip" image: "http://subtlepatterns.com/patterns/dark_stripes.png" title: "Dark stripes" categories: ["dark", "stripes"] image_dimensions: "50x50" , image_size: "6K" link: "http://subtlepatterns.com/handmade-paper/" description: "White hand made paper pattern with small bumps." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/handmadepaper.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/handmadepaper.zip" image: "http://subtlepatterns.com/patterns/handmadepaper.png" title: "Handmade paper" categories: ["light", "paper"] image_dimensions: "100x100" , image_size: "537B" link: "http://subtlepatterns.com/pinstripe/" description: "Light gray pattern with a thin pinstripe." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pinstripe.png" author: "<a href=\"http://extrast.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pinstripe.zip" image: "http://subtlepatterns.com/patterns/pinstripe.png" title: "Pinstripe" categories: ["gray", "light", "pinstripe"] image_dimensions: "50x500" , image_size: "45K" link: "http://subtlepatterns.com/wine-cork/" description: "Wine cork texture based off a scanned corkboard." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cork_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cork_1.zip" image: "http://subtlepatterns.com/patterns/cork_1.png" title: "Wine Cork" categories: ["cork", "light"] image_dimensions: "300x300" , image_size: "85K" link: "http://subtlepatterns.com/bedge-grunge/" description: "A large (588x375px) sand colored pattern for your ever growing collection. Shrink at will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/bedge_grunge.png" author: "<a href=\"http://www.tapein.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bedge_grunge.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/bedge_grunge.png" title: "Bedge grunge" categories: ["light"] image_dimensions: "588x375" , image_size: "24K" link: "http://subtlepatterns.com/noisy-net/" description: "Little x’es, noise and all the stuff you like. Dark like a Monday, with a hint of blue." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noisy_net.png" author: "<a href=\"http://twitter.com/_mcrdl\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy_net.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy_net.png" title: "Noisy Net" categories: ["dark", "noise"] image_dimensions: "200x200" , image_size: "53K" link: "http://subtlepatterns.com/grid/" description: "There are quite a few grid patterns, but this one is a super tiny grid with some dust for good measure." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grid.png" author: "<a href=\"http://www.werk.sk\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grid.png" title: "Grid" categories: ["grid", "light"] image_dimensions: "310x310" , image_size: "202B" link: "http://subtlepatterns.com/straws/" description: "Super detailed 16×16 tile that forms a beautiful pattern of straws." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/straws.png" author: "<a href=\"http://evaluto.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/straws.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/straws.png" title: "Straws" categories: ["light"] image_dimensions: "16x16" , image_size: "32K" link: "http://subtlepatterns.com/cardboard-flat/" description: "Not a flat you live inside, like in the UK – but a flat piece of cardboard." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cardboard_flat.png" author: "Appleshadow" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cardboard_flat.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cardboard_flat.png" title: "Cardboard Flat" categories: ["light"] image_dimensions: "256x256" , image_size: "32K" link: "http://subtlepatterns.com/noisy-grid/" description: "This is a grid, only it’s noisy. You know. Reminds you of those printed grids you draw on." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noisy_grid.png" author: "<a href=\"http://www.vectorpile.com\" target=\"_blank\">Vectorpile.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy_grid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noisy_grid.png" title: "Noisy Grid" categories: ["grid", "light"] image_dimensions: "150x150" , image_size: "2K" link: "http://subtlepatterns.com/office/" description: "I guess this one is inspired by an office. A dark office." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/office.png" author: "<a href=\"http://www.andresrigo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI.</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/office.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/office.png" title: "Office" categories: ["dark"] image_dimensions: "70x70" , image_size: "44K" link: "http://subtlepatterns.com/subtle-grey/" description: "The Grid. A digital frontier. I tried to picture clusters of information as they traveled through the computer." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/grey.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grey.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/grey.png" title: "Subtle Grey" categories: ["light"] image_dimensions: "397x322" , image_size: "218B" link: "http://subtlepatterns.com/hexabump/" description: "Hexagonal dark 3D pattern, what more can you ask for?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/hexabump.png" author: "<a href=\"http://spom.me\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/hexabump.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/hexabump.png" title: "Hexabump" categories: ["dark"] image_dimensions: "19x33" , image_size: "134K" link: "http://subtlepatterns.com/shattered/" description: "A large pattern with funky shapes and form. An original. Sort of origami-ish." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/shattered.png" author: "<a href=\"http://luukvanbaars.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shattered.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/shattered.png" title: "Shattered" categories: ["light", "origami"] image_dimensions: "500x500" , image_size: "32K" link: "http://subtlepatterns.com/paper-3/" description: "Light gray paper pattern with small traces of fibre and some dust." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper_3.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_3.zip" image: "http://subtlepatterns.com/patterns/paper_3.png" title: "Paper 3" categories: ["light", "paper"] image_dimensions: "276x276" , image_size: "9K" link: "http://subtlepatterns.com/dark-denim/" description: "A dark denim looking pattern. 145×145 pixels." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_denim.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_denim.zip" image: "http://subtlepatterns.com/patterns/black_denim.png" title: "Dark denim" categories: ["dark"] image_dimensions: "145x145" , image_size: "74K" link: "http://subtlepatterns.com/smooth-wall/" description: "Some rectangles, a bit of dust and grunge, plus a hint of concrete." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/smooth_wall.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">Atle Mo</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/smooth_wall.zip" image: "http://subtlepatterns.com/patterns/smooth_wall.png" title: "Smooth Wall" categories: ["light"] image_dimensions: "358x358" , image_size: "622B" link: "http://subtlepatterns.com/131/" description: "Never out of fashion and so much hotter than the 45º everyone knows, here is a sweet 60º line pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/60degree_gray.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/60degree_gray.zip" image: "http://subtlepatterns.com/patterns/60degree_gray.png" title: "60º lines" categories: ["light"] image_dimensions: "31x31" , image_size: "141K" link: "http://subtlepatterns.com/exclusive-paper/" description: "Exclusive looking paper pattern with small dust particles and 45 degree strokes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/exclusive_paper.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/exclusive_paper.zip" image: "http://subtlepatterns.com/patterns/exclusive_paper.png" title: "Exclusive paper" categories: ["light"] image_dimensions: "560x420" , image_size: "43K" link: "http://subtlepatterns.com/paper-2/" description: "New paper pattern with a slightly organic feel to it, using some thin threads." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper_2.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_2.zip" image: "http://subtlepatterns.com/patterns/paper_2.png" title: "Paper 2" categories: ["light"] image_dimensions: "280x280" , image_size: "17K" link: "http://subtlepatterns.com/white-sand/" description: "Same as gray sand but lighter. A sandy pattern with small light dots, and some angled strokes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_sand.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_sand.zip" image: "http://subtlepatterns.com/patterns/white_sand.png" title: "White sand" categories: ["light"] image_dimensions: "211x211" , image_size: "16K" link: "http://subtlepatterns.com/gray-sand/" description: "A dark gray, sandy pattern with small light dots, and some angled strokes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/gray_sand.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/gray_sand.zip" image: "http://subtlepatterns.com/patterns/gray_sand.png" title: "Gray sand" categories: ["dark"] image_dimensions: "211x211" , image_size: "82K" link: "http://subtlepatterns.com/paper-1/" description: "A slightly grainy paper pattern with small horisontal and vertical strokes." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/paper_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/paper_1.zip" image: "http://subtlepatterns.com/patterns/paper_1.png" title: "Paper 1" categories: ["light"] image_dimensions: "400x400" , image_size: "75K" link: "http://subtlepatterns.com/leather-1/" description: "A leather pattern with a hint of yellow." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/leather_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/leather_1.zip" image: "http://subtlepatterns.com/patterns/leather_1.png" title: "Leather 1" categories: ["light"] image_dimensions: "300x300" , image_size: "133B" link: "http://subtlepatterns.com/white-carbon/" description: "Same as the black version, but now in shades of gray. Very subtle and fine grained." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_carbon.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_carbon.zip" image: "http://subtlepatterns.com/patterns/white_carbon.png" title: "White carbon" categories: ["light"] image_dimensions: "8x8" , image_size: "99K" link: "http://subtlepatterns.com/fabric-1/" description: "Semi light fabric pattern made out of random pixles in shades of gray." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/fabric_1.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/fabric_1.zip" image: "http://subtlepatterns.com/patterns/fabric_1.png" title: "Fabric 1" categories: ["light"] image_dimensions: "400x400" , image_size: "117B" link: "http://subtlepatterns.com/micro-carbon/" description: "Three shades of gray makes this pattern look like a small carbon fibre surface. Great readability even for small fonts." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/micro_carbon.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/micro_carbon.zip" image: "http://subtlepatterns.com/patterns/micro_carbon.png" title: "Micro carbon" categories: ["dark"] image_dimensions: "4x4" , image_size: "1K" link: "http://subtlepatterns.com/tactile-noise/" description: "A heavy dark gray base, some subtle noise and a 45 degree grid makes this look like a pattern with a tactile feel to it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tactile_noise.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tactile_noise.zip" image: "http://subtlepatterns.com/patterns/tactile_noise.png" title: "Tactile noise" categories: ["dark"] image_dimensions: "48x48" , image_size: "142B" link: "http://subtlepatterns.com/carbon-fibre-2/" description: "A dark pattern made out of 3×3 circles and a 1px shadow. This works well as a carbon texture or background." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/carbon_fibre.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/carbon_fibre.zip" image: "http://subtlepatterns.com/patterns/carbon_fibre.png" title: "Carbon fibre" categories: ["dark"] image_dimensions: "24x22" , image_size: "78K" link: "http://subtlepatterns.com/awesome-pattern/" description: "Medium gray fabric pattern with 45 degree lines going across." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/45degreee_fabric.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/45degreee_fabric.zip" image: "http://subtlepatterns.com/patterns/45degreee_fabric.png" title: "45 degree fabric" categories: ["light"] image_dimensions: "315x315" , image_size: "138B" link: "http://subtlepatterns.com/subtle-carbon/" description: "There are many carbon patterns, but this one is tiny." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_carbon.png" author: "<a href=\"http://www.designova.net\" target=\"_blank\">Designova</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_carbon.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_carbon.png" title: "Subtle Carbon" categories: ["carbon", "dark"] image_dimensions: "18x15" , image_size: "4K" link: "http://subtlepatterns.com/swirl/" description: "The name tells you it has curves. Oh yes it does!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/swirl.png" author: "<a href=\"http://peterchondesign.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/swirl.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/swirl.png" title: "Swirl" categories: ["light", "swirl"] image_dimensions: "200x200" , image_size: "424B" link: "http://subtlepatterns.com/back-pattern/" description: "Pixel by pixel, sharp and clean. Very light pattern with clear lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/back_pattern.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/back_pattern.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/back_pattern.png" title: "Back pattern" categories: ["light"] image_dimensions: "28x28" , image_size: "470B" link: "http://subtlepatterns.com/translucent-fibres/" description: "The file was named striped lens, but hey – Translucent Fibres works too." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/striped_lens.png" author: "<a href=\"http://fleeting_days.livejournal.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/striped_lens.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/striped_lens.png" title: "Translucent Fibres" categories: ["light"] image_dimensions: "16x16" , image_size: "141B" link: "http://subtlepatterns.com/skeletal-weave/" description: "Imagine you zoomed in 1000X on some fabric. But then it turned out to be a skeleton!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/skelatal_weave.png" author: "<a href=\"http://fleeting_days.livejournal.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/skelatal_weave.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/skelatal_weave.png" title: "Skeletal Weave" categories: ["light"] image_dimensions: "25x25" , image_size: "191B" link: "http://subtlepatterns.com/black-twill/" description: "Trippy little gradients at an angle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_twill.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_twill.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_twill.png" title: "Black Twill" categories: ["dark"] image_dimensions: "14x14" , image_size: "150K" link: "http://subtlepatterns.com/asfalt/" description: "A very dark asfalt pattern based off of a photo taken with my iPhone. If you want to tweak it, I put the PSD here (a hint lighter, maybe?)." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/asfalt.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/asfalt.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/asfalt.png" title: "Asfalt" categories: ["asfalt", "dark"] image_dimensions: "466x349" , image_size: "199B" link: "http://subtlepatterns.com/subtle-surface/" description: "Super subtle indeed, a medium gray pattern with tiny dots in a grid." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_surface.png" author: "<a href=\"http://www.designova.net\" target=\"_blank\">Designova</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_surface.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_surface.png" title: "Subtle Surface" categories: ["gray", "light"] image_dimensions: "16x8" , image_size: "99K" link: "http://subtlepatterns.com/retina-wood/" description: "I’m not going to use the word Retina for all the new patterns, but it just felt right for this one. Huge wood pattern for ya’ll." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/retina_wood.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retina_wood.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retina_wood.png" title: "Retina Wood" categories: ["light", "retina", "wood"] image_dimensions: "512x512" , image_size: "1K" link: "http://subtlepatterns.com/subtle-dots/" description: "As simple and subtle as it get’s, but sometimes that’s just what you want." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_dots.png" author: "<a href=\"http://www.designova.net\" target=\"_blank\">DesignPI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_dots.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_dots.png" title: "Subtle Dots" categories: ["dots", "light"] image_dimensions: "27x15" , image_size: "89K" link: "http://subtlepatterns.com/dust/" description: "Another one bites the dust! Boyah." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dust.png" author: "<a href=\"http://www.werk.sk\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dust.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dust.png" title: "Dust" categories: ["light"] image_dimensions: "400x300" , image_size: "1K" link: "http://subtlepatterns.com/use-your-illusion/" description: "A dark one with geometric shapes and dotted lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/use_your_illusion.png" author: "<a href=\"http://www.mohawkstudios.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/use_your_illusion.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/use_your_illusion.png" title: "Use Your Illusion" categories: ["dark"] image_dimensions: "54x58" , image_size: "17K" link: "http://subtlepatterns.com/retina-dust/" description: "First pattern tailor made for Retina, with many more to come. All the old ones are upscaled, in case you want to re-download." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/retina_dust.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retina_dust.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retina_dust.png" title: "Retina dust" categories: ["light", "retina"] image_dimensions: "200x200" , image_size: "8K" link: "http://subtlepatterns.com/gray-lines/" description: "Some more diagonal lines and noise, because you know you want it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_noise_diagonal.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_noise_diagonal.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_noise_diagonal.png" title: "Gray lines" categories: ["diagonal", "light", "noise"] image_dimensions: "150x150" , image_size: "2K" link: "http://subtlepatterns.com/noise-lines/" description: "Lovely pattern with some good looking non-random-noise-lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/noise_lines.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noise_lines.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/noise_lines.png" title: "Noise lines" categories: ["diagonal", "light", "noise"] image_dimensions: "60x59" , image_size: "139B" link: "http://subtlepatterns.com/pyramid/" description: "Could remind you a bit of those squares in Super Mario Bros, yeh?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/pyramid.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pyramid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/pyramid.png" title: "Pyramid" categories: ["light"] image_dimensions: "16x16" , image_size: "4K" link: "http://subtlepatterns.com/retro-intro/" description: "A slightly more textured pattern, medium gray. A bit like a potato sack?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/retro_intro.png" author: "<a href=\"http://www.twitter.com/Creartinc\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retro_intro.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/retro_intro.png" title: "Retro Intro" categories: ["light", "textured"] image_dimensions: "109x109" , image_size: "240B" link: "http://subtlepatterns.com/tiny-grid/" description: "You know, tiny and sharp. I’m sure you’ll find a use for it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/tiny_grid.png" author: "<a href=\"http://atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tiny_grid.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tiny_grid.png" title: "Tiny Grid" categories: ["grid", "light"] image_dimensions: "26x26" , image_size: "33K" link: "http://subtlepatterns.com/textured-stripes/" description: "A lovely light gray pattern with stripes and a dash of noise." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/textured_stripes.png" author: "<a href=\"http://tiled-bg.blogspot.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/textured_stripes.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/textured_stripes.png" title: "Textured Stripes" categories: ["light"] image_dimensions: "256x256" , image_size: "27K" link: "http://subtlepatterns.com/strange-bullseyes/" description: "This is indeed a bit strange, but here’s to the crazy ones!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/strange_bullseyes.png" author: "<a href=\"http://cwbuecheler.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/strange_bullseyes.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/strange_bullseyes.png" title: "Strange Bullseyes" categories: ["light"] image_dimensions: "300x300" , image_size: "22K" link: "http://subtlepatterns.com/low-contrast-linen/" description: "A smooth mid-tone gray, or low contrast if you will, linen pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/low_contrast_linen.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/low_contrast_linen.zip" image: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/low_contrast_linen.png" title: "Low Contrast Linen" categories: ["dark"] image_dimensions: "256x256" , image_size: "56K" link: "http://subtlepatterns.com/egg-shell/" description: "It’s an egg, in the form of a pattern. This really is 2012." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/egg_shell.png" author: "<a href=\"http://phoenixweiss.me\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/egg_shell.zip" image: "http://subtlepatterns.com/patterns/egg_shell.png" title: "Egg Shell" categories: ["light"] image_dimensions: "256x256" , image_size: "142K" link: "http://subtlepatterns.com/clean-gray-paper/" description: "On a large canvas you can see it tiling, but used on smaller areas it’s beautiful." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/extra_clean_paper.png" author: "<a href=\"http://phoenixweiss.me\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/extra_clean_paper.zip" image: "http://subtlepatterns.com/patterns/extra_clean_paper.png" title: "Clean gray paper" categories: ["light"] image_dimensions: "512x512" , image_size: "443B" link: "http://subtlepatterns.com/norwegian-rose/" description: "I’m not going to lie – if you submit something with the words Norwegian and Rose in it, it’s likely I’ll publish it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/norwegian_rose.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/norwegian_rose.zip" image: "http://subtlepatterns.com/patterns/norwegian_rose.png" title: "Norwegian Rose" categories: ["light", "rose"] image_dimensions: "48x48" , image_size: "291B" link: "http://subtlepatterns.com/subtlenet/" description: "You can never get enough of these tiny pixel patterns with sharp lines." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtlenet2.png" author: "<a href=\"http://www.designova.net\" target=\"_blank\">Designova</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtlenet2.zip" image: "http://subtlepatterns.com/patterns/subtlenet2.png" title: "SubtleNet" categories: ["light"] image_dimensions: "60x60" , image_size: "32K" link: "http://subtlepatterns.com/dirty-old-black-shirt/" description: "Used in small doses, this could be a nice subtle pattern. Used on a large surface, it’s dirty!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dirty_old_shirt.png" author: "<a href=\"https://twitter.com/#!/PaulReulat\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dirty_old_shirt.zip" image: "http://subtlepatterns.com/patterns/dirty_old_shirt.png" title: "Dirty old black shirt" categories: ["dark"] image_dimensions: "250x250" , image_size: "71K" link: "http://subtlepatterns.com/redox-02/" description: "After 1 comes 2, same but different. You get the idea." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/redox_02.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/redox_02.zip" image: "http://subtlepatterns.com/patterns/redox_02.png" title: "Redox 02" categories: ["light"] image_dimensions: "600x340" , image_size: "88K" link: "http://subtlepatterns.com/redox-01/" description: "Bright gray tones with a hint of some metal surface." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/redox_01.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/redox_01.zip" image: "http://subtlepatterns.com/patterns/redox_01.png" title: "Redox 01" categories: ["light"] image_dimensions: "600x375" , image_size: "51K" link: "http://subtlepatterns.com/skin-side-up/" description: "White fabric looking texture with some nice random wave features." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/skin_side_up.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">PI:NAME:<NAME>END_PImers</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/skin_side_up.zip" image: "http://subtlepatterns.com/patterns/skin_side_up.png" title: "Skin Side Up" categories: ["light"] image_dimensions: "320x360" , image_size: "211K" link: "http://subtlepatterns.com/solid/" description: "A mid-tone gray patterns with some cement looking texture." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/solid.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/solid.zip" image: "http://subtlepatterns.com/patterns/solid.png" title: "Solid" categories: ["cement", "light"] image_dimensions: "500x500" , image_size: "297B" link: "http://subtlepatterns.com/stitched-wool/" description: "I love these crisp, tiny, super subtle patterns." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/stitched_wool.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/stitched_wool.zip" image: "http://subtlepatterns.com/patterns/stitched_wool.png" title: "Stitched Wool" categories: ["light"] image_dimensions: "224x128" , image_size: "50K" link: "http://subtlepatterns.com/crisp-paper-ruffles/" description: "Sort of reminds me of those old house wallpapers." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/crisp_paper_ruffles.png" author: "<a href=\"http://www.ayonnette.blogspot.com\" target=\"_blank\">Tish</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/crisp_paper_ruffles.zip" image: "http://subtlepatterns.com/patterns/crisp_paper_ruffles.png" title: "Crisp Paper Ruffles" categories: ["light"] image_dimensions: "481x500" , image_size: "1K" link: "http://subtlepatterns.com/white-linen/" description: "Dead simple but beautiful horizontal line pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/linen.png" author: "<a href=\"http://fabianschultz.de/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/linen.zip" image: "http://subtlepatterns.com/patterns/linen.png" title: "White Linen" categories: ["light"] image_dimensions: "400x300" , image_size: "122B" link: "http://subtlepatterns.com/polyester-lite/" description: "A tiny polyester pixel pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/polyester_lite.png" author: "<a href=\"http://dribbble.com/jeremyelder\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/polyester_lite.zip" image: "http://subtlepatterns.com/patterns/polyester_lite.png" title: "Polyester Lite" categories: ["light"] image_dimensions: "17x22" , image_size: "131K" link: "http://subtlepatterns.com/light-paper-fibers/" description: "More in the paper realm, this time with fibers." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/lightpaperfibers.png" author: "<a href=\"http://www.jorgefuentes.net\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/lightpaperfibers.zip" image: "http://subtlepatterns.com/patterns/lightpaperfibers.png" title: "Light paper fibers" categories: ["light"] image_dimensions: "500x300" , image_size: "98K" link: "http://subtlepatterns.com/natural-paper/" description: "You know I’m a sucker for these. Well crafted paper pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/natural_paper.png" author: "PI:NAME:<NAME>END_PI" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/natural_paper.zip" image: "http://subtlepatterns.com/patterns/natural_paper.png" title: "Natural Paper" categories: ["light"] image_dimensions: "523x384" , image_size: "47K" link: "http://subtlepatterns.com/burried/" description: "Have you wondered about how it feels to be buried alive? Here is the pattern for it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/burried.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/burried.zip" image: "http://subtlepatterns.com/patterns/burried.png" title: "Burried" categories: ["dark", "mud"] image_dimensions: "350x350" , image_size: "44K" link: "http://subtlepatterns.com/rebel/" description: "Not the Rebel alliance, but a dark textured pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/rebel.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/rebel.zip" image: "http://subtlepatterns.com/patterns/rebel.png" title: "Rebel" categories: ["dark"] image_dimensions: "320x360" , image_size: "7K" link: "http://subtlepatterns.com/assault/" description: "Dark, crisp and sort of muddy this one." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/assault.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/assault.zip" image: "http://subtlepatterns.com/patterns/assault.png" title: "Assault" categories: ["dark"] image_dimensions: "154x196" , image_size: "146B" link: "http://subtlepatterns.com/absurdity/" description: "Bit of a strange name on this one, but still nice. Tiny gray square things." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/absurdidad.png" author: "<a href=\"http://saveder.blogspot.mx/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/absurdidad.zip" image: "http://subtlepatterns.com/patterns/absurdidad.png" title: "Absurdity" categories: ["light"] image_dimensions: "4x4" , image_size: "103B" link: "http://subtlepatterns.com/white-carbonfiber/" description: "More carbon fiber for your collections. This time in white or semi-dark gray." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_carbonfiber.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_carbonfiber.zip" image: "http://subtlepatterns.com/patterns/white_carbonfiber.png" title: "White Carbonfiber" categories: ["carbon", "light"] image_dimensions: "4x4" , image_size: "1K" link: "http://subtlepatterns.com/white-bed-sheet/" description: "Nothing like a clean set of bed sheets, huh?" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_bed_sheet.png" author: "<a href=\"http://dribbble.com/graphcoder\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_bed_sheet.zip" image: "http://subtlepatterns.com/patterns/white_bed_sheet.png" title: "White Bed Sheet" categories: ["light"] image_dimensions: "54x54" , image_size: "24K" link: "http://subtlepatterns.com/skewed-print/" description: "An interesting dark spotted pattern at an angle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/skewed_print.png" author: "<a href=\"http://www.hendriklammers.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/skewed_print.zip" image: "http://subtlepatterns.com/patterns/skewed_print.png" title: "Skewed print" categories: ["dark"] image_dimensions: "330x320" , image_size: "31K" link: "http://subtlepatterns.com/dark-wall/" description: "Just to prove my point, here is a slightly modified dark version." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/dark_wall.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/dark_wall.zip" image: "http://subtlepatterns.com/patterns/dark_wall.png" title: "Dark Wall" categories: ["dark"] image_dimensions: "300x300" , image_size: "47K" link: "http://subtlepatterns.com/wall-4-light/" description: "I’m starting to think I have a concrete wall fetish." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/wall4.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/wall4.zip" image: "http://subtlepatterns.com/patterns/wall4.png" title: "Wall #4 Light" categories: ["light"] image_dimensions: "300x300" , image_size: "395B" link: "http://subtlepatterns.com/escheresque/" description: "Cubes as far as your eyes can see. You know, because they tile." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/escheresque.png" author: "<a href=\"http://dribbble.com/janmeeus\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/escheresque.zip" image: "http://subtlepatterns.com/patterns/escheresque.png" title: "Escheresque" categories: ["light"] image_dimensions: "46x29" , image_size: "209B" link: "http://subtlepatterns.com/climpek/" description: "Small gradient crosses inside 45 degree boxes, or bigger crosses if you will." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/climpek.png" author: "<a href=\"http://blugraphic.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/climpek.zip" image: "http://subtlepatterns.com/patterns/climpek.png" title: "Climpek" categories: ["light"] image_dimensions: "44x44" , image_size: "154B" link: "http://subtlepatterns.com/nistri/" description: "No idea what Nistri means, but it’s a crisp little pattern nonetheless." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/nistri.png" author: "<a href=\"http://reitermark.us/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/nistri.zip" image: "http://subtlepatterns.com/patterns//nistri.png" title: "Nistri" categories: ["light"] image_dimensions: "38x38" , image_size: "242K" link: "http://subtlepatterns.com/white-wall/" description: "A huge one at 800x600px. Made from a photo I took going home after work." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/white_wall.png" author: "<a href=\"http://www.atlemo.com\" target=\"_blank\">AtPI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/white_wall.zip" image: "http://subtlepatterns.com/patterns/white_wall.png" title: "White wall" categories: ["light", "wall"] image_dimensions: "800x600" , image_size: "390B" link: "http://subtlepatterns.com/the-black-mamba/" description: "Super dark, crisp and detailed. And a Kill Bill reference." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/black_mamba.png" author: "<a href=\"http://graphicriver.net/user/graphcoder?ref=graphcoder\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/black_mamba.zip" image: "http://subtlepatterns.com/patterns/black_mamba.png" title: "The Black Mamba" categories: ["dark"] image_dimensions: "192x192" , image_size: "8K" link: "http://subtlepatterns.com/diamond-upholstery/" description: "A re-make of the Gradient Squares pattern." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/diamond_upholstery.png" author: "<a href=\"http://hellogrid.com\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/diamond_upholstery.zip" image: "http://subtlepatterns.com/patterns/diamond_upholstery.png" title: "Diamond Upholstery" categories: ["diamond", "light"] image_dimensions: "200x200" , image_size: "179B" link: "http://subtlepatterns.com/corrugation/" description: "The act or state of corrugating or of being corrugated, a wrinkle; fold; furrow; ridge." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/corrugation.png" author: "<a href=\"http://graphicriver.net/user/Naf_Naf?ref=Naf_Naf\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/corrugation.zip" image: "http://subtlepatterns.com/patterns/corrugation.png" title: "Corrugation" categories: ["light"] image_dimensions: "8x5" , image_size: "479B" link: "http://subtlepatterns.com/reticular-tissue/" description: "Tiny and crisp, just the way it should be." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/reticular_tissue.png" author: "<a href=\"http://graphicriver.net/user/Naf_Naf?ref=Naf_Naf\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/reticular_tissue.zip" image: "http://subtlepatterns.com/patterns/reticular_tissue.png" title: "Reticular Tissue" categories: ["light"] image_dimensions: "25x25" , image_size: "408B" link: "http://subtlepatterns.com/lyonnette/" description: "Small crosses with round edges. Quite cute." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/lyonnette.png" author: "<a href=\"http://www.ayonnette.blogspot.com\" target=\"_blank\">Tish</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/lyonnette.zip" image: "http://subtlepatterns.com/patterns/lyonnette.png" title: "Lyonnette" categories: ["light"] image_dimensions: "90x90" , image_size: "21K" link: "http://subtlepatterns.com/light-toast/" description: "Has nothing to do with toast, but it’s nice and subtle." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/light_toast.png" author: "<a href=\"https://twitter.com/#!/pippinlee\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/light_toast.zip" image: "http://subtlepatterns.com/patterns/light_toast.png" title: "Light Toast" categories: ["light", "noise"] image_dimensions: "200x200" , image_size: "24K" link: "http://subtlepatterns.com/txture/" description: "Dark, lines, noise, tactile. You get the drift." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/txture.png" author: "<a href=\"http://designchomp.com/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/txture.zip" image: "http://subtlepatterns.com/patterns/txture.png" title: "Txture" categories: ["dark"] image_dimensions: "400x300" , image_size: "6K" link: "http://subtlepatterns.com/gray-floral/" description: "Floral patterns might not be the hottest thing right now, but you never know when you need it!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/greyfloral.png" author: "<a href=\"http://laurenharrison.org\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/greyfloral.zip" image: "http://subtlepatterns.com/patterns/greyfloral.png" title: "Gray Floral" categories: ["floral", "light"] image_dimensions: "150x124" , image_size: "85B" link: "http://subtlepatterns.com/brilliant/" description: "This is so subtle you need to bring your magnifier!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/brillant.png" author: "<a href=\"http://saveder.blogspot.mx/\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/brillant.zip" image: "http://subtlepatterns.com/patterns/brillant.png" title: "Brilliant" categories: ["light", "subtle"] image_dimensions: "3x3" , image_size: "1K" link: "http://subtlepatterns.com/subtle-stripes/" description: "Vertical lines with a bumpy yet crisp feel to it." mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/subtle_stripes.png" author: "<a href=\"http://cargocollective.com/raasa\" target=\"_blank\">Raasa</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/subtle_stripes.zip" image: "http://subtlepatterns.com/patterns/subtle_stripes.png" title: "Subtle stripes" categories: ["light", "stripes"] image_dimensions: "40x40" , image_size: "86K" link: "http://subtlepatterns.com/cartographer/" description: "A topographic map like this has actually been requested a few times, so here you go!" mirror_image: "http://bradjasper.com/subtle-patterns-bookmarklet/patterns/cartographer.png" author: "<a href=\"http://sam.feyaerts.me\" target=\"_blank\">PI:NAME:<NAME>END_PI</a>" download: "http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/cartographer.zip" image: "http://subtlepatterns.com/patterns/cartographer.png" title: "Cartographer" categories: ["cartographer", "dark", "topography"] image_dimensions: "500x499" ]
[ { "context": "wo\nlist.3 = three\n\n! add a sub object\nperson.name: Alexander Schilling\nperson.job: Developer\n\n#references\nref = ${string", "end": 525, "score": 0.9998852610588074, "start": 506, "tag": "NAME", "value": "Alexander Schilling" }, { "context": "\nref = ${string}\n\n...
src/type/properties.coffee
alinex/node-formatter
0
### Properties ============================================================== Mainly in the Java world properties are used to setup configuration values. But it won't have support for arrays, you only may use objects with numbered keys. Common file extension `properties`. ``` properties # strings string = test other text multiline This text \ goes over multiple lines. # numbers integer = 15 float: -4.6 ! add a simple list list.1 = one list.2 = two list.3 = three ! add a sub object person.name: Alexander Schilling person.job: Developer #references ref = ${string} # add a section [section] name = Alex same = ${section|name} ``` This format supports: - key and value may be divided by `=`, `:` with spaces or only a space - comments start with `!` or `#` - structure data using sections with square brackets like in ini files - structure data using namespaces in the key using dot as seperator - references to other values with `${key}` - references work also as section names or reference name ### # Node Modules # ------------------------------------------------- # include base modules properties = require 'properties' # Implementation # ------------------------------------------------- # @param {Object} obj to be formatted # @param {Object} [options] not used in this type # @param {Function(Error, String)} cb callback will be called with result exports.stringify = (obj, _, cb) -> try text = properties.stringify flatten(obj), unicode: true catch error return cb error if error cb null, text # @param {String} text to be parsed # @param {Object} [options] not used in this type # @param {Function(Error, Object)} cb callback will be called with result exports.parse = (text, _, cb) -> properties.parse text.toString(), sections: true namespaces: true variables: true , (err, result) -> return cb err if err unless propertiesCheck result return cb new Error "Unexpected characters []{}/ in key name found" cb null, optimizeArray result # Helper # ------------------------------------------------- # @param {Object} data parsed data to check # @return {Boolean} true if no parsing errors are included propertiesCheck = (data) -> return true unless typeof data is 'object' for k, v of data if v is null or ~'[]{}/'.indexOf k.charAt 0 return false return false unless propertiesCheck v return true # @param {Object} obj deep structure # @return flat structure flatten = (obj) -> return obj unless typeof obj is 'object' flat = {} # recursive flatten for key, value of obj unless typeof value is 'object' flat[key] = value else for k, v of flatten value flat["#{key}.#{k}"] = v return flat # @param {Object} obj to convert to array if possible # @return {Object|Array} optimized structure optimizeArray = (obj) -> return obj unless typeof obj is 'object' # recursive work further for key, value of obj obj[key] = optimizeArray value # replace with array if possible keys = Object.keys obj keys.sort() if keys.join(',') is [0..keys.length-1].join(',') list = [] list.push obj[k] for k in keys obj = list obj
143482
### Properties ============================================================== Mainly in the Java world properties are used to setup configuration values. But it won't have support for arrays, you only may use objects with numbered keys. Common file extension `properties`. ``` properties # strings string = test other text multiline This text \ goes over multiple lines. # numbers integer = 15 float: -4.6 ! add a simple list list.1 = one list.2 = two list.3 = three ! add a sub object person.name: <NAME> person.job: Developer #references ref = ${string} # add a section [section] name = <NAME> same = ${section|name} ``` This format supports: - key and value may be divided by `=`, `:` with spaces or only a space - comments start with `!` or `#` - structure data using sections with square brackets like in ini files - structure data using namespaces in the key using dot as seperator - references to other values with `${key}` - references work also as section names or reference name ### # Node Modules # ------------------------------------------------- # include base modules properties = require 'properties' # Implementation # ------------------------------------------------- # @param {Object} obj to be formatted # @param {Object} [options] not used in this type # @param {Function(Error, String)} cb callback will be called with result exports.stringify = (obj, _, cb) -> try text = properties.stringify flatten(obj), unicode: true catch error return cb error if error cb null, text # @param {String} text to be parsed # @param {Object} [options] not used in this type # @param {Function(Error, Object)} cb callback will be called with result exports.parse = (text, _, cb) -> properties.parse text.toString(), sections: true namespaces: true variables: true , (err, result) -> return cb err if err unless propertiesCheck result return cb new Error "Unexpected characters []{}/ in key name found" cb null, optimizeArray result # Helper # ------------------------------------------------- # @param {Object} data parsed data to check # @return {Boolean} true if no parsing errors are included propertiesCheck = (data) -> return true unless typeof data is 'object' for k, v of data if v is null or ~'[]{}/'.indexOf k.charAt 0 return false return false unless propertiesCheck v return true # @param {Object} obj deep structure # @return flat structure flatten = (obj) -> return obj unless typeof obj is 'object' flat = {} # recursive flatten for key, value of obj unless typeof value is 'object' flat[key] = value else for k, v of flatten value flat["#{key}.#{k}"] = v return flat # @param {Object} obj to convert to array if possible # @return {Object|Array} optimized structure optimizeArray = (obj) -> return obj unless typeof obj is 'object' # recursive work further for key, value of obj obj[key] = optimizeArray value # replace with array if possible keys = Object.keys obj keys.sort() if keys.join(',') is [0..keys.length-1].join(',') list = [] list.push obj[k] for k in keys obj = list obj
true
### Properties ============================================================== Mainly in the Java world properties are used to setup configuration values. But it won't have support for arrays, you only may use objects with numbered keys. Common file extension `properties`. ``` properties # strings string = test other text multiline This text \ goes over multiple lines. # numbers integer = 15 float: -4.6 ! add a simple list list.1 = one list.2 = two list.3 = three ! add a sub object person.name: PI:NAME:<NAME>END_PI person.job: Developer #references ref = ${string} # add a section [section] name = PI:NAME:<NAME>END_PI same = ${section|name} ``` This format supports: - key and value may be divided by `=`, `:` with spaces or only a space - comments start with `!` or `#` - structure data using sections with square brackets like in ini files - structure data using namespaces in the key using dot as seperator - references to other values with `${key}` - references work also as section names or reference name ### # Node Modules # ------------------------------------------------- # include base modules properties = require 'properties' # Implementation # ------------------------------------------------- # @param {Object} obj to be formatted # @param {Object} [options] not used in this type # @param {Function(Error, String)} cb callback will be called with result exports.stringify = (obj, _, cb) -> try text = properties.stringify flatten(obj), unicode: true catch error return cb error if error cb null, text # @param {String} text to be parsed # @param {Object} [options] not used in this type # @param {Function(Error, Object)} cb callback will be called with result exports.parse = (text, _, cb) -> properties.parse text.toString(), sections: true namespaces: true variables: true , (err, result) -> return cb err if err unless propertiesCheck result return cb new Error "Unexpected characters []{}/ in key name found" cb null, optimizeArray result # Helper # ------------------------------------------------- # @param {Object} data parsed data to check # @return {Boolean} true if no parsing errors are included propertiesCheck = (data) -> return true unless typeof data is 'object' for k, v of data if v is null or ~'[]{}/'.indexOf k.charAt 0 return false return false unless propertiesCheck v return true # @param {Object} obj deep structure # @return flat structure flatten = (obj) -> return obj unless typeof obj is 'object' flat = {} # recursive flatten for key, value of obj unless typeof value is 'object' flat[key] = value else for k, v of flatten value flat["#{key}.#{k}"] = v return flat # @param {Object} obj to convert to array if possible # @return {Object|Array} optimized structure optimizeArray = (obj) -> return obj unless typeof obj is 'object' # recursive work further for key, value of obj obj[key] = optimizeArray value # replace with array if possible keys = Object.keys obj keys.sort() if keys.join(',') is [0..keys.length-1].join(',') list = [] list.push obj[k] for k in keys obj = list obj
[ { "context": "e layer content\n# * **g** - A {https://github.com/mbostock/d3/wiki/Selections D3 selection} for the SVG g no", "end": 930, "score": 0.9994378089904785, "start": 922, "tag": "USERNAME", "value": "mbostock" }, { "context": "idths, rounding errors, etc.\n# @abstract\n# @a...
js/c3-layers.coffee
jgkamat/chartcollection
0
# c3 Visualization Library # Layers for XY Plots ################################################################### # XY Plot Chart Layers ################################################################### # The root abstract class of layers for the {c3.Plot c3 XY Plot Chart} # # ## Internal Interface # The internal interface that plot layers can implement essentially match the {c3.Base} internal abstract interface: # * **{c3.base#init init()}** # * **{c3.base#size size()}** # * **{c3.base#update update()}** # * **{c3.base#draw draw()}** # * **{c3.base#style style()}** # # An additional method is added: # * **zoom()** - Called when the chart is zoomed or panned. # # ## Extensibility # Each layer has the following members added: # * **chart** - Reference to the {c3.Plot XY Plot Chart} this layer belongs to # * **content** - A {c3.Selection selection} of the layer content # * **g** - A {https://github.com/mbostock/d3/wiki/Selections D3 selection} for the SVG g node for this layer # * **width** - width of the layer # * **height** - height of the layer # # @method #on(event, handler) # Register an event handler to catch events fired by the visualization. # @param event [String] The name of the event to handle. _See the Exetensibility and Events section for {c3.base}._ # @param handler [Function] Callback function called with the event. The arguments passed to the function are event-specific. # # Items should be positioned on the the layer using the layer's `h` and `v` scales. # As a performance optimization some layers may create a g node with the `scaled` class. # When the plot is zoomed then this group will have a transform applied to reflect the zoom so # individual elements do not need to be adjusted. Please use the `chart.orig_h` scale in this case. # Not that this approach does not work for many circumstances as it affects text aspect ratio, # stroke widths, rounding errors, etc. # @abstract # @author Douglas Armstrong class c3.Plot.Layer @version: 0.2 c3.Layer = this # Shortcut for accessing plot layers. type: 'layer' @_next_uid: 0 # [Array] Data for this layer _This can be set for each individual layer or a default for the entire chart._ data: undefined # [String] User name for this layer. This is used in legends, for example. name: undefined # [String] CSS class to assign to this layer for user style sheets to customize class: undefined # [Boolean] If true this layer is considered to have "static" data and will not update when {c3.Base#redraw redraw()} is called. static_data: false # [{https://github.com/mbostock/d3/wiki/Scales d3.scale}] Scale for the _vertical_ Y axis for this layer. # Please set the _domain()_, c3 will set the _range()_. # _The vertical scale may be set for the entire chart instead of for each layer._ h: undefined # [{https://github.com/mbostock/d3/wiki/Scales d3.scale}] Scale for the _vertical_ Y axis for this layer. # Please set the _domain()_, c3 will set the _range()_. # _The vertical scale may be set for the entire chart instead of for each layer._ v: undefined # [Function] An accessor function to get the X value from a data item. # _This can be set for each individual layer or a default for the entire chart._ # Some plots support calling this accessor with the index of the data as well as the datum itself. x: undefined # [Function] An accessor function to get the Y value from a data item. # _This can be set for each individual layer or a default for the entire chart._ # Some plots support calling this accessor with the index of the data as well as the datum itself. y: undefined # [String] `left` for 0 to be at the left, `right` for the right. h_orient: undefined # [String] `top` for 0 to be at the top, `bottom` for the bottom. v_orient: undefined # [{c3.Selection.Options}] Options to set the **class**, **classes**, **styles**, # **events**, and **title** for this layer. options: undefined # [Object] An object to setup event handlers to catch events triggered by this c3 layer. # The keys represent event names and the values are the cooresponding handlers. handlers: undefined constructor: (opt)-> c3.util.extend this, new c3.Dispatch c3.util.extend this, opt @uid = c3.Plot.Layer._next_uid++ # Internal function for the Plot to prepare the layer. init: (@chart, @g)=> @trigger 'render_start' @data ?= @chart.data @h ?= @chart.h @v ?= @chart.v @x ?= @chart.x @y ?= @chart.y @h_orient ?= @chart.h_orient @v_orient ?= @chart.v_orient if @class? then @g.classed @class, true if @handlers? then @on event, handler for event, handler of @handlers @content = c3.select(@g) # Apply classes to layer g nodes based on the `type` of the layer object hierarchy prototype = Object.getPrototypeOf(@) while prototype if prototype.type? then @g.classed prototype.type, true prototype = Object.getPrototypeOf prototype @_init?() @trigger 'render' # Resize the layer, but _doesn't_ update the rendering, `resize()` should be used for that. size: (@width, @height)=> @trigger 'resize_start' if @h_orient != @chart.h_orient and @h == @chart.h then @h = @h.copy() c3.d3.set_range @h, if @h_orient is 'left' then [0, @width] else [@width, 0] if @v_orient != @chart.v_orient and @v == @chart.v then @v = @v.copy() c3.d3.set_range @v, if @v_orient is 'bottom' then [@height, 0] else [0, @height] @_size?() @trigger 'resize' # Update the DOM bindings based on the new or modified data set update: (origin)=> if not @chart? then throw Error "Attempt to redraw uninitialized plot layer, please use render() when modifying set of layers." @trigger 'redraw_start', origin @_update?(origin) # Position the DOM elements based on current scales. draw: (origin)=> if not (@static_data and origin is 'redraw') @trigger 'redraw_start', origin if origin is 'resize' @_draw?(origin) @trigger 'redraw', origin # Restyle existing items in the layer style: (style_new)=> @trigger 'restyle_start', style_new @_style?(style_new) @trigger 'restyle', style_new @trigger 'rendered' if not @rendered return this # Called when a layer needs to update from a zoom, decimated layers overload this zoom: => @draw?('zoom') @style?(true) # Redraw just this layer redraw: (origin='redraw')=> @update(origin) @draw(origin) @style(true) return this # Method to restyle this layer restyle: Layer::style # Adjust domains for layer scales for any automatic domains. # For layer-specific automatic domains the layer needs its own scale defined, # it cannot update the chart's shared scale. # @note Needs to happen after update() so that stacked layers are computed scale: => refresh = false if @h_domain? if @h==@chart.h then throw Error "Layer cannot scale shared h scale, please define just h or both h and h_domain for layers" h_domain = if typeof @h_domain is 'function' then @h_domain.call(this) else @h_domain if h_domain[0] is 'auto' then h_domain[0] = @min_x() if h_domain[1] is 'auto' then h_domain[1] = @max_x() if h_domain[0]!=@h.domain()[0] or h_domain[1]!=@h.domain()[1] @h.domain h_domain refresh = true if @v_domain? if @v==@chart.v then throw Error "Layer cannot scale shared v scale, please define just v or both v and v_domain for layers" v_domain = if typeof @v_domain is 'function' then @v_domain.call(this) else @v_domain if v_domain[0] is 'auto' then v_domain[0] = @min_y() if v_domain[1] is 'auto' then v_domain[1] = @max_y() if v_domain[0]!=@v.domain()[0] or v_domain[1]!=@v.domain()[1] @v.domain v_domain refresh = true return refresh min_x: => if @x? then d3.min @data, @x max_x: => if @x? then d3.max @data, @x min_y: => if @y? then d3.min @data, @y max_y: => if @y? then d3.max @data, @y ################################################################### # XY Plot Stackable Layers ################################################################### # An **abstract** class for layers that support stacking # such as {c3.Plot.Layer.Path} and {c3.Plot.Layer.Bar}. # # **Stacking** allows the user to group their data into different _stacks_, which are stacked # on top of each other in the chart. Stacking is enabled when you define _either_ `stack_options.key`, `stacks`, # or both options. `stack_options` allows you to configure how stacking is performed from the layer's data, # while `stacks` allows you to manually configure the exact set of stacks. # # This layer stacking is flexible to support several different ways of organizing the dataset into stacks: # * For normalized datasets you can define a `stack_options.key()` accessor to provide a key that uniquely # identifies which stack an element belongs to. # * Otherwise, you can manually define the set of `stacks` and the layer's `data` is copied into each. # * * The layer `y` accessor will be called with the arguments (_datum_,_index_,_stack_) # for you to provide the value for that element for that stack. # * * Or, you can define a `y` accessor for each stack to get the value for that element for that stack. # * You can also directly define `data` in each stack specified in `stacks`. # # Please view the examples for more explanation on how to stack data. # Remember, the set and order or stacks can always be programmatically constructed and dynamically updated. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **groups** - An entry will exist for an svg:g node for each stack in the layer # # @see ../../../examples/doc/stack_example.html # @abstract # @author Douglas Armstrong # @note If stacked, the input datasets may not have duplicate values in the same stack for the same X value. There are other resitrictions if `safe` mode is not used. # @note If you do not provide data elements for all stacks at all x values, then be prepared for your accessor callbacks to be called with _null_ objects. class c3.Plot.Layer.Stackable extends c3.Plot.Layer @version: 0.2 type: 'stackable' # [{c3.Selection.Options}] Enable stacking and specify stacking options for this layer. # This provides the normal {c3.Selection.Options} applied to each stack in the layer. For callbacks, # the first argument is the stack object and the second argument is the index to the stack # In addition, the following options control stacking behaviour: # * **key** [Function] An accessor you can define to return a key that uniquely identifies which stack # a data element belongs to. If this is specified, then this callback is used to determine which stack # each data element is assigned to. Otherwise, the layer data array is used in full for each stack. # * **name** [Function] A callback you define to set the name of a stack that is passed the stack key as an argument. # * **offset** [String, Function] The name or a function for the stacking algorithm used to place the data. # See {https://github.com/mbostock/d3/wiki/Stack-Layout#wiki-offset d3.stack.offset()} for details. # * * `none` - Do not stack the groups. Useful for grouped line charts. # * * `zero` - The default for a zero baseline. # * * `expand` - Normalize all points to range from 0-1. # * **order** [String] Specify the mechanism to order the stacks. # See {https://github.com/mbostock/d3/wiki/Stack-Layout#wiki-order d3.stack.order()} for details. stack_options: undefined # [Array<{c3.Plot.Layer.Stackable.Stack}>] An array of {c3.Plot.Layer.Stackable.Stack stack} # objects that can be used to manually specify the set of stacks. # Stack objects may contain: # * **key** [String] The key for this stack # * **y** [Function] A y accessor to use for this stack overriding the one provided by the chart or layer. # * **data** [Array] Manually specified dataset for this stack instead of using the layer's `data`. # * **name** [String] Name for the stack # * **options** [{c3.Selection.Options}] Options to manually set the **class**, **classes**, # **styles**, **events**, and **title** of just this stack. stacks: undefined # [Boolean] Safe Mode. # Preform additional checks and fix up the data for situations such as: # * Data not sorted along X axis # * Remove data elements where X or Y values are undefined # * Pad missing values where stacks are not defined for all X values. # Note that this mode may cause the indexes passed to the accessors to match the # corrected data instead of the original data array. safe: true # Restack the data based on the **stack** and **stacks** options. _stack: => if @stack_options or @stacks? @stacks ?= [] x_values_set = {} # Helper function to setup the current stack data and populate a shadow structure # to hold the x, y, and y0 positioning so we avoid modifying the user's data. add_value = (stack, datum, i, j)=> x = @x(datum,i); x_values_set[x] = x stack.y = stack.y ? @y ? throw Error "Y accessor must be defined in stack, layer, or chart" y = stack.y(datum, i, j, stack) stack.values.push { x:x, y:y, datum:datum } for stack, j in @stacks stack.name ?= @stack_options?.name? stack.key # Clear any previous stacking stack.values = [] # Shadow array to hold stack positioning # Data was provided manually in the stack definition if stack.data? then for datum, i in stack.data add_value stack, datum, i, j # Data has been provided in @current_data that we need to assign it to a stack if @current_data.length # Use stack_options.key() to assign data to stacks if @stack_options?.key? stack_map = {} stack_index = {} for stack, j in @stacks # Refer to hard-coded stacks if defined if stack_map[stack.key]? then throw Error "Stacks provided with duplicate keys: "+stack.key stack_map[stack.key] = stack stack_index[stack.key] = j for datum, i in @current_data key = @stack_options.key(datum) if stack_map[key]? stack = stack_map[key] j = stack_index[key] else @stacks.push stack = stack_map[key] = { key:key, name:@stack_options.name?(key), current_data:[], values:[] } j = @stacks.length add_value stack, datum, i, j # Otherwise, assign all data to all stacks using each stack's y() accessor else if @stacks? then for stack, j in @stacks for datum, i in @current_data add_value stack, datum, i, j else throw Error "Either stacks or stack_options.key must be defined to create the set of stacks." if @safe # Ensure everything is sorted # NOTE: We sort based on the @h scale in case of ordinal or other odd scales if @h.range()[0] is @h.range()[1] then @h.range [0,1] x_values = c3.array.sort_up (v for k,v of x_values_set), @h for stack in @stacks c3.array.sort_up stack.values, (v)=> @h v.x # Splice in missing data and remove undefined data (Important for D3's stack layout) i=0; while i<x_values.length undef = 0 for stack in @stacks # Check for missing values # Compare using h scale to tolerate values such as Dates stack_h = @h stack.values[i]?.x layer_h = @h x_values[i] if stack_h isnt layer_h if stack_h < layer_h # Check for duplicate X values if @h.domain()[0] is @h.domain()[1] throw Error "Did you intend for an h scale with 0 domain? Duplicate X values, invalid stacking, or bad h scale" else throw Error "Multiple data elements with the same x value in the same stack, or invalid stacking" stack.values.splice i, 0, { x:x_values[i], y:0, datum:null } undef++ # Check for undefined y values else if not stack.values[i].y? stack.values[i].y = 0 undef++ # If item is undefined for all stacks, then remove it completely if undef is @stacks.length stack.values.splice(i,1) for stack in @stacks x_values.splice(i,1) i-- i++ # Prepare array of current data for each stack in case it is needed for binding (used by bar chart) for stack in @stacks stack.current_data = stack.values.map (v)->v.datum # Configure and run the D3 stack layout to generate y0 and y layout data for the elements. if @stack_options?.offset == 'none' for stack in @stacks for value in stack.values value.y0 = 0 else stacker = d3.layout.stack().values (stack)->stack.values if @stack_options?.offset? then stacker.offset @stack_options.offset if @stack_options?.order? then stacker.order @stack_options.order stacker @stacks _update: => # Ensure data is sorted and skip elements that do not have a defined x or y value @current_data = if not @safe then @data else if @data? # TODO: we could try to use this values array later as an optimization and for more # stable i parameters passed to user accessors. However, it will complicate the code. if @y? and not @stacks? and not @stack_options? values = ({x:@x(d,i), y:@y(d,i), datum:d} for d,i in @data) c3.array.sort_up values, (v)=> @h v.x # Use @h to accomodate date types (v.datum for v in values when v.x? and v.y?) else values = ({x:@x(d,i), datum:d} for d,i in @data) if @stacks? or @stack_options? # Sorting handled by _stack() c3.array.sort_up values, (v)=> @h v.x (v.datum for v in values when v.x?) @current_data ?= [] @_stack() @groups = @content.select('g.stack') .bind (@stacks ? [null]), if not @stacks?[0]?.key? then null else (stack)->stack.key .options @stack_options, (if @stacks?.some((stack)->stack.options?) then (stack)->stack.options) .update() _style: (style_new)=> @groups?.style(style_new) min_x: => if not @stacks? then super else d3.min @stacks[0]?.values, (v)-> v.x max_x: => if not @stacks? then super else d3.max @stacks[0]?.values, (v)-> v.x min_y: => if not @stacks? then super else d3.min @stacks, (stack)-> d3.min stack.values, (v)-> v.y0 + v.y max_y: => if not @stacks? then super else d3.max @stacks, (stack)-> d3.max stack.values, (v)-> v.y0 + v.y # A _struct-type_ convention class to describe a stack when manually specifying the set of stacks # to use for a stackable chart layer. class c3.Plot.Layer.Stackable.Stack @version: 0.1 # [String] The key for this stack key: undefined # [Function] A _y accessor_ to use for this stack, overriding the one provided by the chart or layer. y: undefined # [Array] An array of data elements to use for this stack instead of the layer or chart's `data`. data: undefined # [String] Name for the stack name: undefined # [{c3.Selection.Options}] Options to manually set the **class**, **classes**, # **styles**, **events**, and **title** of just this stack. options: undefined constructor: (opt)-> c3.util.extend this, opt ################################################################### # XY Plot Line and Area Layers ################################################################### # Abstract chart layer for the {c3.Plot XY Plot Chart}. # Please instantiate a {c3.Plot.Layer.Line} or {c3.Plot.Layer.Area} # @see c3.Plot.Layer.Line # @see c3.Plot.Layer.Area # # Define an `r` or `a` to create circles at the various data points along the path # with that associated radius or area. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **paths** - There will be an element in paths for each stack in the layer # * **circles** - Circles for each datapoint # * **labels** - Labels for each datapoint # # @abstract # @author Douglas Armstrong class c3.Plot.Layer.Path extends c3.Plot.Layer.Stackable @version: 0.2 type: 'path' # [Function] Factory to generate an SVG path string generator function. _See {https://github.com/mbostock/d3/wiki/SVG-Shapes#path-data-generators} for details. path_generator_factory: undefined # [String] The type of D3 line interpolation to use. _See {https://github.com/mbostock/d3/wiki/SVG-Shapes#area_interpolate d3.svg.area.interpolate} for options._ Some useful examples: # * _linear_ - Straight lines between data points # * _basis_ - Smooth curve based on a B-spline, the curve may not touch the data points # * _cardinal_ - Smooth curve that intersects all data points. # * _step-before_ - A step function where the horizontal segments are to the left of the data points # * _step-after_ - A step function where the horizontal segments are to the right of the data points interpolate: undefined # [Number] The tension value [0,1] for cardinal interpolation. _See {https://github.com/mbostock/d3/wiki/SVG-Shapes#area_tension d3.svg.area.tension}._ tension: undefined # [Function] Accessor function you can return true or false if the data point in data[] is defined or should be skipped. _See {https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-area_defined d3.svg.area.defined}._ # Note that this will cause disjoint paths on either side of the missing element, # it will not render a continuous path that skips the undefined element. For that # behaviour simply enable `safe` mode and have the x or y accessor return undefined. defined: undefined # [Number, Function] Define to create circles at the data points along the path with this radius. r: undefined # [Number, Function] Define to create circles at the data points along the path with this area. # Takes precedence over r. a: undefined # [{c3.Selection.Options}] Options for the svg:path. For example, to enable animations. path_options: undefined # [{c3.Selection.Options}] If circles are created at the data points via `r` or `a`, then this # defines options used to style or extend them. circle_options: undefined # [{c3.Selection.Options}] Create labels for each datapoint with these options label_options: undefined _init: => if not @path_generator_factory? then throw Error "path_generator_factory must be defined for a path layer" @path_generator = @path_generator_factory() _update: (origin)=> if origin isnt 'zoom' super @paths = @groups.inherit('path.scaled').options(@path_options) # Bind the datapoint circles and labels if @r? or @a? @circles = @groups.select('circle').options(@circle_options).animate(origin is 'redraw') .bind(if @stacks? then (stack)->stack.current_data else @current_data).update() if @label_options? @labels = @groups.select('text').options(@label_options).animate(origin is 'redraw') .bind(if @stacks? then (stack)->stack.current_data else @current_data).update() _draw: (origin)=> # Only need to update the paths if the data has changed if origin isnt 'zoom' # Update the path generator based on the current settings if @interpolate? then @path_generator.interpolate @interpolate if @tension? then @path_generator.tension @tension if @defined? then @path_generator.defined @defined # Generate and render the paths. orig_h = @chart.orig_h ? @h # For rendering on the scaled layer @paths.animate(origin is 'redraw').position d: if @stacks? then (stack, stack_idx)=> @path_generator .x (d,i)=> orig_h stack.values[i].x .y (d,i)=> @v (stack.values[i].y0 + stack.values[i].y) .y0? if @baseline? and not stack_idx then (d,i)=> @v c3.functor(@baseline)(d,i) else (d,i)=> @v(stack.values[i].y0) @path_generator(stack.current_data) # Call the generator with this particular stack's data else => @path_generator .x (d,i)=> orig_h @x(d,i) .y (d,i)=> @v @y(d,i) .y0? if @baseline? then (d,i)=> @v c3.functor(@baseline)(d,i) else @height @path_generator(@current_data) # Position the circles @circles?.animate(origin is 'redraw').position cx: (d,i,s)=> @h @x(d,i,s) cy: if @stacks? then (d,i,s)=> values = @stacks[s].values[i]; @v values.y+values.y0 else (d,i)=> @v @y(d,i) r: if not @a? then @r else if typeof @a is 'function' then (d,i,s)=> Math.sqrt( @a(d,i,s) / Math.PI ) else Math.sqrt( @a / Math.PI ) # Set the labels @labels?.animate(origin is 'redraw').position transform: (d,i,s)=> 'translate('+(@h @x(d,i,s))+','+(@v @y(d,i,s))+')' _style: (style_new)=> super @paths.style(style_new) @circles?.style(style_new) @labels?.style(style_new) min_x: => if not @stacks? then (if @data.length then @x @data[0]) else @stacks[0]?.values[0]?.x max_x: => if not @stacks? then (if @data.length then @x @data.slice(-1)[0]) else @stacks[0]?.values.slice(-1)[0]?.x # Line graph layer for the {c3.Plot XY Plot Chart}. Please refer to {c3.Plot.Layer.Path} for documentation. # @see c3.Plot.Layer.Path # @author Douglas Armstrong class c3.Plot.Layer.Line extends c3.Plot.Layer.Path type: 'line' path_generator_factory: d3.svg.line # Area graph layer for the {c3.Plot XY Plot Chart}. Please refer to {c3.Plot.Layer.Path} for documentation. # @see c3.Plot.Layer.Path # @author Douglas Armstrong # @note The input data array should be sorted along the x axis. class c3.Plot.Layer.Area extends c3.Plot.Layer.Path type: 'area' path_generator_factory: d3.svg.area # [Number, Function] Base value or accessor for the bottom of the area chart. # _Defaults to the bottom of the chart._ baseline: undefined ################################################################### # XY Plot Bar Layer ################################################################### # Bar chart layer for the {c3.Plot XY Plot Chart} # # Bar charts may have positive or negative values unless they are stacked, # then they must be positive. # # When an orinal scale is used this layer will adjust it so that it provides padding # so the full bar on the left and right ends are fully visible. With other types of scales # the bars may have arbitrary x values from the user and may overlap. In this case, it is up # to the user to set the domain so bars are fully visible. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **rects** # # @todo Support negative y values for bar layers # @author Douglas Armstrong class c3.Plot.Layer.Bar extends c3.Plot.Layer.Stackable @version: 0.2 type: 'bar' # [Function] A callback to describe a unique key for each data element. # This is useful for animations during a redraw when updating the dataset. key: undefined # [Number, String, Function] Specify the width of the bars. # If this is a number it specifies the bar width in pixels. # If this is a string, such as `50%`, then it can specify the width of the bars as a # percentage of the available space for each bar based on proximity to each neighbor. # If this is a function it can set the width dynamically for each bar. bar_width: "50%" # [{c3.Selection.Options}] Options for the svg:rect's. # The callbacks are called with the user data for the rect as the first argument, the index of that # datum as the second argument, and the index of the stack for this rect as the third argument. # `stack.options` can be used instead to apply the same options to an entire stack. rect_options: undefined _update: => super @rects = @groups.select('rect').options(@rect_options).animate('origin is redraw') .bind((if @stacks? then ((stack)->stack.current_data) else @current_data), @key).update() _draw: (origin)=> baseline = @v(0) # Set bar_width and bar_shift if typeof @bar_width is 'function' bar_width = @bar_width bar_shift = -> bar_width(arguments...) / 2 else bar_width = +@bar_width if !isNaN bar_width # The user provided a simple number of pixels @h.rangeBands? @h.rangeExtent(), 1, 0.5 # Provide padding for an ordinal D3 scale bar_shift = bar_width/2 else # The user provided a percentage if @bar_width.charAt?(@bar_width.length-1) is '%' # Use charAt to confirm this is a string bar_ratio = +@bar_width[..-2] / 100 if isNaN bar_ratio then throw "Invalid bar_width percentage "+@bar_width[0..-2] if @h.rangeBands? # Setup padding for an ordinal D3 scale @h.rangeBands @h.rangeExtent(), 1-bar_ratio, 1-bar_ratio bar_width = @h.rangeBand() bar_shift = 0 else # Dynamically compute widths based on proximity to neighbors bar_width = if @stacks? then (d,i,j)=> values = @stacks[j].values mid = @h values[i].x left = @h if !i then (@chart.orig_h ? @h).domain()[0] else values[i-1].x right = @h if i==values.length-1 then (@chart.orig_h ? @h).domain()[1] else values[i+1].x width = Math.min((mid-left), (right-mid)) * bar_ratio if width >= 0 then width else 0 else (d,i)=> mid = @h @x(d,i) left = @h if !i then (@chart.orig_h ? @h).domain()[0] else @x(@current_data[i-1],i-1) right = @h if i==@current_data.length-1 then (@chart.orig_h ? @h).domain()[1] else @x(@current_data[i+1],i+1) width = Math.min((mid-left), (right-mid)) * bar_ratio if width >= 0 then width else 0 bar_shift = -> bar_width(arguments...) / 2 else throw "Invalid bar_width "+@bar_width if @stacks? x = (d,i,j)=> @h( @stacks[j].values[i].x ) y = (d,i,j)=> @v( @stacks[j].values[i].y0 + @stacks[j].values[i].y ) height = (d,i,j)=> baseline - (@v @stacks[j].values[i].y) else x = (d,i)=> @h @x(d,i) y = (d,i)=> y=@y(d,i); if y>0 then @v(y) else baseline height = (d,i)=> Math.abs( baseline - (@v @y(d,i)) ) @rects.animate(origin is 'redraw').position x: if not bar_shift then x else if typeof bar_shift isnt 'function' then -> x(arguments...) - bar_shift else -> x(arguments...) - bar_shift(arguments...) y: y height: height width: bar_width _style: (style_new)=> super @rects.style(style_new) ################################################################### # XY Plot Straight Line Layers ################################################################### # Straight **horizontal** or **vertical** line layer for the # {c3.Plot XY Plot Chart}. This is an **abstract** layer, please instantiate a # {c3.Plot.Layer.Line.Horizontal} or {c3.Plot.Layer.Line.Vertical} # directly. # # A seperate line is drawn for each data element in the `data` array. # _Set `label_options.text` to define a **label** for each line._ # Straight line layers are not _{c3.Plot.Layer.Stackable stackable}_. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **vectors** # * **lines** # * **labels** # # ## Events # * **dragstart** # * **drag** # * **dragend** # # @abstract # @author Douglas Armstrong class c3.Plot.Layer.Line.Straight extends c3.Plot.Layer @version: 0.1 type: 'straight' # [Function] Optional accessor to identify data elements when changing the dataset key: undefined # [Function] Accessor to get the value for each data element. # _Defaults to the identity function._ value: undefined # [Function] Accessor to determine if data elements are filtered in or not. filter: undefined # [Boolean] Enable lines to be draggable. # The drag event callbacks can be used to adjust the original data values draggable: false # [{c3.Selection.Options}] Options for the svg:g of the vector group nodes. # There is one node per data element. Use this option for animating line movement. vector_options: undefined # [{c3.Selection.Options}] Options for the svg:line lines. line_options: undefined # [{c3.Selection.Options}] Options for the svg:line lines for hidden lines # behind each line that is wider and easier for users to interact with # e.g. for click or drag events. grab_line_options: undefined # [{c3.Selection.Options}] Define this to render labels. Options for the svg:text labels. # This option also takes the following additional properties: # * **alignment** - [String] Alignment of label. # * * `left` or `right` for horizontal lines # * * `top` or `bottom` for vertical lines # * **dx** - [String] Relative placement for the label # * **dy** - [String] Relative placement for the label label_options: undefined _init: => @value ?= (d)-> d # Draggable lines if @draggable # NOTE: Because vertical lines are rotated, we are always dragging `y` self = this @dragger = d3.behavior.drag() drag_value = undefined #drag.origin (d,i)=> { y: @scale @value(d,i) } @dragger.on 'dragstart', (d,i)=> d3.event.sourceEvent.stopPropagation() # Prevent panning in zoomable charts @trigger 'dragstart', d, i @dragger.on 'drag', (d,i)-> domain = (self.chart.orig_h ? self.scale).domain() drag_value = Math.min(Math.max(self.scale.invert(d3.event.y), domain[0]), domain[1]) d3.select(this).attr 'transform', 'translate(0,'+self.scale(drag_value)+')' self.trigger 'drag', drag_value, d, i @dragger.on 'dragend', (d,i)=> @trigger 'dragend', drag_value, d, i _size: => @lines?.all?.attr 'x2', @line_length @grab_lines?.all?.attr 'x2', @line_length @labels?.all?.attr 'x', if @label_options.alignment is 'right' or @label_options.alignment is 'top' then @width else 0 _update: (origin)=> @current_data = if @filter? then (d for d,i in @data when @filter(d,i)) else @data @vectors = @content.select('g.vector').options(@vector_options).animate(origin is 'redraw') .bind(@current_data, @key).update() @lines = @vectors.inherit('line').options(@line_options).update() if @label_options? @label_options.dx ?= '0.25em' @label_options.dy ?= '-0.25em' @labels = @vectors.inherit('text').options(@label_options).update() # Add extra width for grabbable line area if @draggable or @grab_line_options @grab_lines = @vectors.inherit('line.grab') if @grab_line_options then @grab_lines.options(@grab_line_options).update() if @draggable @vectors.new.call @dragger _draw: (origin)=> @vectors.animate(origin is 'redraw').position transform: (d,i)=> 'translate(0,' + (@scale @value(d,i)) + ')' @lines.new.attr 'x2', @line_length @grab_lines?.new.attr 'x2', @line_length if @labels? far_labels = @label_options.alignment is 'right' or @label_options.alignment is 'top' @g.style 'text-anchor', if far_labels then 'end' else 'start' @labels.position dx: if far_labels then '-'+@label_options.dx else @label_options.dx dy: @label_options.dy x: if far_labels then @line_length else 0 _style: (style_new)=> @g.classed 'draggable', @draggable @vectors.style(style_new) @lines.style(style_new) @grab_lines?.style?(style_new) @labels?.style?(style_new) # Horizontal line layer. Please refer to {c3.Plot.Layer.Line.Straight} for documentation. # @see c3.Plot.Layer.Line.Straight class c3.Plot.Layer.Line.Horizontal extends c3.Plot.Layer.Line.Straight type: 'horizontal' _init: => label_options?.alignment ?= 'left' super @scale = @v _size: => @line_length = @width super # Vertical line layer. Please refer to {c3.Plot.Layer.Line.Straight} for documentation. # @see c3.Plot.Layer.Line.Straight class c3.Plot.Layer.Line.Vertical extends c3.Plot.Layer.Line.Straight type: 'vertical' _init: => label_options?.alignment ?= 'top' super @scale = @h _size: => @g.attr transform: 'rotate(-90) translate('+-@height+',0)' @line_length = @height super ################################################################### # XY Plot Region Layers ################################################################### # Render a rectangular region in an {c3.Plot XY Plot Chart}. # # Define `x` and `x2` options for vertical regions, # `y` and `y2` for horizontal regions, or all four for rectangular regions. # # The regions may be enabled to be `draggable` and/or `resizable`. # The chart will move or resize the region interactively, however it is up to # the user code to modify the data elements based on the `drag` or `dragend` # events. These callbacks are called with a structure of the new values and # the data element as parameters. The structure of new values is an object # with `x`, `x2` and `y`, `y2` members. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **regions** # * **rects** # # ## Events # * **dragstart** - called with the data element. # * **drag** - called with the new position and the data element. # * **dragend** - called with the new position and the data element. # # @author Douglas Armstrong class c3.Plot.Layer.Region extends c3.Plot.Layer type: 'region' _init: => if (@x? and !@x2?) or (!@x? and @x2?) or (@y? and !@y2?) or (!@y? and @y2?) throw Error "x and x2 options or y and y2 options must either be both defined or undefined" # Draggable lines if @draggable or @resizable drag_value = undefined origin = undefined self = this @dragger = d3.behavior.drag() .origin (d,i)=> x: if @x? then @h @x d,i else 0 y: if @y? then @v @y d,i else 0 .on 'drag', (d,i)-> h_domain = (self.orig_h ? self.h).domain() v_domain = self.v.domain() if self.x? width = self.x2(d) - self.x(d) x = Math.min(Math.max(self.h.invert(d3.event.x), h_domain[0]), h_domain[1]-width) if self.y? height = self.y2(d) - self.y(d) y = Math.min(Math.max(self.v.invert(d3.event.y), v_domain[0]), v_domain[1]-height) # Run values through scale round-trip in case it is a time scale. drag_value = x: if x? then self.h.invert self.h x x2: if x? then self.h.invert self.h x + width y: if y? then self.v.invert self.v y y2: if y? then self.v.invert self.v y + height if self.x? then d3.select(this).attr 'x', self.h drag_value.x if self.y? then d3.select(this).attr 'y', self.v drag_value.y2 self.trigger 'drag', drag_value, d, i @left_resizer = d3.behavior.drag() .origin (d,i)=> x: @h @x d, i .on 'drag', (d,i)-> h_domain = (self.orig_h ? self.h).domain() x = Math.min(Math.max(self.h.invert(d3.event.x), h_domain[0]), h_domain[1]) x2 = self.x2 d drag_value = x: self.h.invert self.h Math.min(x, x2) x2: self.h.invert self.h Math.max(x, x2) y: if self.y? then self.y(d) y2: if self.y2? then self.y2(d) d3.select(this.parentNode).select('rect').attr x: self.h drag_value.x width: self.h(drag_value.x2) - self.h(drag_value.x) self.trigger 'drag', drag_value, d, i @right_resizer = d3.behavior.drag() .origin (d,i)=> x: @h @x2 d, i .on 'drag', (d,i)-> h_domain = (self.orig_h ? self.h).domain() x = Math.min(Math.max(self.h.invert(d3.event.x), h_domain[0]), h_domain[1]) x2 = self.x d drag_value = x: self.h.invert self.h Math.min(x, x2) x2: self.h.invert self.h Math.max(x, x2) y: if self.y? then self.y(d) y2: if self.y2? then self.y2(d) d3.select(this.parentNode).select('rect').attr x: self.h drag_value.x width: self.h(drag_value.x2) - self.h(drag_value.x) self.trigger 'drag', drag_value, d, i @top_resizer = d3.behavior.drag() .origin (d,i)=> y: @v @y2 d, i .on 'drag', (d,i)-> v_domain = self.v.domain() y = Math.min(Math.max(self.v.invert(d3.event.y), v_domain[0]), v_domain[1]) y2 = self.y d drag_value = x: if self.x? then self.x(d) x2: if self.x2? then self.x2(d) y: self.v.invert self.v Math.min(y, y2) y2: self.v.invert self.v Math.max(y, y2) d3.select(this.parentNode).select('rect').attr y: self.v drag_value.y2 height: self.v(drag_value.y) - self.v(drag_value.y2) self.trigger 'drag', drag_value, d, i @bottom_resizer = d3.behavior.drag() .origin (d,i)=> y: @v @y d, i .on 'drag', (d,i)-> v_domain = self.v.domain() y = Math.min(Math.max(self.v.invert(d3.event.y), v_domain[0]), v_domain[1]) y2 = self.y2 d drag_value = x: if self.x? then self.x(d) x2: if self.x2? then self.x2(d) y: self.v.invert self.v Math.min(y, y2) y2: self.v.invert self.v Math.max(y, y2) d3.select(this.parentNode).select('rect').attr y: self.v drag_value.y2 height: self.v(drag_value.y) - self.v(drag_value.y2) self.trigger 'drag', drag_value, d, i for dragger in [@dragger, @left_resizer, @right_resizer, @top_resizer, @bottom_resizer] dragger .on 'dragstart', (d,i)=> d3.event.sourceEvent.stopPropagation() # Prevent panning in zoomable charts @trigger 'dragstart', d, i .on 'dragend', (d,i)=> @trigger 'dragend', drag_value, d, i @_draw() # reposition the grab lines for the moved region _size: => if not @x? @rects?.all.attr 'width', @width @left_grab_lines?.all.attr 'width', @width @right_grab_lines?.all.attr 'width', @width if not @y? @rects?.all.attr 'height', @height @top_grab_lines?.all.attr 'height', @height @bottom_grab_lines?.all.attr 'height', @height _update: (origin)=> @current_data = if @filter? then (d for d,i in @data when @filter(d,i)) else @data @regions = @content.select('g.region').options(@region_options).animate(origin is 'redraw') .bind(@current_data, @key).update() @rects = @regions.inherit('rect').options(@rect_options).update() if @draggable @rects.new.call @dragger # Add extra lines for resizing regions if @resizable if @x? @left_grab_lines = @regions.inherit('line.grab.left') @left_grab_lines.new.call @left_resizer if @x2? @right_grab_lines = @regions.inherit('line.grab.right') @right_grab_lines.new.call @right_resizer if @y? @top_grab_lines = @regions.inherit('line.grab.top') @top_grab_lines.new.call @top_resizer if @y2? @bottom_grab_lines = @regions.inherit('line.grab.bottom') @bottom_grab_lines.new.call @bottom_resizer _draw: (origin)=> @rects.animate(origin is 'redraw').position x: (d)=> if @x? then @h @x d else 0 width: (d)=> if @x2? then @h(@x2(d))-@h(@x(d)) else @width y: (d)=> if @y2? then @v @y2 d else 0 height: (d)=> if @y? then @v(@y(d))-@v(@y2(d)) else @height if @resizable @left_grab_lines?.animate(origin is 'redraw').position x1: (d)=> @h @x d x2: (d)=> @h @x d y1: (d)=> if @y? then @v @y d else 0 y2: (d)=> if @y2? then @v @y2 d else @height @right_grab_lines?.animate(origin is 'redraw').position x1: (d)=> @h @x2 d x2: (d)=> @h @x2 d y1: (d)=> if @y? then @v @y d else 0 y2: (d)=> if @y2? then @v @y2 d else @height @top_grab_lines?.animate(origin is 'redraw').position x1: (d)=> if @x? then @h @x d else 0 x2: (d)=> if @x2? then @h @x2 d else @width y1: (d)=> @v @y2 d y2: (d)=> @v @y2 d @bottom_grab_lines?.animate(origin is 'redraw').position x1: (d)=> if @x? then @h @x d else 0 x2: (d)=> if @x2? then @h @x2 d else @width y1: (d)=> @v @y d y2: (d)=> @v @y d _style: (style_new)=> @g.classed 'draggable': @draggable 'horizontal': not @x? 'vertical': not @y? @regions.style style_new @rects.style style_new ################################################################### # XY Plot Scatter Layer ################################################################### # Scatter plot layer for the {c3.Plot XY Plot Chart} # # Datapoints include a circle and an optional label. # _Set `label_options.text` to define the label for each point._ # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **points** - Representing svg:g nodes for each datapoint # * **circles** - Representing svg:circle nodes for each datapoint # * **labels** - Representing svg:text labels for each datapoint # @author Douglas Armstrong # @todo Only render datapoints within the current zoomed domain. class c3.Plot.Layer.Scatter extends c3.Plot.Layer @version: 0.1 type: 'scatter' # [Function] Accessor function to define a unique key to each data point. This has performance implications. # _This is required to enable **animations**._ key: undefined # [Function, Number] Accessor or value to set the value for each data point. # This is used when limiting the number of elements. value: undefined # [Function, Number] Accessor or value to set the circle radius r: 1 # [Function, Number] Accessor or value to set the circle area. _Takes precedence over r._ a: undefined # [Boolean] Safe mode will not render data where a positioning accessor returns undefined. # _This may cause the index passed to accessors to not match the original data array._ safe: true # [Function] Accessor to determine if the data point should be drawn or not # _This may cause the index passed to accessors to not match the original data array._ filter: undefined # [Number] Limit the number of data points. # _This may cause the index passed to accessors to not match the original data array._ limit_elements: undefined # [{c3.Selection.Options}] Options for svg:g nodes for each datapoint. point_options: undefined # [{c3.Selection.Options}] Options for the svg:circle of each datapoint circle_options: undefined # [{c3.Selection.Options}] Options for the svg:text lables of each datapoint. label_options: undefined _init: => if not @x? then throw Error "x must be defined for a scatter plot layer" if not @y? then throw Error "y must be defined for a scatter plot layer" if not @h? then throw Error "h must be defined for a scatter plot layer" if not @v? then throw Error "v must be defined for a scatter plot layer" _update: (origin)=> if not @data then throw Error "Data must be defined for scatter layer." # Filter the data for safety @current_data = if @filter? and @key? then (d for d,i in @data when @filter(d,i)) else @data if @safe then @current_data = (d for d in @current_data when ( @x(d)? and @y(d)? and (!@a? or typeof @a!='function' or @a(d)?) and (typeof @r!='function' or @r(d)?) )) # Limit the number of elements? if @limit_elements? if @value? @current_data = @current_data[..] # Copy the array to avoid messing up the user's order c3.array.sort_up @current_data, (d)=> -@value(d) # Sort by negative to avoid reversing array @current_data = @current_data[..@limit_elements] else @current_data = @current_data[..@limit_elements] # Bind and create the elements @points = @content.select('g.point').options(@point_options).animate(origin is 'redraw') .bind(@current_data, @key).update() # If there is no key, then hide the elements that are filtered if @filter? and not @key? @points.all.attr 'display', (d,i)=> if not @filter(d,i) then 'none' # Add circles to the data points @circles = @points.inherit('circle').options(@circle_options).animate(origin is 'redraw').update() # Add labels to the data points if @label_options? @labels = @points.inherit('text').options(@label_options).update() _draw: (origin)=> @points.animate(origin is 'redraw').position transform: (d,i)=> 'translate('+(@h @x(d,i))+','+(@v @y(d,i))+')' @circles.animate(origin is 'redraw').position r: if not @a? then @r else if typeof @a is 'function' then (d,i)=> Math.sqrt( @a(d,i) / Math.PI ) else Math.sqrt( @a / Math.PI ) _style: (style_new)=> @points.style(style_new) @circles.style(style_new) @labels?.style(style_new) ################################################################### # XY Plot Swimlane Layers ################################################################### # Base abstract class for {c3.Plot XY Plot} {c3.Plot.Layer layers} with horizontal swim lanes. # Swimlanes are numbered based on the vertical scale domain for the layer. # The first entry in the domain is the top swimlane and the last entry is the bottom swimlane plus 1. # If the first and last domain values are equal, then there are no swimlanes rendered. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **lanes** - svg:rect's for each swimlane # * **tip** - HTML hover content # @abstract # @author Douglas Armstrong class c3.Plot.Layer.Swimlane extends c3.Plot.Layer type: 'swimlane' # [String] `top` for 0 to be at the top, `bottom` for the bottom. # Swimlanes default to 0 at the top. v_orient: 'top' # [Number] Height of a swimlane in pixels. # Chart height will be adjusted if number of swimlanes changes in a redraw() dy: undefined # [Function] Provide HTML content for a hover div when mousing over the layer # This callback will be called with the datum and index of the item being hovered over. # It will be called with null when hovering over the layer but not any data items. hover: undefined # [{c3.Selection.Options}] Options for the lane svg:rect nodes for swimlanes lane_options: undefined _init: => if @lane_options? then @lanes = @content.select('rect.lane',':first-child').options(@lane_options) # Support html hover tooltips if @hover? anchor = d3.select(@chart.anchor) @tip = c3.select( anchor, 'div.c3.hover' ).singleton() layer = this mousemove = -> [layerX,layerY] = d3.mouse(this) # Get swimlane and ensure it is properly in range (mouse may be over last pixel) swimlane = Math.floor layer.v.invert layerY swimlane = Math.min swimlane, Math.max layer.v.domain()[0], layer.v.domain()[1]-1 x = layer.h.invert layerX hover_datum = layer._hover_datum(x, swimlane) hover_html = (c3.functor layer.hover)( hover_datum, (if hover_datum then layer.data.indexOf(hover_datum) else null), swimlane ) if not hover_html layer.tip.all.style 'display', 'none' else layer.tip.all.html hover_html layer.tip.all.style display: 'block' left: d3.event.clientX+'px' top: d3.event.clientY+'px' # Manage tooltip event handlers, disable while zooming/panning @chart.content.all.on 'mouseleave.hover', => layer.tip.all.style 'display', 'none' @chart.content.all.on 'mousedown.hover', => layer.tip.all.style 'display', 'none' @chart.content.all.on 'mousemove.hover', null @chart.content.all.on 'mouseup.hover', => @chart.content.all.on 'mousemove.hover', mousemove @chart.content.all.on 'mouseenter.hover', => if !d3.event.buttons then @chart.content.all.on 'mousemove.hover', mousemove @chart.content.all.on 'mousemove.hover', mousemove _size: => # If @dy is not defined, we determine it based on the chart height if not @y? then @dy = @height else @dy ?= Math.round @height / (Math.abs(@v.domain()[1]-@v.domain()[0])) # If a swimlane starts at the bottom, then shift up by dy because SVG always # renders the height of element downward. @g.attr 'transform', if @v_orient is 'bottom' then 'translate(0,-'+@dy+')' else '' _update: => # Support constant values and accessors @x = c3.functor @x @dx = c3.functor @dx @lanes?.bind([@v.domain()[0]...@v.domain()[1]]).update() # Update chart height to fit current number of swimlanes based on current v domain if @y? then @chart.size null, @dy*(Math.abs(@v.domain()[1]-@v.domain()[0])) + @chart.margins.top + @chart.margins.bottom _draw: (origin)=> if origin is 'resize' or origin is 'render' @lanes?.position y: (lane)=> @v lane width: @chart.orig_h.range()[1] height: @dy _style: => @lanes?.style() ################################################################### # XY Plot Segment Swimlane Layer ################################################################### # A {c3.Plot.Layer.Swimlane swimlane layer} for drawing horizontal segments in each swimlane. # # _Set `label_options.text` to define labels for the segments._ # The following {c3.Selection} members are made available if appropriate: # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **rects** - svg:rect for each segment # @todo Better threshold for determining which segments get labels. _Currently it is any segment > 50 pixels wide._ # @author Douglas Armstrong class c3.Plot.Layer.Swimlane.Segment extends c3.Plot.Layer.Swimlane @version: 0.1 type: 'segment' # **REQUIRED** [Function] Accessor to get the width of the segment dx: null # [Function] Key accessor to uniquely identify the segment. # Defining this improves performance for redraws. key: undefined # [Function] Accessor to determine if an element should be rendered filter: undefined # [Function] Value accessor for each segment. Used when limiting the number of elements. _Defaults to dx._ value: undefined # [Number] Specifies the maximum number of segments this layer will draw. Smaller segments are elided first. limit_elements: undefined # [{c3.Selection.Options}] Options for the svg:rect nodes for each segment rect_options: undefined # [{c3.Selection.Options}] Options for the label svg:text nodes for each segment label_options: undefined # IE10/11 doesn't support vector-effects: non-scaling-stroke, so avoid using scaled SVG. # This is a performance hit, because then we have to adjust the position of all rects for each redraw # TODO: Investigate if they added support for this in Edge. #scaled = !window.navigator.userAgent.match(/MSIE|Trident/) # MSIE==IE10, Trident==IE11, Edge==Edge # [3/18/2016] Disable the SVG scaled layer optimization completely for now. # If there are very large domains (e.g. a billion) then there is a floating-point precision problem # relying on SVG transformations to do the scaling/translation. # This doesn't seem to be a problem if we do the scaling ourselves in JavaScript. scaled = false _init: => super @g.classed 'segment', true # Manually do this so inherited types also have this class if scaled then @scaled_g = @g.append('g').attr('class','scaled') @rects_group = c3.select((@scaled_g ? @g),'g.segments').singleton() if @label_options? then @labels_clip = c3.select(@g,'g.labels').singleton().select('svg') _hover_datum: (x, swimlane)=> right = @h.invert @h(x)+1 # Get the pixel width for datum,idx in @current_data if (!@y? or @y(datum)==swimlane) and (_x=@x(datum)) <= right and x <= _x+@dx(datum) then break return if idx==@current_data.length then null else datum _update: => super # Pull filtered data elements @current_data = if not @filter? then @data else (d for d,i in @data when @filter(d,i)) # Pre-sort data by "value" for limiting to the most important elements if @limit_elements? if not @filter? then @current_data = @current_data[..] c3.array.sort_down @current_data, (@value ? @dx) _draw: (origin)=> super # Gather data for the current viewport domain [left_edge, right_edge] = @h.domain() half_pixel_width = (right_edge-left_edge) / ((@h.range()[1]-@h.range()[0]) || 1) / 2 data = [] for datum in @current_data when (x=@x(datum)) < right_edge and (x+(dx=@dx(datum))) > left_edge if dx < half_pixel_width if @limit_elements? then break else continue data.push datum if data.length == @limit_elements then break # Bind here because the current data set is dynamic based on zooming @rects = @rects_group.select('rect.segment').options(@rect_options).bind(data, @key).update() # Position the rects h = if @scaled_g? then (@chart.orig_h ? @h) else @h zero_pos = h(0) (if origin is 'resize' then @rects.all else @rects.new).attr 'height', @dy (if !scaled or !@key? or origin=='resize' or (origin=='redraw' and this instanceof c3.Plot.Layer.Swimlane.Flamechart) then @rects.all else @rects.new).attr x: (d)=> h @x(d) width: (d)=> (h @dx(d)) - zero_pos y: if not @y? then 0 else (d)=> @v @y(d) # Bind and render lables here (not in _update() since the set is dynamic based on zooming and resizing) if @label_options? # Create labels in a nested SVG node so we can crop them based on the segment size. zero_pos = @h(0) current_labels = (datum for datum in data when (@h @dx datum)-zero_pos>50) @labels_clip.bind(current_labels, @key) @labels = @labels_clip.inherit('text').options(@label_options).update() (if origin is 'resize' then @labels_clip.all else @labels_clip.new).attr 'height', @dy @labels_clip.position x: (d)=> @h @x(d) y: if not @y? then 0 else (d,i)=> @v @y(d,i) width: (d)=> (@h @dx(d)) - zero_pos self = this (if origin is 'resize' then @labels.all else @labels.new).attr 'y', self.dy/2 @labels.position x: (d)-> x = self.x(d) dx = self.dx(d) left = Math.max x, self.h.domain()[0] right = Math.min x+dx, self.h.domain()[1] return self.h( (right-left)/2 + (left-x) ) - zero_pos # x: (d)-> # x = self.x(d) # dx = self.dx(d) # left = Math.max x, self.h.domain()[0] # right = Math.min x+dx, self.h.domain()[1] # # NOTE: This is expensive. Chrome was faster with offsetWidth, but Firefox and IE11 didn't support it # text_width = this.offsetWidth ? this.getBBox().width # if self.h(right-left)-zero_pos > text_width # return self.h( (right-left)/2 + (left-x) ) - zero_pos - (text_width/2) # else # return if x < left then self.h(left-x)-zero_pos+1 else 1 else c3.select(@g,'g.labels').all.remove() delete @labels # Style any new elements we added by resizing larger that allowed new relevant elements to be drawn if origin is 'resize' and (not @rects.new.empty() or (@labels? and not @labels.new.empty())) @_style true _style: (style_new)=> super @rects.style(style_new) @labels?.style(style_new) ################################################################### # Flamechart ################################################################### # A {c3.Plot.Layer.Swimlane swimlane layer} for rendering _flamecharts_ or _flamegraphs_. # # In C3, both a {c3.Plot.Layer.Swimlane.Flamechart Flamechart} and an # {c3.Plot.Layer.Swimlane.Icicle Icicle} can actually grow either up or down # depending if you set `v_orient` as `top` or `bottom`. # A _Flamechart_ defaults to growing up and an _Icicle_ defaults to growing down. # In C3, a {c3.Plot.Layer.Swimlane.Flamechart Flamechart} visualizes a timeline # of instances of nested events over time, while an {c3.Plot.Layer.Swimlane.Icicle Icicle} # visualizes an aggregated tree hierarchy of nodes. The {c3.Polar.Layer.Sunburst Sunburst} # is the equivalent of an _Icicle_ rendered on a polar axis. # # A `key()` is required for this layer. # You should not define `y`, but you must define a `x`, `dx`, and `dy`. # # @author Douglas Armstrong class c3.Plot.Layer.Swimlane.Flamechart extends c3.Plot.Layer.Swimlane.Segment @version: 0.1 type: 'flamechart' # [String] `top` for 0 to be at the top, `bottom` for the bottom. # Flamechart defaults to bottom-up. v_orient: 'bottom' _init: => super if not @key? then throw Error "`key()` accessor function is required for Flamechart layers" if not @dy? then throw Error "`dy` option is required for Flamechart layers" if @y? then throw Error "`y` option cannot be defined for Flamechart layers" @y = (d)=> @depths[@key d] @depths = {} _update: (origin)=> super # Compute depths for each data element data = @current_data[..] c3.array.sort_up data, @x max_depth = 0 stack = [] for datum in data frame = x: @x datum dx: @dx datum while stack.length and frame.x >= (_frame=stack[stack.length-1]).x + _frame.dx stack.length-- stack.push frame max_depth = Math.max max_depth, stack.length # stack.length is starting from 0, so don't reduce by one. @depths[@key datum] = stack.length - 1 # Set the vertical domain and resize chart based on maximum flamechart depth @v.domain [0, max_depth] c3.Plot.Layer.Swimlane::_update.call this, origin ################################################################### # Icicle ################################################################### # A {c3.Plot.Layer.Swimlane swimlane layer} for rendering _icicle_ charts. # # In C3, both a {c3.Plot.Layer.Swimlane.Flamechart Flamechart} and an # {c3.Plot.Layer.Swimlane.Icicle Icicle} can actually grow either up or down # depending if you set `v_orient` as `top` or `bottom`. # A _Flamechart_ defaults to growing up and an _Icicle_ defaults to growing down. # In C3, a {c3.Plot.Layer.Swimlane.Flamechart Flamechart} visualizes a timeline # of instances of nested events over time, while an {c3.Plot.Layer.Swimlane.Icicle Icicle} # visualizes an aggregated tree hierarchy of nodes. The {c3.Polar.Layer.Sunburst Sunburst} # is the equivalent of an _Icicle_ rendered on a polar axis. # # A `key()` is required for this layer. # You should not define `x` or `y`, but you must define `dy`. # Specify a callback for either `parent_key`, # `children`, or `children_keys` to describe the hierarchy. # If using `parent_key` or `children_keys` the `data` array shoud include all nodes, # if using `children` it only should include the root nodes. # Define either `value()` or `self_value()` to value the nodes in the hierarchy. # # If you care about performance, you can pass the # parameter `revalue` to `redraw('revalue')` if you are keeping the same dataset # hierarchy, and only changing the element's values. # The Icicle layer can use a more optimized algorithm in this situation. # # ## Events # * **rebase** Called with the datum of a node when it becomes the new root # or with `null` if reverting to the top of the hierarchy. # # @author Douglas Armstrong class c3.Plot.Layer.Swimlane.Icicle extends c3.Plot.Layer.Swimlane @version: 0.1 type: 'icicle' # **REQUIRED** [Function] Accessor function to define a unique key for each data element. # _This has performance implications and is required for some layers and **animations**._ key: undefined # [Function] Accessor to get the "_total_" value of the data element. # That is the total value of the element itself inclusive of all of it's children's value. # You can define either _value_ or _self_value_. value: undefined # [Function] The `value` accessor defines the "_total_" value for an element, that is the value of # the element itself plus that of all of its children. If you know the "self" value of an # element without the value of its children, then define this callback accessor instead. # The `value` option will then also be defined for you, which you can use to get the total value # of an element after the layer has been drawn. self_value: undefined # [Function] A callback that should return the key of the parent of an element. # It is called with a data element as the first parameter. parent_key: undefined # [Function] A callback that should return an array of child keys of an element. # The returned array may be empty or null. # It is called with a data element as the first parameter. children_keys: undefined # [Function] A callback that should return an array of children elements of an element. # The returned array may be empty or null. # It is called with a data element as the first parameter. children: undefined # [Boolean, Function] How to sort the partitioned tree segments. # `true` sorts based on _total_ value, or you can define an alternative # accessor function to be used for sorting. sort: false # [Number] Limit the number of data elements to render based on their value. # _This affects the callback index parameter_ limit_elements: undefined # [Number] Don't bother rendering segments whose value is smaller than this # percentage of the current domain focus. (1==100%) limit_min_percent: 0.001 # Data element that represents the root of the hierarchy to render. # If this is specified, then only this root and its parents and children will be rendered # When {c3.Plot.Layer.Icicle#rebase rebase()} is called or a node is clicked on # it will animate the transition to a new root node, if animation is enabled. root_datum: null # [{c3.Selection.Options}] Options for the svg:rect nodes for each segment rect_options: undefined # [{c3.Selection.Options}] Options for the label svg:text nodes for each segment label_options: undefined _init: => super if not @key? then throw Error "`key()` accessor function is required for Icicle layers" if not @dy? then throw Error "`dy` option is required for Icicle layers" if @x? then throw Error "`x` option cannot be defined for Icicle layers" if @y? then throw Error "`y` option cannot be defined for Icicle layers" @y = (datum)=> @nodes[@key datum].y1 @segments_g = c3.select(@g, 'g.segments').singleton() @segment_options = { events: { click: (d)=> @rebase if d isnt @root_datum then d else (if @parent_key? then @nodes[@parent_key d] else @nodes[@key d].parent)?.datum } } @label_clip_options = {} if @label_options? @label_options.animate ?= @rect_options.animate @label_options.duration ?= @rect_options.duration @label_clip_options.animate ?= @rect_options.animate @label_clip_options.duration ?= @rect_options.duration _hover_datum: (x, swimlane)=> right = @h.invert @h(x)+1 # Get the pixel width for key,node of @nodes if node.y1 is swimlane and node.x1 <= right and x <= node.x2 return node.datum return null _update: (origin)=> super # Construct the tree hierarchy if origin isnt 'revalue' and origin isnt 'rebase' @tree = new c3.Layout.Tree key: @key, parent_key: @parent_key, children_keys: @children_keys, children: @children value: @value, self_value: @self_value @nodes = @tree.construct @data # Set the vertical domain and resize chart based on maximum flamechart depth @v.domain [0, d3.max Object.keys(@nodes), (key)=> @nodes[key].y2] c3.Plot.Layer.Swimlane::_update.call this, origin # Compute the "total value" of each node if origin isnt 'rebase' @value = @tree.revalue() # Partition the arc segments based on the node values # We need to do this even for 'rebase' in case we shot-circuited previous paritioning @current_data = @tree.layout( if origin isnt 'revalue' and origin isnt 'rebase' then @sort else false @limit_min_percent @root_datum ) # Limit the number of elements to bind to the DOM if @current_data.length > @limit_elements c3.array.sort_up @current_data, @value # sort_up is more efficient than sort_down @current_data = @current_data[-@limit_elements..] # Bind data elements to the DOM @segment_options.animate = @rect_options?.animate @segment_options.animate_old = @rect_options?.animate @segment_options.duration = @rect_options?.duration @segments = @segments_g.select('g.segment').options(@segment_options) .animate(origin is 'redraw' or origin is 'revalue' or origin is 'rebase') .bind(@current_data, @key).update() @rect_options?.animate_old ?= @rect_options?.animate @rects = @segments.inherit('rect').options(@rect_options).update() if @label_options? @label_clip_options.animate_old = @label_options?.animate @label_clips = @segments.inherit('svg.label').options(@label_clip_options) _draw: (origin)=> super # Set the horizontal domain based on the root node. prev_h = @h.copy() prev_zero_pos = prev_h(0) root_node = @nodes[@key @root_datum] if @root_datum? @h.domain [root_node?.x1 ? 0, root_node?.x2 ? 1] zero_pos = @h(0) # Position the segments. # Place any new segments where they would have been if not decimated. (if origin is 'resize' then @rects.all else @rects.new).attr 'height', @dy @rects.animate(origin is 'redraw' or origin is 'revalue' or origin is 'rebase').position { x: (d)=> @h @nodes[@key d].x1 y: (d)=> @v @nodes[@key d].y1 width: (d)=> @h((node=@nodes[@key d]).x2 - node.x1) - zero_pos }, { x: (d)=> prev_h @nodes[@key d].px1 y: (d)=> @v @nodes[@key d].py1 width: (d)=> prev_h((node=@nodes[@key d]).px2 - node.px1) - prev_zero_pos } if @label_options? (if origin is 'resize' then @rects.all else @rects.new).attr 'height', @dy @label_clips.animate(origin is 'redraw' or origin is 'revalue' or origin is 'rebase').position { x: (d)=> @h @nodes[@key d].x1 y: (d)=> @v @nodes[@key d].y1 width: (d)=> @h((node=@nodes[@key d]).x2 - node.x1) - zero_pos }, { x: (d)=> prev_h @nodes[@key d].px1 y: (d)=> @v @nodes[@key d].py1 width: (d)=> prev_h((node=@nodes[@key d]).px2 - node.px1) - prev_zero_pos } # Bind and position labels for larger segments. @labels = c3.select( @label_clips.all.filter((d)=> @h((node=@nodes[@key d]).x2 - node.x1) - zero_pos >= 50) ).inherit('text', 'restore') .options(@label_options).update() .animate(origin is 'redraw' or origin is 'revalue' or origin is 'rebase').position y: @dy / 2 x: (d)=> node = @nodes[@key d] left = Math.max node.x1, @h.domain()[0] right = Math.min node.x2, @h.domain()[1] return @h( (right-left)/2 + (left-node.x1) ) - zero_pos # Remove any stale labels from segments that are now too small @segments.all .filter((d)=> @h((node=@nodes[@key d]).x2 - node.x1) - zero_pos < 50) .selectAll('text') .transition('fade').duration(@label_options.duration).style('opacity',0) .remove() else @segments.all.selectAll('text').remove() delete @labels # Style any new elements we added by resizing larger that allowed new relevant elements to be drawn if origin is 'resize' and (not @rects.new.empty() or (@labels? and not @labels.new.empty())) @_style true _style: (style_new)=> super @rects.style(style_new) @labels?.style(style_new) # Navigate to a new root node in the hierarchy representing the `datum` element rebase: (@root_datum)=> @trigger 'rebase_start', @root_datum @chart.redraw 'rebase' # redraw all layers, since the scales will change @trigger 'rebase', @root_datum # Navigate to a new root node in the hierarchy represented by `key` rebase_key: (root_key)=> @rebase @nodes[root_key]?.datum ################################################################### # XY Plot Sampled Swimlane Layers ################################################################### # A {c3.Plot.Layer.Swimlane swimlane layer} that will sample for each pixel in each swimlane. # @abstract # @author Douglas Armstrong class c3.Plot.Layer.Swimlane.Sampled extends c3.Plot.Layer.Swimlane @version: 0.0 type: 'sampled' # **REQUIRED** [Function] Accessor to get the width of the segment dx: null # [Function] Callback to determine if the data element should be rendered or not filter: undefined # [Boolean] If safe mode is off then it is assumed the data is sorted by the x-axis safe: true _hover_datum: (x, swimlane)=> data = @swimlane_data[swimlane] right = @h.invert @h(x)+1 # Get the pixel width idx = d3.bisector(@x).right(data, x) - 1 return if idx<0 then null else if x < @x(datum=data[idx])+@dx(datum) then datum else if ++idx<data.length and @x(datum=data[idx]) <= right then datum else null _update: => super # Arrange data by swimlane and remove filtered items @swimlane_data = [] @swimlane_data[swimlane] = [] for swimlane in [@v.domain()[0]...@v.domain()[1]] [top_edge, bottom_edge] = @v.domain() for datum, i in @data when (!@filter? or @filter(datum,i)) swimlane = @y datum, i if top_edge <= swimlane < bottom_edge then @swimlane_data[swimlane].push datum # Sort data in safe mode if @safe c3.array.sort_up(data,@x) for data in @swimlane_data _sample: (sample)=> # Sample data points for each pixel in each swimlane bisector = d3.bisector(@x).right for swimlane in [@v.domain()[0]...@v.domain()[1]] v = @v swimlane data = @swimlane_data[swimlane] if not data.length then continue # Optimized to find the left starting point prev_idx = bisector(data, @h.domain()[0]) if not prev_idx pixel = Math.round @h @x @data[prev_idx] else prev_idx-- pixel = if @h(@x(@data[prev_idx])+@dx(@data[prev_idx])) > 0 then 0 else Math.round @h @x data[prev_idx] # Iterate through each pixel in this swimlane while pixel < @width x = @h.invert(pixel) # Find the next data element for this pixel, or skip to the next pixel if there is a gap idx = prev_idx while idx < data.length datum = data[idx] prev_idx = idx if (datum_x=@x(datum)) > x pixel = Math.round @h datum_x break if x <= datum_x+@dx(datum) then break idx++ if idx==data.length then break sample pixel, v, datum pixel++ return # avoid returning a comprehension # A {c3.Plot.Layer.Swimlane.Sampled sampled swimlane layer} implemented via SVG lines # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **lines** - svg:rect's for each swimlane # @todo Optimize by generating pixel data array once in _size() and reusing it in _draw() class c3.Plot.Layer.Swimlane.Sampled.SVG extends c3.Plot.Layer.Swimlane.Sampled @version: 0.0 type: 'svg' # [{c3.Selection.Options}] Options for the svg:line's in each swimlane line_options: undefined _draw: (origin)=> super # Gather sampled pixels to bind to SVG linex current_data = [] pixels = [] @_sample (x,y,datum)-> current_data.push datum pixels.push { x:x, y:y } # Bind data in _draw without a key because it is based on pixel sampling @lines = c3.select(@g,'line').options(@line_options).bind(current_data).update() @lines.position x1: (d,i)-> pixels[i].x + 0.5 # Center line on pixels to avoid anti-aliasing x2: (d,i)-> pixels[i].x + 0.5 y1: if not @y? then 0 else (d,i)-> pixels[i].y - 0.5 y2: if not @y? then @height else (d,i)=> pixels[i].y + @dy - 0.5 _style: => super @lines.style() # A {c3.Plot.Layer.Swimlane.Sampled sampled swimlane layer} implemented via HTML5 Canvas # This layer supports `line_options.styles.stroke` and HTML `hover` "tooltips". class c3.Plot.Layer.Swimlane.Sampled.Canvas extends c3.Plot.Layer.Swimlane.Sampled @version: 0.0 type: 'canvas' # [{c3.Selection.Options}] Options for the svg:line's in each swimlane line_options: undefined _init: => super foreignObject = c3.select(@g,'foreignObject').singleton().position({height:'100%',width:'100%'}) @canvas = foreignObject.select('xhtml|canvas').singleton() #@canvas = document.createElement('canvas') #@image = c3.select(@g,'svg|image').singleton() _size: => super @canvas.position height: @height width: @width __draw: => context = @canvas.node().getContext('2d') context.clearRect 0,0, @width,@height # Translate by 0.5 so lines are centered on pixels to avoid anti-aliasing which causes transparency context.translate 0.5, 0.5 # Sample pixels to render onto canvas stroke = c3.functor @line_options?.styles?.stroke @_sample (x,y,datum)=> context.beginPath() context.moveTo x, y context.lineTo x, y+@dy context.strokeStyle = stroke datum context.stroke() context.translate -0.5, -0.5 #@image.all.attr('href',@canvas.toDataURL('image/png')) #@image.all.node().setAttributeNS('http://www.w3.org/1999/xlink','xlink:href',@canvas.toDataURL('image/png')) _draw: (origin)=> super; @__draw(origin) _style: (style_new)=> super; if not style_new then @__draw('restyle') # For the sampled layer, draw and style are the same. By default zoom does both, so just do one. zoom: => @__draw('zoom') #################################################################### ## XY Plot Decimated Layer #################################################################### # ## A decimated layer may be created to assist certain layer types to manage large datasets. ## When using a decimated layer pass into the constructor an array of the data at different ## detail granularities as well as a layer object instance that will be used as a "prototype" to ## construct a different layer for each detail level of data. This layer will only show one ## of the levels at a time and will automatically transition between them as the user zooms in and out. ## ## _When using a decimated layer, the **data** option does not need to be set for the layer prototype._ ## @example Creating a decimated layer ## mychart = new c3.Plot.horiz_zoom { ## anchor: '#chart_div' ## h: d3.scale.linear().domain [0, 1] ## v: d3.scale.linear().domain [0, 100] ## x: (d)-> d.x ## layers: [ ## new c3.Layer.decimated mylevels, new c3.Layer.area { ## y: (d)-> d.y ## interpolate: 'basis' ## } ## ] ## } ## mychart.render() ## @todo Should this be implemented as a mix-in instead? ## @todo A built-in helper for users to construct decimated groups using CrossFilter ## @author Douglas Armstrong #class c3.Plot.Layer.Decimated extends c3.Plot.Layer # @version: 0.1 # type: 'decimated' # # # [Number] The maximum number of data elements to render at a given time when preparing sections for smooth panning. # renderport_elements: 8000 # # [Number] If a decimated element spans more than this number of pixels after zooming then switch to the next level of detail. # pixels_per_bucket_limit: 2 # # # @param levels [Array] An Array of detail levels. Each entry in the array should be an array of data elements. # # Each level should also add a **granulairty** property which specified how many X domain units are combined into a single element for this level of detail. # # @param proto_layer [c3.Plot.Layer] A layer instance to use as a prototype to make layers for each level of detail. # constructor: (@levels, @proto_layer)-> ## @type += ' '+@proto_layer.type # for level, i in @levels # level.index = i # level.renderport = [0,0] # # _init: => # for level, i in @levels # level.layer = new @proto_layer.constructor() # c3.util.defaults level.layer, @proto_layer # level.layer.data = level # level.layer.g = @g.append('g').attr('class', 'level _'+i+' layer') # level.layer.init @chart # # _size: => # for level in @levels # level.layer.size @width, @height # # _update: => # # Invalidate the non-visible levels # for level in @levels when level isnt @current_level # level.renderport = [0,0] # @current_level?.layer.update() # # _draw: => # if not @current_level? then @zoom() # else @current_level.layer.draw() # # zoom: => # # Find the optimal decimation level for this viewport # view_width = @chart.h.domain()[1] - @chart.h.domain()[0] # for level in @levels # visible_buckets = view_width / level.granularity # if visible_buckets*@pixels_per_bucket_limit > @width # new_level = level # break # if !new_level? then new_level = @levels[@levels.length-1] # # # Did we change decimation levels? # if @current_level != new_level # @current_level = new_level # @g.selectAll('g.level').style('display','none') # @g.select('g.level[class~=_'+@current_level.index+']').style('display',null) # # # Determine if current viewport is outside current renderport and we need to redraw # if @chart.h.domain()[0] < @current_level.renderport[0] or # @chart.h.domain()[1] > @current_level.renderport[1] # # # Limit number of elements to render, centered on the current viewport # center = (@chart.h.domain()[0]+@chart.h.domain()[1]) / 2 # bisector = d3.bisector (d)->d.key # center_element = bisector.left @current_level, center # element_domain = [] # element_domain[0] = center_element - @renderport_elements/2 - 1 # element_domain[1] = center_element + @renderport_elements/2 # if element_domain[0]<0 then element_domain[0] = 0 # if element_domain[1]>@current_level.length-1 then element_domain[1] = @current_level.length-1 # # @current_level.renderport = (@current_level[i].key for i in element_domain) # # # Swap data for the new renderport and redraw # @current_level.layer.data = @current_level[element_domain[0]..element_domain[1]] # @current_level.layer.redraw()
210528
# c3 Visualization Library # Layers for XY Plots ################################################################### # XY Plot Chart Layers ################################################################### # The root abstract class of layers for the {c3.Plot c3 XY Plot Chart} # # ## Internal Interface # The internal interface that plot layers can implement essentially match the {c3.Base} internal abstract interface: # * **{c3.base#init init()}** # * **{c3.base#size size()}** # * **{c3.base#update update()}** # * **{c3.base#draw draw()}** # * **{c3.base#style style()}** # # An additional method is added: # * **zoom()** - Called when the chart is zoomed or panned. # # ## Extensibility # Each layer has the following members added: # * **chart** - Reference to the {c3.Plot XY Plot Chart} this layer belongs to # * **content** - A {c3.Selection selection} of the layer content # * **g** - A {https://github.com/mbostock/d3/wiki/Selections D3 selection} for the SVG g node for this layer # * **width** - width of the layer # * **height** - height of the layer # # @method #on(event, handler) # Register an event handler to catch events fired by the visualization. # @param event [String] The name of the event to handle. _See the Exetensibility and Events section for {c3.base}._ # @param handler [Function] Callback function called with the event. The arguments passed to the function are event-specific. # # Items should be positioned on the the layer using the layer's `h` and `v` scales. # As a performance optimization some layers may create a g node with the `scaled` class. # When the plot is zoomed then this group will have a transform applied to reflect the zoom so # individual elements do not need to be adjusted. Please use the `chart.orig_h` scale in this case. # Not that this approach does not work for many circumstances as it affects text aspect ratio, # stroke widths, rounding errors, etc. # @abstract # @author <NAME> class c3.Plot.Layer @version: 0.2 c3.Layer = this # Shortcut for accessing plot layers. type: 'layer' @_next_uid: 0 # [Array] Data for this layer _This can be set for each individual layer or a default for the entire chart._ data: undefined # [String] User name for this layer. This is used in legends, for example. name: undefined # [String] CSS class to assign to this layer for user style sheets to customize class: undefined # [Boolean] If true this layer is considered to have "static" data and will not update when {c3.Base#redraw redraw()} is called. static_data: false # [{https://github.com/mbostock/d3/wiki/Scales d3.scale}] Scale for the _vertical_ Y axis for this layer. # Please set the _domain()_, c3 will set the _range()_. # _The vertical scale may be set for the entire chart instead of for each layer._ h: undefined # [{https://github.com/mbostock/d3/wiki/Scales d3.scale}] Scale for the _vertical_ Y axis for this layer. # Please set the _domain()_, c3 will set the _range()_. # _The vertical scale may be set for the entire chart instead of for each layer._ v: undefined # [Function] An accessor function to get the X value from a data item. # _This can be set for each individual layer or a default for the entire chart._ # Some plots support calling this accessor with the index of the data as well as the datum itself. x: undefined # [Function] An accessor function to get the Y value from a data item. # _This can be set for each individual layer or a default for the entire chart._ # Some plots support calling this accessor with the index of the data as well as the datum itself. y: undefined # [String] `left` for 0 to be at the left, `right` for the right. h_orient: undefined # [String] `top` for 0 to be at the top, `bottom` for the bottom. v_orient: undefined # [{c3.Selection.Options}] Options to set the **class**, **classes**, **styles**, # **events**, and **title** for this layer. options: undefined # [Object] An object to setup event handlers to catch events triggered by this c3 layer. # The keys represent event names and the values are the cooresponding handlers. handlers: undefined constructor: (opt)-> c3.util.extend this, new c3.Dispatch c3.util.extend this, opt @uid = c3.Plot.Layer._next_uid++ # Internal function for the Plot to prepare the layer. init: (@chart, @g)=> @trigger 'render_start' @data ?= @chart.data @h ?= @chart.h @v ?= @chart.v @x ?= @chart.x @y ?= @chart.y @h_orient ?= @chart.h_orient @v_orient ?= @chart.v_orient if @class? then @g.classed @class, true if @handlers? then @on event, handler for event, handler of @handlers @content = c3.select(@g) # Apply classes to layer g nodes based on the `type` of the layer object hierarchy prototype = Object.getPrototypeOf(@) while prototype if prototype.type? then @g.classed prototype.type, true prototype = Object.getPrototypeOf prototype @_init?() @trigger 'render' # Resize the layer, but _doesn't_ update the rendering, `resize()` should be used for that. size: (@width, @height)=> @trigger 'resize_start' if @h_orient != @chart.h_orient and @h == @chart.h then @h = @h.copy() c3.d3.set_range @h, if @h_orient is 'left' then [0, @width] else [@width, 0] if @v_orient != @chart.v_orient and @v == @chart.v then @v = @v.copy() c3.d3.set_range @v, if @v_orient is 'bottom' then [@height, 0] else [0, @height] @_size?() @trigger 'resize' # Update the DOM bindings based on the new or modified data set update: (origin)=> if not @chart? then throw Error "Attempt to redraw uninitialized plot layer, please use render() when modifying set of layers." @trigger 'redraw_start', origin @_update?(origin) # Position the DOM elements based on current scales. draw: (origin)=> if not (@static_data and origin is 'redraw') @trigger 'redraw_start', origin if origin is 'resize' @_draw?(origin) @trigger 'redraw', origin # Restyle existing items in the layer style: (style_new)=> @trigger 'restyle_start', style_new @_style?(style_new) @trigger 'restyle', style_new @trigger 'rendered' if not @rendered return this # Called when a layer needs to update from a zoom, decimated layers overload this zoom: => @draw?('zoom') @style?(true) # Redraw just this layer redraw: (origin='redraw')=> @update(origin) @draw(origin) @style(true) return this # Method to restyle this layer restyle: Layer::style # Adjust domains for layer scales for any automatic domains. # For layer-specific automatic domains the layer needs its own scale defined, # it cannot update the chart's shared scale. # @note Needs to happen after update() so that stacked layers are computed scale: => refresh = false if @h_domain? if @h==@chart.h then throw Error "Layer cannot scale shared h scale, please define just h or both h and h_domain for layers" h_domain = if typeof @h_domain is 'function' then @h_domain.call(this) else @h_domain if h_domain[0] is 'auto' then h_domain[0] = @min_x() if h_domain[1] is 'auto' then h_domain[1] = @max_x() if h_domain[0]!=@h.domain()[0] or h_domain[1]!=@h.domain()[1] @h.domain h_domain refresh = true if @v_domain? if @v==@chart.v then throw Error "Layer cannot scale shared v scale, please define just v or both v and v_domain for layers" v_domain = if typeof @v_domain is 'function' then @v_domain.call(this) else @v_domain if v_domain[0] is 'auto' then v_domain[0] = @min_y() if v_domain[1] is 'auto' then v_domain[1] = @max_y() if v_domain[0]!=@v.domain()[0] or v_domain[1]!=@v.domain()[1] @v.domain v_domain refresh = true return refresh min_x: => if @x? then d3.min @data, @x max_x: => if @x? then d3.max @data, @x min_y: => if @y? then d3.min @data, @y max_y: => if @y? then d3.max @data, @y ################################################################### # XY Plot Stackable Layers ################################################################### # An **abstract** class for layers that support stacking # such as {c3.Plot.Layer.Path} and {c3.Plot.Layer.Bar}. # # **Stacking** allows the user to group their data into different _stacks_, which are stacked # on top of each other in the chart. Stacking is enabled when you define _either_ `stack_options.key`, `stacks`, # or both options. `stack_options` allows you to configure how stacking is performed from the layer's data, # while `stacks` allows you to manually configure the exact set of stacks. # # This layer stacking is flexible to support several different ways of organizing the dataset into stacks: # * For normalized datasets you can define a `stack_options.key()` accessor to provide a key that uniquely # identifies which stack an element belongs to. # * Otherwise, you can manually define the set of `stacks` and the layer's `data` is copied into each. # * * The layer `y` accessor will be called with the arguments (_datum_,_index_,_stack_) # for you to provide the value for that element for that stack. # * * Or, you can define a `y` accessor for each stack to get the value for that element for that stack. # * You can also directly define `data` in each stack specified in `stacks`. # # Please view the examples for more explanation on how to stack data. # Remember, the set and order or stacks can always be programmatically constructed and dynamically updated. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **groups** - An entry will exist for an svg:g node for each stack in the layer # # @see ../../../examples/doc/stack_example.html # @abstract # @author <NAME> # @note If stacked, the input datasets may not have duplicate values in the same stack for the same X value. There are other resitrictions if `safe` mode is not used. # @note If you do not provide data elements for all stacks at all x values, then be prepared for your accessor callbacks to be called with _null_ objects. class c3.Plot.Layer.Stackable extends c3.Plot.Layer @version: 0.2 type: 'stackable' # [{c3.Selection.Options}] Enable stacking and specify stacking options for this layer. # This provides the normal {c3.Selection.Options} applied to each stack in the layer. For callbacks, # the first argument is the stack object and the second argument is the index to the stack # In addition, the following options control stacking behaviour: # * **key** [Function] An accessor you can define to return a key that uniquely identifies which stack # a data element belongs to. If this is specified, then this callback is used to determine which stack # each data element is assigned to. Otherwise, the layer data array is used in full for each stack. # * **name** [Function] A callback you define to set the name of a stack that is passed the stack key as an argument. # * **offset** [String, Function] The name or a function for the stacking algorithm used to place the data. # See {https://github.com/mbostock/d3/wiki/Stack-Layout#wiki-offset d3.stack.offset()} for details. # * * `none` - Do not stack the groups. Useful for grouped line charts. # * * `zero` - The default for a zero baseline. # * * `expand` - Normalize all points to range from 0-1. # * **order** [String] Specify the mechanism to order the stacks. # See {https://github.com/mbostock/d3/wiki/Stack-Layout#wiki-order d3.stack.order()} for details. stack_options: undefined # [Array<{c3.Plot.Layer.Stackable.Stack}>] An array of {c3.Plot.Layer.Stackable.Stack stack} # objects that can be used to manually specify the set of stacks. # Stack objects may contain: # * **key** [String] The key for this stack # * **y** [Function] A y accessor to use for this stack overriding the one provided by the chart or layer. # * **data** [Array] Manually specified dataset for this stack instead of using the layer's `data`. # * **name** [String] Name for the stack # * **options** [{c3.Selection.Options}] Options to manually set the **class**, **classes**, # **styles**, **events**, and **title** of just this stack. stacks: undefined # [Boolean] Safe Mode. # Preform additional checks and fix up the data for situations such as: # * Data not sorted along X axis # * Remove data elements where X or Y values are undefined # * Pad missing values where stacks are not defined for all X values. # Note that this mode may cause the indexes passed to the accessors to match the # corrected data instead of the original data array. safe: true # Restack the data based on the **stack** and **stacks** options. _stack: => if @stack_options or @stacks? @stacks ?= [] x_values_set = {} # Helper function to setup the current stack data and populate a shadow structure # to hold the x, y, and y0 positioning so we avoid modifying the user's data. add_value = (stack, datum, i, j)=> x = @x(datum,i); x_values_set[x] = x stack.y = stack.y ? @y ? throw Error "Y accessor must be defined in stack, layer, or chart" y = stack.y(datum, i, j, stack) stack.values.push { x:x, y:y, datum:datum } for stack, j in @stacks stack.name ?= @stack_options?.name? stack.key # Clear any previous stacking stack.values = [] # Shadow array to hold stack positioning # Data was provided manually in the stack definition if stack.data? then for datum, i in stack.data add_value stack, datum, i, j # Data has been provided in @current_data that we need to assign it to a stack if @current_data.length # Use stack_options.key() to assign data to stacks if @stack_options?.key? stack_map = {} stack_index = {} for stack, j in @stacks # Refer to hard-coded stacks if defined if stack_map[stack.key]? then throw Error "Stacks provided with duplicate keys: "+stack.key stack_map[stack.key] = stack stack_index[stack.key] = j for datum, i in @current_data key = @stack_options.key(datum) if stack_map[key]? stack = stack_map[key] j = stack_index[key] else @stacks.push stack = stack_map[key] = { key:key, name:@stack_options.name?(key), current_data:[], values:[] } j = @stacks.length add_value stack, datum, i, j # Otherwise, assign all data to all stacks using each stack's y() accessor else if @stacks? then for stack, j in @stacks for datum, i in @current_data add_value stack, datum, i, j else throw Error "Either stacks or stack_options.key must be defined to create the set of stacks." if @safe # Ensure everything is sorted # NOTE: We sort based on the @h scale in case of ordinal or other odd scales if @h.range()[0] is @h.range()[1] then @h.range [0,1] x_values = c3.array.sort_up (v for k,v of x_values_set), @h for stack in @stacks c3.array.sort_up stack.values, (v)=> @h v.x # Splice in missing data and remove undefined data (Important for D3's stack layout) i=0; while i<x_values.length undef = 0 for stack in @stacks # Check for missing values # Compare using h scale to tolerate values such as Dates stack_h = @h stack.values[i]?.x layer_h = @h x_values[i] if stack_h isnt layer_h if stack_h < layer_h # Check for duplicate X values if @h.domain()[0] is @h.domain()[1] throw Error "Did you intend for an h scale with 0 domain? Duplicate X values, invalid stacking, or bad h scale" else throw Error "Multiple data elements with the same x value in the same stack, or invalid stacking" stack.values.splice i, 0, { x:x_values[i], y:0, datum:null } undef++ # Check for undefined y values else if not stack.values[i].y? stack.values[i].y = 0 undef++ # If item is undefined for all stacks, then remove it completely if undef is @stacks.length stack.values.splice(i,1) for stack in @stacks x_values.splice(i,1) i-- i++ # Prepare array of current data for each stack in case it is needed for binding (used by bar chart) for stack in @stacks stack.current_data = stack.values.map (v)->v.datum # Configure and run the D3 stack layout to generate y0 and y layout data for the elements. if @stack_options?.offset == 'none' for stack in @stacks for value in stack.values value.y0 = 0 else stacker = d3.layout.stack().values (stack)->stack.values if @stack_options?.offset? then stacker.offset @stack_options.offset if @stack_options?.order? then stacker.order @stack_options.order stacker @stacks _update: => # Ensure data is sorted and skip elements that do not have a defined x or y value @current_data = if not @safe then @data else if @data? # TODO: we could try to use this values array later as an optimization and for more # stable i parameters passed to user accessors. However, it will complicate the code. if @y? and not @stacks? and not @stack_options? values = ({x:@x(d,i), y:@y(d,i), datum:d} for d,i in @data) c3.array.sort_up values, (v)=> @h v.x # Use @h to accomodate date types (v.datum for v in values when v.x? and v.y?) else values = ({x:@x(d,i), datum:d} for d,i in @data) if @stacks? or @stack_options? # Sorting handled by _stack() c3.array.sort_up values, (v)=> @h v.x (v.datum for v in values when v.x?) @current_data ?= [] @_stack() @groups = @content.select('g.stack') .bind (@stacks ? [null]), if not @stacks?[0]?.key? then null else (stack)->stack.key .options @stack_options, (if @stacks?.some((stack)->stack.options?) then (stack)->stack.options) .update() _style: (style_new)=> @groups?.style(style_new) min_x: => if not @stacks? then super else d3.min @stacks[0]?.values, (v)-> v.x max_x: => if not @stacks? then super else d3.max @stacks[0]?.values, (v)-> v.x min_y: => if not @stacks? then super else d3.min @stacks, (stack)-> d3.min stack.values, (v)-> v.y0 + v.y max_y: => if not @stacks? then super else d3.max @stacks, (stack)-> d3.max stack.values, (v)-> v.y0 + v.y # A _struct-type_ convention class to describe a stack when manually specifying the set of stacks # to use for a stackable chart layer. class c3.Plot.Layer.Stackable.Stack @version: 0.1 # [String] The key for this stack key: undefined # [Function] A _y accessor_ to use for this stack, overriding the one provided by the chart or layer. y: undefined # [Array] An array of data elements to use for this stack instead of the layer or chart's `data`. data: undefined # [String] Name for the stack name: undefined # [{c3.Selection.Options}] Options to manually set the **class**, **classes**, # **styles**, **events**, and **title** of just this stack. options: undefined constructor: (opt)-> c3.util.extend this, opt ################################################################### # XY Plot Line and Area Layers ################################################################### # Abstract chart layer for the {c3.Plot XY Plot Chart}. # Please instantiate a {c3.Plot.Layer.Line} or {c3.Plot.Layer.Area} # @see c3.Plot.Layer.Line # @see c3.Plot.Layer.Area # # Define an `r` or `a` to create circles at the various data points along the path # with that associated radius or area. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **paths** - There will be an element in paths for each stack in the layer # * **circles** - Circles for each datapoint # * **labels** - Labels for each datapoint # # @abstract # @author <NAME> class c3.Plot.Layer.Path extends c3.Plot.Layer.Stackable @version: 0.2 type: 'path' # [Function] Factory to generate an SVG path string generator function. _See {https://github.com/mbostock/d3/wiki/SVG-Shapes#path-data-generators} for details. path_generator_factory: undefined # [String] The type of D3 line interpolation to use. _See {https://github.com/mbostock/d3/wiki/SVG-Shapes#area_interpolate d3.svg.area.interpolate} for options._ Some useful examples: # * _linear_ - Straight lines between data points # * _basis_ - Smooth curve based on a B-spline, the curve may not touch the data points # * _cardinal_ - Smooth curve that intersects all data points. # * _step-before_ - A step function where the horizontal segments are to the left of the data points # * _step-after_ - A step function where the horizontal segments are to the right of the data points interpolate: undefined # [Number] The tension value [0,1] for cardinal interpolation. _See {https://github.com/mbostock/d3/wiki/SVG-Shapes#area_tension d3.svg.area.tension}._ tension: undefined # [Function] Accessor function you can return true or false if the data point in data[] is defined or should be skipped. _See {https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-area_defined d3.svg.area.defined}._ # Note that this will cause disjoint paths on either side of the missing element, # it will not render a continuous path that skips the undefined element. For that # behaviour simply enable `safe` mode and have the x or y accessor return undefined. defined: undefined # [Number, Function] Define to create circles at the data points along the path with this radius. r: undefined # [Number, Function] Define to create circles at the data points along the path with this area. # Takes precedence over r. a: undefined # [{c3.Selection.Options}] Options for the svg:path. For example, to enable animations. path_options: undefined # [{c3.Selection.Options}] If circles are created at the data points via `r` or `a`, then this # defines options used to style or extend them. circle_options: undefined # [{c3.Selection.Options}] Create labels for each datapoint with these options label_options: undefined _init: => if not @path_generator_factory? then throw Error "path_generator_factory must be defined for a path layer" @path_generator = @path_generator_factory() _update: (origin)=> if origin isnt 'zoom' super @paths = @groups.inherit('path.scaled').options(@path_options) # Bind the datapoint circles and labels if @r? or @a? @circles = @groups.select('circle').options(@circle_options).animate(origin is 'redraw') .bind(if @stacks? then (stack)->stack.current_data else @current_data).update() if @label_options? @labels = @groups.select('text').options(@label_options).animate(origin is 'redraw') .bind(if @stacks? then (stack)->stack.current_data else @current_data).update() _draw: (origin)=> # Only need to update the paths if the data has changed if origin isnt 'zoom' # Update the path generator based on the current settings if @interpolate? then @path_generator.interpolate @interpolate if @tension? then @path_generator.tension @tension if @defined? then @path_generator.defined @defined # Generate and render the paths. orig_h = @chart.orig_h ? @h # For rendering on the scaled layer @paths.animate(origin is 'redraw').position d: if @stacks? then (stack, stack_idx)=> @path_generator .x (d,i)=> orig_h stack.values[i].x .y (d,i)=> @v (stack.values[i].y0 + stack.values[i].y) .y0? if @baseline? and not stack_idx then (d,i)=> @v c3.functor(@baseline)(d,i) else (d,i)=> @v(stack.values[i].y0) @path_generator(stack.current_data) # Call the generator with this particular stack's data else => @path_generator .x (d,i)=> orig_h @x(d,i) .y (d,i)=> @v @y(d,i) .y0? if @baseline? then (d,i)=> @v c3.functor(@baseline)(d,i) else @height @path_generator(@current_data) # Position the circles @circles?.animate(origin is 'redraw').position cx: (d,i,s)=> @h @x(d,i,s) cy: if @stacks? then (d,i,s)=> values = @stacks[s].values[i]; @v values.y+values.y0 else (d,i)=> @v @y(d,i) r: if not @a? then @r else if typeof @a is 'function' then (d,i,s)=> Math.sqrt( @a(d,i,s) / Math.PI ) else Math.sqrt( @a / Math.PI ) # Set the labels @labels?.animate(origin is 'redraw').position transform: (d,i,s)=> 'translate('+(@h @x(d,i,s))+','+(@v @y(d,i,s))+')' _style: (style_new)=> super @paths.style(style_new) @circles?.style(style_new) @labels?.style(style_new) min_x: => if not @stacks? then (if @data.length then @x @data[0]) else @stacks[0]?.values[0]?.x max_x: => if not @stacks? then (if @data.length then @x @data.slice(-1)[0]) else @stacks[0]?.values.slice(-1)[0]?.x # Line graph layer for the {c3.Plot XY Plot Chart}. Please refer to {c3.Plot.Layer.Path} for documentation. # @see c3.Plot.Layer.Path # @author <NAME> class c3.Plot.Layer.Line extends c3.Plot.Layer.Path type: 'line' path_generator_factory: d3.svg.line # Area graph layer for the {c3.Plot XY Plot Chart}. Please refer to {c3.Plot.Layer.Path} for documentation. # @see c3.Plot.Layer.Path # @author <NAME> # @note The input data array should be sorted along the x axis. class c3.Plot.Layer.Area extends c3.Plot.Layer.Path type: 'area' path_generator_factory: d3.svg.area # [Number, Function] Base value or accessor for the bottom of the area chart. # _Defaults to the bottom of the chart._ baseline: undefined ################################################################### # XY Plot Bar Layer ################################################################### # Bar chart layer for the {c3.Plot XY Plot Chart} # # Bar charts may have positive or negative values unless they are stacked, # then they must be positive. # # When an orinal scale is used this layer will adjust it so that it provides padding # so the full bar on the left and right ends are fully visible. With other types of scales # the bars may have arbitrary x values from the user and may overlap. In this case, it is up # to the user to set the domain so bars are fully visible. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **rects** # # @todo Support negative y values for bar layers # @author <NAME> class c3.Plot.Layer.Bar extends c3.Plot.Layer.Stackable @version: 0.2 type: 'bar' # [Function] A callback to describe a unique key for each data element. # This is useful for animations during a redraw when updating the dataset. key: undefined # [Number, String, Function] Specify the width of the bars. # If this is a number it specifies the bar width in pixels. # If this is a string, such as `50%`, then it can specify the width of the bars as a # percentage of the available space for each bar based on proximity to each neighbor. # If this is a function it can set the width dynamically for each bar. bar_width: "50%" # [{c3.Selection.Options}] Options for the svg:rect's. # The callbacks are called with the user data for the rect as the first argument, the index of that # datum as the second argument, and the index of the stack for this rect as the third argument. # `stack.options` can be used instead to apply the same options to an entire stack. rect_options: undefined _update: => super @rects = @groups.select('rect').options(@rect_options).animate('origin is redraw') .bind((if @stacks? then ((stack)->stack.current_data) else @current_data), @key).update() _draw: (origin)=> baseline = @v(0) # Set bar_width and bar_shift if typeof @bar_width is 'function' bar_width = @bar_width bar_shift = -> bar_width(arguments...) / 2 else bar_width = +@bar_width if !isNaN bar_width # The user provided a simple number of pixels @h.rangeBands? @h.rangeExtent(), 1, 0.5 # Provide padding for an ordinal D3 scale bar_shift = bar_width/2 else # The user provided a percentage if @bar_width.charAt?(@bar_width.length-1) is '%' # Use charAt to confirm this is a string bar_ratio = +@bar_width[..-2] / 100 if isNaN bar_ratio then throw "Invalid bar_width percentage "+@bar_width[0..-2] if @h.rangeBands? # Setup padding for an ordinal D3 scale @h.rangeBands @h.rangeExtent(), 1-bar_ratio, 1-bar_ratio bar_width = @h.rangeBand() bar_shift = 0 else # Dynamically compute widths based on proximity to neighbors bar_width = if @stacks? then (d,i,j)=> values = @stacks[j].values mid = @h values[i].x left = @h if !i then (@chart.orig_h ? @h).domain()[0] else values[i-1].x right = @h if i==values.length-1 then (@chart.orig_h ? @h).domain()[1] else values[i+1].x width = Math.min((mid-left), (right-mid)) * bar_ratio if width >= 0 then width else 0 else (d,i)=> mid = @h @x(d,i) left = @h if !i then (@chart.orig_h ? @h).domain()[0] else @x(@current_data[i-1],i-1) right = @h if i==@current_data.length-1 then (@chart.orig_h ? @h).domain()[1] else @x(@current_data[i+1],i+1) width = Math.min((mid-left), (right-mid)) * bar_ratio if width >= 0 then width else 0 bar_shift = -> bar_width(arguments...) / 2 else throw "Invalid bar_width "+@bar_width if @stacks? x = (d,i,j)=> @h( @stacks[j].values[i].x ) y = (d,i,j)=> @v( @stacks[j].values[i].y0 + @stacks[j].values[i].y ) height = (d,i,j)=> baseline - (@v @stacks[j].values[i].y) else x = (d,i)=> @h @x(d,i) y = (d,i)=> y=@y(d,i); if y>0 then @v(y) else baseline height = (d,i)=> Math.abs( baseline - (@v @y(d,i)) ) @rects.animate(origin is 'redraw').position x: if not bar_shift then x else if typeof bar_shift isnt 'function' then -> x(arguments...) - bar_shift else -> x(arguments...) - bar_shift(arguments...) y: y height: height width: bar_width _style: (style_new)=> super @rects.style(style_new) ################################################################### # XY Plot Straight Line Layers ################################################################### # Straight **horizontal** or **vertical** line layer for the # {c3.Plot XY Plot Chart}. This is an **abstract** layer, please instantiate a # {c3.Plot.Layer.Line.Horizontal} or {c3.Plot.Layer.Line.Vertical} # directly. # # A seperate line is drawn for each data element in the `data` array. # _Set `label_options.text` to define a **label** for each line._ # Straight line layers are not _{c3.Plot.Layer.Stackable stackable}_. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **vectors** # * **lines** # * **labels** # # ## Events # * **dragstart** # * **drag** # * **dragend** # # @abstract # @author <NAME> class c3.Plot.Layer.Line.Straight extends c3.Plot.Layer @version: 0.1 type: 'straight' # [Function] Optional accessor to identify data elements when changing the dataset key: undefined # [Function] Accessor to get the value for each data element. # _Defaults to the identity function._ value: undefined # [Function] Accessor to determine if data elements are filtered in or not. filter: undefined # [Boolean] Enable lines to be draggable. # The drag event callbacks can be used to adjust the original data values draggable: false # [{c3.Selection.Options}] Options for the svg:g of the vector group nodes. # There is one node per data element. Use this option for animating line movement. vector_options: undefined # [{c3.Selection.Options}] Options for the svg:line lines. line_options: undefined # [{c3.Selection.Options}] Options for the svg:line lines for hidden lines # behind each line that is wider and easier for users to interact with # e.g. for click or drag events. grab_line_options: undefined # [{c3.Selection.Options}] Define this to render labels. Options for the svg:text labels. # This option also takes the following additional properties: # * **alignment** - [String] Alignment of label. # * * `left` or `right` for horizontal lines # * * `top` or `bottom` for vertical lines # * **dx** - [String] Relative placement for the label # * **dy** - [String] Relative placement for the label label_options: undefined _init: => @value ?= (d)-> d # Draggable lines if @draggable # NOTE: Because vertical lines are rotated, we are always dragging `y` self = this @dragger = d3.behavior.drag() drag_value = undefined #drag.origin (d,i)=> { y: @scale @value(d,i) } @dragger.on 'dragstart', (d,i)=> d3.event.sourceEvent.stopPropagation() # Prevent panning in zoomable charts @trigger 'dragstart', d, i @dragger.on 'drag', (d,i)-> domain = (self.chart.orig_h ? self.scale).domain() drag_value = Math.min(Math.max(self.scale.invert(d3.event.y), domain[0]), domain[1]) d3.select(this).attr 'transform', 'translate(0,'+self.scale(drag_value)+')' self.trigger 'drag', drag_value, d, i @dragger.on 'dragend', (d,i)=> @trigger 'dragend', drag_value, d, i _size: => @lines?.all?.attr 'x2', @line_length @grab_lines?.all?.attr 'x2', @line_length @labels?.all?.attr 'x', if @label_options.alignment is 'right' or @label_options.alignment is 'top' then @width else 0 _update: (origin)=> @current_data = if @filter? then (d for d,i in @data when @filter(d,i)) else @data @vectors = @content.select('g.vector').options(@vector_options).animate(origin is 'redraw') .bind(@current_data, @key).update() @lines = @vectors.inherit('line').options(@line_options).update() if @label_options? @label_options.dx ?= '0.25em' @label_options.dy ?= '-0.25em' @labels = @vectors.inherit('text').options(@label_options).update() # Add extra width for grabbable line area if @draggable or @grab_line_options @grab_lines = @vectors.inherit('line.grab') if @grab_line_options then @grab_lines.options(@grab_line_options).update() if @draggable @vectors.new.call @dragger _draw: (origin)=> @vectors.animate(origin is 'redraw').position transform: (d,i)=> 'translate(0,' + (@scale @value(d,i)) + ')' @lines.new.attr 'x2', @line_length @grab_lines?.new.attr 'x2', @line_length if @labels? far_labels = @label_options.alignment is 'right' or @label_options.alignment is 'top' @g.style 'text-anchor', if far_labels then 'end' else 'start' @labels.position dx: if far_labels then '-'+@label_options.dx else @label_options.dx dy: @label_options.dy x: if far_labels then @line_length else 0 _style: (style_new)=> @g.classed 'draggable', @draggable @vectors.style(style_new) @lines.style(style_new) @grab_lines?.style?(style_new) @labels?.style?(style_new) # Horizontal line layer. Please refer to {c3.Plot.Layer.Line.Straight} for documentation. # @see c3.Plot.Layer.Line.Straight class c3.Plot.Layer.Line.Horizontal extends c3.Plot.Layer.Line.Straight type: 'horizontal' _init: => label_options?.alignment ?= 'left' super @scale = @v _size: => @line_length = @width super # Vertical line layer. Please refer to {c3.Plot.Layer.Line.Straight} for documentation. # @see c3.Plot.Layer.Line.Straight class c3.Plot.Layer.Line.Vertical extends c3.Plot.Layer.Line.Straight type: 'vertical' _init: => label_options?.alignment ?= 'top' super @scale = @h _size: => @g.attr transform: 'rotate(-90) translate('+-@height+',0)' @line_length = @height super ################################################################### # XY Plot Region Layers ################################################################### # Render a rectangular region in an {c3.Plot XY Plot Chart}. # # Define `x` and `x2` options for vertical regions, # `y` and `y2` for horizontal regions, or all four for rectangular regions. # # The regions may be enabled to be `draggable` and/or `resizable`. # The chart will move or resize the region interactively, however it is up to # the user code to modify the data elements based on the `drag` or `dragend` # events. These callbacks are called with a structure of the new values and # the data element as parameters. The structure of new values is an object # with `x`, `x2` and `y`, `y2` members. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **regions** # * **rects** # # ## Events # * **dragstart** - called with the data element. # * **drag** - called with the new position and the data element. # * **dragend** - called with the new position and the data element. # # @author <NAME> class c3.Plot.Layer.Region extends c3.Plot.Layer type: 'region' _init: => if (@x? and !@x2?) or (!@x? and @x2?) or (@y? and !@y2?) or (!@y? and @y2?) throw Error "x and x2 options or y and y2 options must either be both defined or undefined" # Draggable lines if @draggable or @resizable drag_value = undefined origin = undefined self = this @dragger = d3.behavior.drag() .origin (d,i)=> x: if @x? then @h @x d,i else 0 y: if @y? then @v @y d,i else 0 .on 'drag', (d,i)-> h_domain = (self.orig_h ? self.h).domain() v_domain = self.v.domain() if self.x? width = self.x2(d) - self.x(d) x = Math.min(Math.max(self.h.invert(d3.event.x), h_domain[0]), h_domain[1]-width) if self.y? height = self.y2(d) - self.y(d) y = Math.min(Math.max(self.v.invert(d3.event.y), v_domain[0]), v_domain[1]-height) # Run values through scale round-trip in case it is a time scale. drag_value = x: if x? then self.h.invert self.h x x2: if x? then self.h.invert self.h x + width y: if y? then self.v.invert self.v y y2: if y? then self.v.invert self.v y + height if self.x? then d3.select(this).attr 'x', self.h drag_value.x if self.y? then d3.select(this).attr 'y', self.v drag_value.y2 self.trigger 'drag', drag_value, d, i @left_resizer = d3.behavior.drag() .origin (d,i)=> x: @h @x d, i .on 'drag', (d,i)-> h_domain = (self.orig_h ? self.h).domain() x = Math.min(Math.max(self.h.invert(d3.event.x), h_domain[0]), h_domain[1]) x2 = self.x2 d drag_value = x: self.h.invert self.h Math.min(x, x2) x2: self.h.invert self.h Math.max(x, x2) y: if self.y? then self.y(d) y2: if self.y2? then self.y2(d) d3.select(this.parentNode).select('rect').attr x: self.h drag_value.x width: self.h(drag_value.x2) - self.h(drag_value.x) self.trigger 'drag', drag_value, d, i @right_resizer = d3.behavior.drag() .origin (d,i)=> x: @h @x2 d, i .on 'drag', (d,i)-> h_domain = (self.orig_h ? self.h).domain() x = Math.min(Math.max(self.h.invert(d3.event.x), h_domain[0]), h_domain[1]) x2 = self.x d drag_value = x: self.h.invert self.h Math.min(x, x2) x2: self.h.invert self.h Math.max(x, x2) y: if self.y? then self.y(d) y2: if self.y2? then self.y2(d) d3.select(this.parentNode).select('rect').attr x: self.h drag_value.x width: self.h(drag_value.x2) - self.h(drag_value.x) self.trigger 'drag', drag_value, d, i @top_resizer = d3.behavior.drag() .origin (d,i)=> y: @v @y2 d, i .on 'drag', (d,i)-> v_domain = self.v.domain() y = Math.min(Math.max(self.v.invert(d3.event.y), v_domain[0]), v_domain[1]) y2 = self.y d drag_value = x: if self.x? then self.x(d) x2: if self.x2? then self.x2(d) y: self.v.invert self.v Math.min(y, y2) y2: self.v.invert self.v Math.max(y, y2) d3.select(this.parentNode).select('rect').attr y: self.v drag_value.y2 height: self.v(drag_value.y) - self.v(drag_value.y2) self.trigger 'drag', drag_value, d, i @bottom_resizer = d3.behavior.drag() .origin (d,i)=> y: @v @y d, i .on 'drag', (d,i)-> v_domain = self.v.domain() y = Math.min(Math.max(self.v.invert(d3.event.y), v_domain[0]), v_domain[1]) y2 = self.y2 d drag_value = x: if self.x? then self.x(d) x2: if self.x2? then self.x2(d) y: self.v.invert self.v Math.min(y, y2) y2: self.v.invert self.v Math.max(y, y2) d3.select(this.parentNode).select('rect').attr y: self.v drag_value.y2 height: self.v(drag_value.y) - self.v(drag_value.y2) self.trigger 'drag', drag_value, d, i for dragger in [@dragger, @left_resizer, @right_resizer, @top_resizer, @bottom_resizer] dragger .on 'dragstart', (d,i)=> d3.event.sourceEvent.stopPropagation() # Prevent panning in zoomable charts @trigger 'dragstart', d, i .on 'dragend', (d,i)=> @trigger 'dragend', drag_value, d, i @_draw() # reposition the grab lines for the moved region _size: => if not @x? @rects?.all.attr 'width', @width @left_grab_lines?.all.attr 'width', @width @right_grab_lines?.all.attr 'width', @width if not @y? @rects?.all.attr 'height', @height @top_grab_lines?.all.attr 'height', @height @bottom_grab_lines?.all.attr 'height', @height _update: (origin)=> @current_data = if @filter? then (d for d,i in @data when @filter(d,i)) else @data @regions = @content.select('g.region').options(@region_options).animate(origin is 'redraw') .bind(@current_data, @key).update() @rects = @regions.inherit('rect').options(@rect_options).update() if @draggable @rects.new.call @dragger # Add extra lines for resizing regions if @resizable if @x? @left_grab_lines = @regions.inherit('line.grab.left') @left_grab_lines.new.call @left_resizer if @x2? @right_grab_lines = @regions.inherit('line.grab.right') @right_grab_lines.new.call @right_resizer if @y? @top_grab_lines = @regions.inherit('line.grab.top') @top_grab_lines.new.call @top_resizer if @y2? @bottom_grab_lines = @regions.inherit('line.grab.bottom') @bottom_grab_lines.new.call @bottom_resizer _draw: (origin)=> @rects.animate(origin is 'redraw').position x: (d)=> if @x? then @h @x d else 0 width: (d)=> if @x2? then @h(@x2(d))-@h(@x(d)) else @width y: (d)=> if @y2? then @v @y2 d else 0 height: (d)=> if @y? then @v(@y(d))-@v(@y2(d)) else @height if @resizable @left_grab_lines?.animate(origin is 'redraw').position x1: (d)=> @h @x d x2: (d)=> @h @x d y1: (d)=> if @y? then @v @y d else 0 y2: (d)=> if @y2? then @v @y2 d else @height @right_grab_lines?.animate(origin is 'redraw').position x1: (d)=> @h @x2 d x2: (d)=> @h @x2 d y1: (d)=> if @y? then @v @y d else 0 y2: (d)=> if @y2? then @v @y2 d else @height @top_grab_lines?.animate(origin is 'redraw').position x1: (d)=> if @x? then @h @x d else 0 x2: (d)=> if @x2? then @h @x2 d else @width y1: (d)=> @v @y2 d y2: (d)=> @v @y2 d @bottom_grab_lines?.animate(origin is 'redraw').position x1: (d)=> if @x? then @h @x d else 0 x2: (d)=> if @x2? then @h @x2 d else @width y1: (d)=> @v @y d y2: (d)=> @v @y d _style: (style_new)=> @g.classed 'draggable': @draggable 'horizontal': not @x? 'vertical': not @y? @regions.style style_new @rects.style style_new ################################################################### # XY Plot Scatter Layer ################################################################### # Scatter plot layer for the {c3.Plot XY Plot Chart} # # Datapoints include a circle and an optional label. # _Set `label_options.text` to define the label for each point._ # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **points** - Representing svg:g nodes for each datapoint # * **circles** - Representing svg:circle nodes for each datapoint # * **labels** - Representing svg:text labels for each datapoint # @author <NAME> # @todo Only render datapoints within the current zoomed domain. class c3.Plot.Layer.Scatter extends c3.Plot.Layer @version: 0.1 type: 'scatter' # [Function] Accessor function to define a unique key to each data point. This has performance implications. # _This is required to enable **animations**._ key: undefined # [Function, Number] Accessor or value to set the value for each data point. # This is used when limiting the number of elements. value: undefined # [Function, Number] Accessor or value to set the circle radius r: 1 # [Function, Number] Accessor or value to set the circle area. _Takes precedence over r._ a: undefined # [Boolean] Safe mode will not render data where a positioning accessor returns undefined. # _This may cause the index passed to accessors to not match the original data array._ safe: true # [Function] Accessor to determine if the data point should be drawn or not # _This may cause the index passed to accessors to not match the original data array._ filter: undefined # [Number] Limit the number of data points. # _This may cause the index passed to accessors to not match the original data array._ limit_elements: undefined # [{c3.Selection.Options}] Options for svg:g nodes for each datapoint. point_options: undefined # [{c3.Selection.Options}] Options for the svg:circle of each datapoint circle_options: undefined # [{c3.Selection.Options}] Options for the svg:text lables of each datapoint. label_options: undefined _init: => if not @x? then throw Error "x must be defined for a scatter plot layer" if not @y? then throw Error "y must be defined for a scatter plot layer" if not @h? then throw Error "h must be defined for a scatter plot layer" if not @v? then throw Error "v must be defined for a scatter plot layer" _update: (origin)=> if not @data then throw Error "Data must be defined for scatter layer." # Filter the data for safety @current_data = if @filter? and @key? then (d for d,i in @data when @filter(d,i)) else @data if @safe then @current_data = (d for d in @current_data when ( @x(d)? and @y(d)? and (!@a? or typeof @a!='function' or @a(d)?) and (typeof @r!='function' or @r(d)?) )) # Limit the number of elements? if @limit_elements? if @value? @current_data = @current_data[..] # Copy the array to avoid messing up the user's order c3.array.sort_up @current_data, (d)=> -@value(d) # Sort by negative to avoid reversing array @current_data = @current_data[..@limit_elements] else @current_data = @current_data[..@limit_elements] # Bind and create the elements @points = @content.select('g.point').options(@point_options).animate(origin is 'redraw') .bind(@current_data, @key).update() # If there is no key, then hide the elements that are filtered if @filter? and not @key? @points.all.attr 'display', (d,i)=> if not @filter(d,i) then 'none' # Add circles to the data points @circles = @points.inherit('circle').options(@circle_options).animate(origin is 'redraw').update() # Add labels to the data points if @label_options? @labels = @points.inherit('text').options(@label_options).update() _draw: (origin)=> @points.animate(origin is 'redraw').position transform: (d,i)=> 'translate('+(@h @x(d,i))+','+(@v @y(d,i))+')' @circles.animate(origin is 'redraw').position r: if not @a? then @r else if typeof @a is 'function' then (d,i)=> Math.sqrt( @a(d,i) / Math.PI ) else Math.sqrt( @a / Math.PI ) _style: (style_new)=> @points.style(style_new) @circles.style(style_new) @labels?.style(style_new) ################################################################### # XY Plot Swimlane Layers ################################################################### # Base abstract class for {c3.Plot XY Plot} {c3.Plot.Layer layers} with horizontal swim lanes. # Swimlanes are numbered based on the vertical scale domain for the layer. # The first entry in the domain is the top swimlane and the last entry is the bottom swimlane plus 1. # If the first and last domain values are equal, then there are no swimlanes rendered. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **lanes** - svg:rect's for each swimlane # * **tip** - HTML hover content # @abstract # @author <NAME> class c3.Plot.Layer.Swimlane extends c3.Plot.Layer type: 'swimlane' # [String] `top` for 0 to be at the top, `bottom` for the bottom. # Swimlanes default to 0 at the top. v_orient: 'top' # [Number] Height of a swimlane in pixels. # Chart height will be adjusted if number of swimlanes changes in a redraw() dy: undefined # [Function] Provide HTML content for a hover div when mousing over the layer # This callback will be called with the datum and index of the item being hovered over. # It will be called with null when hovering over the layer but not any data items. hover: undefined # [{c3.Selection.Options}] Options for the lane svg:rect nodes for swimlanes lane_options: undefined _init: => if @lane_options? then @lanes = @content.select('rect.lane',':first-child').options(@lane_options) # Support html hover tooltips if @hover? anchor = d3.select(@chart.anchor) @tip = c3.select( anchor, 'div.c3.hover' ).singleton() layer = this mousemove = -> [layerX,layerY] = d3.mouse(this) # Get swimlane and ensure it is properly in range (mouse may be over last pixel) swimlane = Math.floor layer.v.invert layerY swimlane = Math.min swimlane, Math.max layer.v.domain()[0], layer.v.domain()[1]-1 x = layer.h.invert layerX hover_datum = layer._hover_datum(x, swimlane) hover_html = (c3.functor layer.hover)( hover_datum, (if hover_datum then layer.data.indexOf(hover_datum) else null), swimlane ) if not hover_html layer.tip.all.style 'display', 'none' else layer.tip.all.html hover_html layer.tip.all.style display: 'block' left: d3.event.clientX+'px' top: d3.event.clientY+'px' # Manage tooltip event handlers, disable while zooming/panning @chart.content.all.on 'mouseleave.hover', => layer.tip.all.style 'display', 'none' @chart.content.all.on 'mousedown.hover', => layer.tip.all.style 'display', 'none' @chart.content.all.on 'mousemove.hover', null @chart.content.all.on 'mouseup.hover', => @chart.content.all.on 'mousemove.hover', mousemove @chart.content.all.on 'mouseenter.hover', => if !d3.event.buttons then @chart.content.all.on 'mousemove.hover', mousemove @chart.content.all.on 'mousemove.hover', mousemove _size: => # If @dy is not defined, we determine it based on the chart height if not @y? then @dy = @height else @dy ?= Math.round @height / (Math.abs(@v.domain()[1]-@v.domain()[0])) # If a swimlane starts at the bottom, then shift up by dy because SVG always # renders the height of element downward. @g.attr 'transform', if @v_orient is 'bottom' then 'translate(0,-'+@dy+')' else '' _update: => # Support constant values and accessors @x = c3.functor @x @dx = c3.functor @dx @lanes?.bind([@v.domain()[0]...@v.domain()[1]]).update() # Update chart height to fit current number of swimlanes based on current v domain if @y? then @chart.size null, @dy*(Math.abs(@v.domain()[1]-@v.domain()[0])) + @chart.margins.top + @chart.margins.bottom _draw: (origin)=> if origin is 'resize' or origin is 'render' @lanes?.position y: (lane)=> @v lane width: @chart.orig_h.range()[1] height: @dy _style: => @lanes?.style() ################################################################### # XY Plot Segment Swimlane Layer ################################################################### # A {c3.Plot.Layer.Swimlane swimlane layer} for drawing horizontal segments in each swimlane. # # _Set `label_options.text` to define labels for the segments._ # The following {c3.Selection} members are made available if appropriate: # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **rects** - svg:rect for each segment # @todo Better threshold for determining which segments get labels. _Currently it is any segment > 50 pixels wide._ # @author <NAME> class c3.Plot.Layer.Swimlane.Segment extends c3.Plot.Layer.Swimlane @version: 0.1 type: 'segment' # **REQUIRED** [Function] Accessor to get the width of the segment dx: null # [Function] Key accessor to uniquely identify the segment. # Defining this improves performance for redraws. key: undefined # [Function] Accessor to determine if an element should be rendered filter: undefined # [Function] Value accessor for each segment. Used when limiting the number of elements. _Defaults to dx._ value: undefined # [Number] Specifies the maximum number of segments this layer will draw. Smaller segments are elided first. limit_elements: undefined # [{c3.Selection.Options}] Options for the svg:rect nodes for each segment rect_options: undefined # [{c3.Selection.Options}] Options for the label svg:text nodes for each segment label_options: undefined # IE10/11 doesn't support vector-effects: non-scaling-stroke, so avoid using scaled SVG. # This is a performance hit, because then we have to adjust the position of all rects for each redraw # TODO: Investigate if they added support for this in Edge. #scaled = !window.navigator.userAgent.match(/MSIE|Trident/) # MSIE==IE10, Trident==IE11, Edge==Edge # [3/18/2016] Disable the SVG scaled layer optimization completely for now. # If there are very large domains (e.g. a billion) then there is a floating-point precision problem # relying on SVG transformations to do the scaling/translation. # This doesn't seem to be a problem if we do the scaling ourselves in JavaScript. scaled = false _init: => super @g.classed 'segment', true # Manually do this so inherited types also have this class if scaled then @scaled_g = @g.append('g').attr('class','scaled') @rects_group = c3.select((@scaled_g ? @g),'g.segments').singleton() if @label_options? then @labels_clip = c3.select(@g,'g.labels').singleton().select('svg') _hover_datum: (x, swimlane)=> right = @h.invert @h(x)+1 # Get the pixel width for datum,idx in @current_data if (!@y? or @y(datum)==swimlane) and (_x=@x(datum)) <= right and x <= _x+@dx(datum) then break return if idx==@current_data.length then null else datum _update: => super # Pull filtered data elements @current_data = if not @filter? then @data else (d for d,i in @data when @filter(d,i)) # Pre-sort data by "value" for limiting to the most important elements if @limit_elements? if not @filter? then @current_data = @current_data[..] c3.array.sort_down @current_data, (@value ? @dx) _draw: (origin)=> super # Gather data for the current viewport domain [left_edge, right_edge] = @h.domain() half_pixel_width = (right_edge-left_edge) / ((@h.range()[1]-@h.range()[0]) || 1) / 2 data = [] for datum in @current_data when (x=@x(datum)) < right_edge and (x+(dx=@dx(datum))) > left_edge if dx < half_pixel_width if @limit_elements? then break else continue data.push datum if data.length == @limit_elements then break # Bind here because the current data set is dynamic based on zooming @rects = @rects_group.select('rect.segment').options(@rect_options).bind(data, @key).update() # Position the rects h = if @scaled_g? then (@chart.orig_h ? @h) else @h zero_pos = h(0) (if origin is 'resize' then @rects.all else @rects.new).attr 'height', @dy (if !scaled or !@key? or origin=='resize' or (origin=='redraw' and this instanceof c3.Plot.Layer.Swimlane.Flamechart) then @rects.all else @rects.new).attr x: (d)=> h @x(d) width: (d)=> (h @dx(d)) - zero_pos y: if not @y? then 0 else (d)=> @v @y(d) # Bind and render lables here (not in _update() since the set is dynamic based on zooming and resizing) if @label_options? # Create labels in a nested SVG node so we can crop them based on the segment size. zero_pos = @h(0) current_labels = (datum for datum in data when (@h @dx datum)-zero_pos>50) @labels_clip.bind(current_labels, @key) @labels = @labels_clip.inherit('text').options(@label_options).update() (if origin is 'resize' then @labels_clip.all else @labels_clip.new).attr 'height', @dy @labels_clip.position x: (d)=> @h @x(d) y: if not @y? then 0 else (d,i)=> @v @y(d,i) width: (d)=> (@h @dx(d)) - zero_pos self = this (if origin is 'resize' then @labels.all else @labels.new).attr 'y', self.dy/2 @labels.position x: (d)-> x = self.x(d) dx = self.dx(d) left = Math.max x, self.h.domain()[0] right = Math.min x+dx, self.h.domain()[1] return self.h( (right-left)/2 + (left-x) ) - zero_pos # x: (d)-> # x = self.x(d) # dx = self.dx(d) # left = Math.max x, self.h.domain()[0] # right = Math.min x+dx, self.h.domain()[1] # # NOTE: This is expensive. Chrome was faster with offsetWidth, but Firefox and IE11 didn't support it # text_width = this.offsetWidth ? this.getBBox().width # if self.h(right-left)-zero_pos > text_width # return self.h( (right-left)/2 + (left-x) ) - zero_pos - (text_width/2) # else # return if x < left then self.h(left-x)-zero_pos+1 else 1 else c3.select(@g,'g.labels').all.remove() delete @labels # Style any new elements we added by resizing larger that allowed new relevant elements to be drawn if origin is 'resize' and (not @rects.new.empty() or (@labels? and not @labels.new.empty())) @_style true _style: (style_new)=> super @rects.style(style_new) @labels?.style(style_new) ################################################################### # Flamechart ################################################################### # A {c3.Plot.Layer.Swimlane swimlane layer} for rendering _flamecharts_ or _flamegraphs_. # # In C3, both a {c3.Plot.Layer.Swimlane.Flamechart Flamechart} and an # {c3.Plot.Layer.Swimlane.Icicle Icicle} can actually grow either up or down # depending if you set `v_orient` as `top` or `bottom`. # A _Flamechart_ defaults to growing up and an _Icicle_ defaults to growing down. # In C3, a {c3.Plot.Layer.Swimlane.Flamechart Flamechart} visualizes a timeline # of instances of nested events over time, while an {c3.Plot.Layer.Swimlane.Icicle Icicle} # visualizes an aggregated tree hierarchy of nodes. The {c3.Polar.Layer.Sunburst Sunburst} # is the equivalent of an _Icicle_ rendered on a polar axis. # # A `key()` is required for this layer. # You should not define `y`, but you must define a `x`, `dx`, and `dy`. # # @author <NAME> class c3.Plot.Layer.Swimlane.Flamechart extends c3.Plot.Layer.Swimlane.Segment @version: 0.1 type: 'flamechart' # [String] `top` for 0 to be at the top, `bottom` for the bottom. # Flamechart defaults to bottom-up. v_orient: 'bottom' _init: => super if not @key? then throw Error "`key()` accessor function is required for Flamechart layers" if not @dy? then throw Error "`dy` option is required for Flamechart layers" if @y? then throw Error "`y` option cannot be defined for Flamechart layers" @y = (d)=> @depths[@key d] @depths = {} _update: (origin)=> super # Compute depths for each data element data = @current_data[..] c3.array.sort_up data, @x max_depth = 0 stack = [] for datum in data frame = x: @x datum dx: @dx datum while stack.length and frame.x >= (_frame=stack[stack.length-1]).x + _frame.dx stack.length-- stack.push frame max_depth = Math.max max_depth, stack.length # stack.length is starting from 0, so don't reduce by one. @depths[@key datum] = stack.length - 1 # Set the vertical domain and resize chart based on maximum flamechart depth @v.domain [0, max_depth] c3.Plot.Layer.Swimlane::_update.call this, origin ################################################################### # Icicle ################################################################### # A {c3.Plot.Layer.Swimlane swimlane layer} for rendering _icicle_ charts. # # In C3, both a {c3.Plot.Layer.Swimlane.Flamechart Flamechart} and an # {c3.Plot.Layer.Swimlane.Icicle Icicle} can actually grow either up or down # depending if you set `v_orient` as `top` or `bottom`. # A _Flamechart_ defaults to growing up and an _Icicle_ defaults to growing down. # In C3, a {c3.Plot.Layer.Swimlane.Flamechart Flamechart} visualizes a timeline # of instances of nested events over time, while an {c3.Plot.Layer.Swimlane.Icicle Icicle} # visualizes an aggregated tree hierarchy of nodes. The {c3.Polar.Layer.Sunburst Sunburst} # is the equivalent of an _Icicle_ rendered on a polar axis. # # A `key()` is required for this layer. # You should not define `x` or `y`, but you must define `dy`. # Specify a callback for either `parent_key`, # `children`, or `children_keys` to describe the hierarchy. # If using `parent_key` or `children_keys` the `data` array shoud include all nodes, # if using `children` it only should include the root nodes. # Define either `value()` or `self_value()` to value the nodes in the hierarchy. # # If you care about performance, you can pass the # parameter `revalue` to `redraw('revalue')` if you are keeping the same dataset # hierarchy, and only changing the element's values. # The Icicle layer can use a more optimized algorithm in this situation. # # ## Events # * **rebase** Called with the datum of a node when it becomes the new root # or with `null` if reverting to the top of the hierarchy. # # @author <NAME> class c3.Plot.Layer.Swimlane.Icicle extends c3.Plot.Layer.Swimlane @version: 0.1 type: 'icicle' # **REQUIRED** [Function] Accessor function to define a unique key for each data element. # _This has performance implications and is required for some layers and **animations**._ key: undefined # [Function] Accessor to get the "_total_" value of the data element. # That is the total value of the element itself inclusive of all of it's children's value. # You can define either _value_ or _self_value_. value: undefined # [Function] The `value` accessor defines the "_total_" value for an element, that is the value of # the element itself plus that of all of its children. If you know the "self" value of an # element without the value of its children, then define this callback accessor instead. # The `value` option will then also be defined for you, which you can use to get the total value # of an element after the layer has been drawn. self_value: undefined # [Function] A callback that should return the key of the parent of an element. # It is called with a data element as the first parameter. parent_key: undefined # [Function] A callback that should return an array of child keys of an element. # The returned array may be empty or null. # It is called with a data element as the first parameter. children_keys: undefined # [Function] A callback that should return an array of children elements of an element. # The returned array may be empty or null. # It is called with a data element as the first parameter. children: undefined # [Boolean, Function] How to sort the partitioned tree segments. # `true` sorts based on _total_ value, or you can define an alternative # accessor function to be used for sorting. sort: false # [Number] Limit the number of data elements to render based on their value. # _This affects the callback index parameter_ limit_elements: undefined # [Number] Don't bother rendering segments whose value is smaller than this # percentage of the current domain focus. (1==100%) limit_min_percent: 0.001 # Data element that represents the root of the hierarchy to render. # If this is specified, then only this root and its parents and children will be rendered # When {c3.Plot.Layer.Icicle#rebase rebase()} is called or a node is clicked on # it will animate the transition to a new root node, if animation is enabled. root_datum: null # [{c3.Selection.Options}] Options for the svg:rect nodes for each segment rect_options: undefined # [{c3.Selection.Options}] Options for the label svg:text nodes for each segment label_options: undefined _init: => super if not @key? then throw Error "`key()` accessor function is required for Icicle layers" if not @dy? then throw Error "`dy` option is required for Icicle layers" if @x? then throw Error "`x` option cannot be defined for Icicle layers" if @y? then throw Error "`y` option cannot be defined for Icicle layers" @y = (datum)=> @nodes[@key datum].y1 @segments_g = c3.select(@g, 'g.segments').singleton() @segment_options = { events: { click: (d)=> @rebase if d isnt @root_datum then d else (if @parent_key? then @nodes[@parent_key d] else @nodes[@key d].parent)?.datum } } @label_clip_options = {} if @label_options? @label_options.animate ?= @rect_options.animate @label_options.duration ?= @rect_options.duration @label_clip_options.animate ?= @rect_options.animate @label_clip_options.duration ?= @rect_options.duration _hover_datum: (x, swimlane)=> right = @h.invert @h(x)+1 # Get the pixel width for key,node of @nodes if node.y1 is swimlane and node.x1 <= right and x <= node.x2 return node.datum return null _update: (origin)=> super # Construct the tree hierarchy if origin isnt 'revalue' and origin isnt 'rebase' @tree = new c3.Layout.Tree key: @key, parent_key: @parent_key, children_keys: @children_keys, children: @children value: @value, self_value: @self_value @nodes = @tree.construct @data # Set the vertical domain and resize chart based on maximum flamechart depth @v.domain [0, d3.max Object.keys(@nodes), (key)=> @nodes[key].y2] c3.Plot.Layer.Swimlane::_update.call this, origin # Compute the "total value" of each node if origin isnt 'rebase' @value = @tree.revalue() # Partition the arc segments based on the node values # We need to do this even for 'rebase' in case we shot-circuited previous paritioning @current_data = @tree.layout( if origin isnt 'revalue' and origin isnt 'rebase' then @sort else false @limit_min_percent @root_datum ) # Limit the number of elements to bind to the DOM if @current_data.length > @limit_elements c3.array.sort_up @current_data, @value # sort_up is more efficient than sort_down @current_data = @current_data[-@limit_elements..] # Bind data elements to the DOM @segment_options.animate = @rect_options?.animate @segment_options.animate_old = @rect_options?.animate @segment_options.duration = @rect_options?.duration @segments = @segments_g.select('g.segment').options(@segment_options) .animate(origin is 'redraw' or origin is 'revalue' or origin is 'rebase') .bind(@current_data, @key).update() @rect_options?.animate_old ?= @rect_options?.animate @rects = @segments.inherit('rect').options(@rect_options).update() if @label_options? @label_clip_options.animate_old = @label_options?.animate @label_clips = @segments.inherit('svg.label').options(@label_clip_options) _draw: (origin)=> super # Set the horizontal domain based on the root node. prev_h = @h.copy() prev_zero_pos = prev_h(0) root_node = @nodes[@key @root_datum] if @root_datum? @h.domain [root_node?.x1 ? 0, root_node?.x2 ? 1] zero_pos = @h(0) # Position the segments. # Place any new segments where they would have been if not decimated. (if origin is 'resize' then @rects.all else @rects.new).attr 'height', @dy @rects.animate(origin is 'redraw' or origin is 'revalue' or origin is 'rebase').position { x: (d)=> @h @nodes[@key d].x1 y: (d)=> @v @nodes[@key d].y1 width: (d)=> @h((node=@nodes[@key d]).x2 - node.x1) - zero_pos }, { x: (d)=> prev_h @nodes[@key d].px1 y: (d)=> @v @nodes[@key d].py1 width: (d)=> prev_h((node=@nodes[@key d]).px2 - node.px1) - prev_zero_pos } if @label_options? (if origin is 'resize' then @rects.all else @rects.new).attr 'height', @dy @label_clips.animate(origin is 'redraw' or origin is 'revalue' or origin is 'rebase').position { x: (d)=> @h @nodes[@key d].x1 y: (d)=> @v @nodes[@key d].y1 width: (d)=> @h((node=@nodes[@key d]).x2 - node.x1) - zero_pos }, { x: (d)=> prev_h @nodes[@key d].px1 y: (d)=> @v @nodes[@key d].py1 width: (d)=> prev_h((node=@nodes[@key d]).px2 - node.px1) - prev_zero_pos } # Bind and position labels for larger segments. @labels = c3.select( @label_clips.all.filter((d)=> @h((node=@nodes[@key d]).x2 - node.x1) - zero_pos >= 50) ).inherit('text', 'restore') .options(@label_options).update() .animate(origin is 'redraw' or origin is 'revalue' or origin is 'rebase').position y: @dy / 2 x: (d)=> node = @nodes[@key d] left = Math.max node.x1, @h.domain()[0] right = Math.min node.x2, @h.domain()[1] return @h( (right-left)/2 + (left-node.x1) ) - zero_pos # Remove any stale labels from segments that are now too small @segments.all .filter((d)=> @h((node=@nodes[@key d]).x2 - node.x1) - zero_pos < 50) .selectAll('text') .transition('fade').duration(@label_options.duration).style('opacity',0) .remove() else @segments.all.selectAll('text').remove() delete @labels # Style any new elements we added by resizing larger that allowed new relevant elements to be drawn if origin is 'resize' and (not @rects.new.empty() or (@labels? and not @labels.new.empty())) @_style true _style: (style_new)=> super @rects.style(style_new) @labels?.style(style_new) # Navigate to a new root node in the hierarchy representing the `datum` element rebase: (@root_datum)=> @trigger 'rebase_start', @root_datum @chart.redraw 'rebase' # redraw all layers, since the scales will change @trigger 'rebase', @root_datum # Navigate to a new root node in the hierarchy represented by `key` rebase_key: (root_key)=> @rebase @nodes[root_key]?.datum ################################################################### # XY Plot Sampled Swimlane Layers ################################################################### # A {c3.Plot.Layer.Swimlane swimlane layer} that will sample for each pixel in each swimlane. # @abstract # @author <NAME> class c3.Plot.Layer.Swimlane.Sampled extends c3.Plot.Layer.Swimlane @version: 0.0 type: 'sampled' # **REQUIRED** [Function] Accessor to get the width of the segment dx: null # [Function] Callback to determine if the data element should be rendered or not filter: undefined # [Boolean] If safe mode is off then it is assumed the data is sorted by the x-axis safe: true _hover_datum: (x, swimlane)=> data = @swimlane_data[swimlane] right = @h.invert @h(x)+1 # Get the pixel width idx = d3.bisector(@x).right(data, x) - 1 return if idx<0 then null else if x < @x(datum=data[idx])+@dx(datum) then datum else if ++idx<data.length and @x(datum=data[idx]) <= right then datum else null _update: => super # Arrange data by swimlane and remove filtered items @swimlane_data = [] @swimlane_data[swimlane] = [] for swimlane in [@v.domain()[0]...@v.domain()[1]] [top_edge, bottom_edge] = @v.domain() for datum, i in @data when (!@filter? or @filter(datum,i)) swimlane = @y datum, i if top_edge <= swimlane < bottom_edge then @swimlane_data[swimlane].push datum # Sort data in safe mode if @safe c3.array.sort_up(data,@x) for data in @swimlane_data _sample: (sample)=> # Sample data points for each pixel in each swimlane bisector = d3.bisector(@x).right for swimlane in [@v.domain()[0]...@v.domain()[1]] v = @v swimlane data = @swimlane_data[swimlane] if not data.length then continue # Optimized to find the left starting point prev_idx = bisector(data, @h.domain()[0]) if not prev_idx pixel = Math.round @h @x @data[prev_idx] else prev_idx-- pixel = if @h(@x(@data[prev_idx])+@dx(@data[prev_idx])) > 0 then 0 else Math.round @h @x data[prev_idx] # Iterate through each pixel in this swimlane while pixel < @width x = @h.invert(pixel) # Find the next data element for this pixel, or skip to the next pixel if there is a gap idx = prev_idx while idx < data.length datum = data[idx] prev_idx = idx if (datum_x=@x(datum)) > x pixel = Math.round @h datum_x break if x <= datum_x+@dx(datum) then break idx++ if idx==data.length then break sample pixel, v, datum pixel++ return # avoid returning a comprehension # A {c3.Plot.Layer.Swimlane.Sampled sampled swimlane layer} implemented via SVG lines # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **lines** - svg:rect's for each swimlane # @todo Optimize by generating pixel data array once in _size() and reusing it in _draw() class c3.Plot.Layer.Swimlane.Sampled.SVG extends c3.Plot.Layer.Swimlane.Sampled @version: 0.0 type: 'svg' # [{c3.Selection.Options}] Options for the svg:line's in each swimlane line_options: undefined _draw: (origin)=> super # Gather sampled pixels to bind to SVG linex current_data = [] pixels = [] @_sample (x,y,datum)-> current_data.push datum pixels.push { x:x, y:y } # Bind data in _draw without a key because it is based on pixel sampling @lines = c3.select(@g,'line').options(@line_options).bind(current_data).update() @lines.position x1: (d,i)-> pixels[i].x + 0.5 # Center line on pixels to avoid anti-aliasing x2: (d,i)-> pixels[i].x + 0.5 y1: if not @y? then 0 else (d,i)-> pixels[i].y - 0.5 y2: if not @y? then @height else (d,i)=> pixels[i].y + @dy - 0.5 _style: => super @lines.style() # A {c3.Plot.Layer.Swimlane.Sampled sampled swimlane layer} implemented via HTML5 Canvas # This layer supports `line_options.styles.stroke` and HTML `hover` "tooltips". class c3.Plot.Layer.Swimlane.Sampled.Canvas extends c3.Plot.Layer.Swimlane.Sampled @version: 0.0 type: 'canvas' # [{c3.Selection.Options}] Options for the svg:line's in each swimlane line_options: undefined _init: => super foreignObject = c3.select(@g,'foreignObject').singleton().position({height:'100%',width:'100%'}) @canvas = foreignObject.select('xhtml|canvas').singleton() #@canvas = document.createElement('canvas') #@image = c3.select(@g,'svg|image').singleton() _size: => super @canvas.position height: @height width: @width __draw: => context = @canvas.node().getContext('2d') context.clearRect 0,0, @width,@height # Translate by 0.5 so lines are centered on pixels to avoid anti-aliasing which causes transparency context.translate 0.5, 0.5 # Sample pixels to render onto canvas stroke = c3.functor @line_options?.styles?.stroke @_sample (x,y,datum)=> context.beginPath() context.moveTo x, y context.lineTo x, y+@dy context.strokeStyle = stroke datum context.stroke() context.translate -0.5, -0.5 #@image.all.attr('href',@canvas.toDataURL('image/png')) #@image.all.node().setAttributeNS('http://www.w3.org/1999/xlink','xlink:href',@canvas.toDataURL('image/png')) _draw: (origin)=> super; @__draw(origin) _style: (style_new)=> super; if not style_new then @__draw('restyle') # For the sampled layer, draw and style are the same. By default zoom does both, so just do one. zoom: => @__draw('zoom') #################################################################### ## XY Plot Decimated Layer #################################################################### # ## A decimated layer may be created to assist certain layer types to manage large datasets. ## When using a decimated layer pass into the constructor an array of the data at different ## detail granularities as well as a layer object instance that will be used as a "prototype" to ## construct a different layer for each detail level of data. This layer will only show one ## of the levels at a time and will automatically transition between them as the user zooms in and out. ## ## _When using a decimated layer, the **data** option does not need to be set for the layer prototype._ ## @example Creating a decimated layer ## mychart = new c3.Plot.horiz_zoom { ## anchor: '#chart_div' ## h: d3.scale.linear().domain [0, 1] ## v: d3.scale.linear().domain [0, 100] ## x: (d)-> d.x ## layers: [ ## new c3.Layer.decimated mylevels, new c3.Layer.area { ## y: (d)-> d.y ## interpolate: 'basis' ## } ## ] ## } ## mychart.render() ## @todo Should this be implemented as a mix-in instead? ## @todo A built-in helper for users to construct decimated groups using CrossFilter ## @author <NAME> <NAME> #class c3.Plot.Layer.Decimated extends c3.Plot.Layer # @version: 0.1 # type: 'decimated' # # # [Number] The maximum number of data elements to render at a given time when preparing sections for smooth panning. # renderport_elements: 8000 # # [Number] If a decimated element spans more than this number of pixels after zooming then switch to the next level of detail. # pixels_per_bucket_limit: 2 # # # @param levels [Array] An Array of detail levels. Each entry in the array should be an array of data elements. # # Each level should also add a **granulairty** property which specified how many X domain units are combined into a single element for this level of detail. # # @param proto_layer [c3.Plot.Layer] A layer instance to use as a prototype to make layers for each level of detail. # constructor: (@levels, @proto_layer)-> ## @type += ' '+@proto_layer.type # for level, i in @levels # level.index = i # level.renderport = [0,0] # # _init: => # for level, i in @levels # level.layer = new @proto_layer.constructor() # c3.util.defaults level.layer, @proto_layer # level.layer.data = level # level.layer.g = @g.append('g').attr('class', 'level _'+i+' layer') # level.layer.init @chart # # _size: => # for level in @levels # level.layer.size @width, @height # # _update: => # # Invalidate the non-visible levels # for level in @levels when level isnt @current_level # level.renderport = [0,0] # @current_level?.layer.update() # # _draw: => # if not @current_level? then @zoom() # else @current_level.layer.draw() # # zoom: => # # Find the optimal decimation level for this viewport # view_width = @chart.h.domain()[1] - @chart.h.domain()[0] # for level in @levels # visible_buckets = view_width / level.granularity # if visible_buckets*@pixels_per_bucket_limit > @width # new_level = level # break # if !new_level? then new_level = @levels[@levels.length-1] # # # Did we change decimation levels? # if @current_level != new_level # @current_level = new_level # @g.selectAll('g.level').style('display','none') # @g.select('g.level[class~=_'+@current_level.index+']').style('display',null) # # # Determine if current viewport is outside current renderport and we need to redraw # if @chart.h.domain()[0] < @current_level.renderport[0] or # @chart.h.domain()[1] > @current_level.renderport[1] # # # Limit number of elements to render, centered on the current viewport # center = (@chart.h.domain()[0]+@chart.h.domain()[1]) / 2 # bisector = d3.bisector (d)->d.key # center_element = bisector.left @current_level, center # element_domain = [] # element_domain[0] = center_element - @renderport_elements/2 - 1 # element_domain[1] = center_element + @renderport_elements/2 # if element_domain[0]<0 then element_domain[0] = 0 # if element_domain[1]>@current_level.length-1 then element_domain[1] = @current_level.length-1 # # @current_level.renderport = (@current_level[i].key for i in element_domain) # # # Swap data for the new renderport and redraw # @current_level.layer.data = @current_level[element_domain[0]..element_domain[1]] # @current_level.layer.redraw()
true
# c3 Visualization Library # Layers for XY Plots ################################################################### # XY Plot Chart Layers ################################################################### # The root abstract class of layers for the {c3.Plot c3 XY Plot Chart} # # ## Internal Interface # The internal interface that plot layers can implement essentially match the {c3.Base} internal abstract interface: # * **{c3.base#init init()}** # * **{c3.base#size size()}** # * **{c3.base#update update()}** # * **{c3.base#draw draw()}** # * **{c3.base#style style()}** # # An additional method is added: # * **zoom()** - Called when the chart is zoomed or panned. # # ## Extensibility # Each layer has the following members added: # * **chart** - Reference to the {c3.Plot XY Plot Chart} this layer belongs to # * **content** - A {c3.Selection selection} of the layer content # * **g** - A {https://github.com/mbostock/d3/wiki/Selections D3 selection} for the SVG g node for this layer # * **width** - width of the layer # * **height** - height of the layer # # @method #on(event, handler) # Register an event handler to catch events fired by the visualization. # @param event [String] The name of the event to handle. _See the Exetensibility and Events section for {c3.base}._ # @param handler [Function] Callback function called with the event. The arguments passed to the function are event-specific. # # Items should be positioned on the the layer using the layer's `h` and `v` scales. # As a performance optimization some layers may create a g node with the `scaled` class. # When the plot is zoomed then this group will have a transform applied to reflect the zoom so # individual elements do not need to be adjusted. Please use the `chart.orig_h` scale in this case. # Not that this approach does not work for many circumstances as it affects text aspect ratio, # stroke widths, rounding errors, etc. # @abstract # @author PI:NAME:<NAME>END_PI class c3.Plot.Layer @version: 0.2 c3.Layer = this # Shortcut for accessing plot layers. type: 'layer' @_next_uid: 0 # [Array] Data for this layer _This can be set for each individual layer or a default for the entire chart._ data: undefined # [String] User name for this layer. This is used in legends, for example. name: undefined # [String] CSS class to assign to this layer for user style sheets to customize class: undefined # [Boolean] If true this layer is considered to have "static" data and will not update when {c3.Base#redraw redraw()} is called. static_data: false # [{https://github.com/mbostock/d3/wiki/Scales d3.scale}] Scale for the _vertical_ Y axis for this layer. # Please set the _domain()_, c3 will set the _range()_. # _The vertical scale may be set for the entire chart instead of for each layer._ h: undefined # [{https://github.com/mbostock/d3/wiki/Scales d3.scale}] Scale for the _vertical_ Y axis for this layer. # Please set the _domain()_, c3 will set the _range()_. # _The vertical scale may be set for the entire chart instead of for each layer._ v: undefined # [Function] An accessor function to get the X value from a data item. # _This can be set for each individual layer or a default for the entire chart._ # Some plots support calling this accessor with the index of the data as well as the datum itself. x: undefined # [Function] An accessor function to get the Y value from a data item. # _This can be set for each individual layer or a default for the entire chart._ # Some plots support calling this accessor with the index of the data as well as the datum itself. y: undefined # [String] `left` for 0 to be at the left, `right` for the right. h_orient: undefined # [String] `top` for 0 to be at the top, `bottom` for the bottom. v_orient: undefined # [{c3.Selection.Options}] Options to set the **class**, **classes**, **styles**, # **events**, and **title** for this layer. options: undefined # [Object] An object to setup event handlers to catch events triggered by this c3 layer. # The keys represent event names and the values are the cooresponding handlers. handlers: undefined constructor: (opt)-> c3.util.extend this, new c3.Dispatch c3.util.extend this, opt @uid = c3.Plot.Layer._next_uid++ # Internal function for the Plot to prepare the layer. init: (@chart, @g)=> @trigger 'render_start' @data ?= @chart.data @h ?= @chart.h @v ?= @chart.v @x ?= @chart.x @y ?= @chart.y @h_orient ?= @chart.h_orient @v_orient ?= @chart.v_orient if @class? then @g.classed @class, true if @handlers? then @on event, handler for event, handler of @handlers @content = c3.select(@g) # Apply classes to layer g nodes based on the `type` of the layer object hierarchy prototype = Object.getPrototypeOf(@) while prototype if prototype.type? then @g.classed prototype.type, true prototype = Object.getPrototypeOf prototype @_init?() @trigger 'render' # Resize the layer, but _doesn't_ update the rendering, `resize()` should be used for that. size: (@width, @height)=> @trigger 'resize_start' if @h_orient != @chart.h_orient and @h == @chart.h then @h = @h.copy() c3.d3.set_range @h, if @h_orient is 'left' then [0, @width] else [@width, 0] if @v_orient != @chart.v_orient and @v == @chart.v then @v = @v.copy() c3.d3.set_range @v, if @v_orient is 'bottom' then [@height, 0] else [0, @height] @_size?() @trigger 'resize' # Update the DOM bindings based on the new or modified data set update: (origin)=> if not @chart? then throw Error "Attempt to redraw uninitialized plot layer, please use render() when modifying set of layers." @trigger 'redraw_start', origin @_update?(origin) # Position the DOM elements based on current scales. draw: (origin)=> if not (@static_data and origin is 'redraw') @trigger 'redraw_start', origin if origin is 'resize' @_draw?(origin) @trigger 'redraw', origin # Restyle existing items in the layer style: (style_new)=> @trigger 'restyle_start', style_new @_style?(style_new) @trigger 'restyle', style_new @trigger 'rendered' if not @rendered return this # Called when a layer needs to update from a zoom, decimated layers overload this zoom: => @draw?('zoom') @style?(true) # Redraw just this layer redraw: (origin='redraw')=> @update(origin) @draw(origin) @style(true) return this # Method to restyle this layer restyle: Layer::style # Adjust domains for layer scales for any automatic domains. # For layer-specific automatic domains the layer needs its own scale defined, # it cannot update the chart's shared scale. # @note Needs to happen after update() so that stacked layers are computed scale: => refresh = false if @h_domain? if @h==@chart.h then throw Error "Layer cannot scale shared h scale, please define just h or both h and h_domain for layers" h_domain = if typeof @h_domain is 'function' then @h_domain.call(this) else @h_domain if h_domain[0] is 'auto' then h_domain[0] = @min_x() if h_domain[1] is 'auto' then h_domain[1] = @max_x() if h_domain[0]!=@h.domain()[0] or h_domain[1]!=@h.domain()[1] @h.domain h_domain refresh = true if @v_domain? if @v==@chart.v then throw Error "Layer cannot scale shared v scale, please define just v or both v and v_domain for layers" v_domain = if typeof @v_domain is 'function' then @v_domain.call(this) else @v_domain if v_domain[0] is 'auto' then v_domain[0] = @min_y() if v_domain[1] is 'auto' then v_domain[1] = @max_y() if v_domain[0]!=@v.domain()[0] or v_domain[1]!=@v.domain()[1] @v.domain v_domain refresh = true return refresh min_x: => if @x? then d3.min @data, @x max_x: => if @x? then d3.max @data, @x min_y: => if @y? then d3.min @data, @y max_y: => if @y? then d3.max @data, @y ################################################################### # XY Plot Stackable Layers ################################################################### # An **abstract** class for layers that support stacking # such as {c3.Plot.Layer.Path} and {c3.Plot.Layer.Bar}. # # **Stacking** allows the user to group their data into different _stacks_, which are stacked # on top of each other in the chart. Stacking is enabled when you define _either_ `stack_options.key`, `stacks`, # or both options. `stack_options` allows you to configure how stacking is performed from the layer's data, # while `stacks` allows you to manually configure the exact set of stacks. # # This layer stacking is flexible to support several different ways of organizing the dataset into stacks: # * For normalized datasets you can define a `stack_options.key()` accessor to provide a key that uniquely # identifies which stack an element belongs to. # * Otherwise, you can manually define the set of `stacks` and the layer's `data` is copied into each. # * * The layer `y` accessor will be called with the arguments (_datum_,_index_,_stack_) # for you to provide the value for that element for that stack. # * * Or, you can define a `y` accessor for each stack to get the value for that element for that stack. # * You can also directly define `data` in each stack specified in `stacks`. # # Please view the examples for more explanation on how to stack data. # Remember, the set and order or stacks can always be programmatically constructed and dynamically updated. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **groups** - An entry will exist for an svg:g node for each stack in the layer # # @see ../../../examples/doc/stack_example.html # @abstract # @author PI:NAME:<NAME>END_PI # @note If stacked, the input datasets may not have duplicate values in the same stack for the same X value. There are other resitrictions if `safe` mode is not used. # @note If you do not provide data elements for all stacks at all x values, then be prepared for your accessor callbacks to be called with _null_ objects. class c3.Plot.Layer.Stackable extends c3.Plot.Layer @version: 0.2 type: 'stackable' # [{c3.Selection.Options}] Enable stacking and specify stacking options for this layer. # This provides the normal {c3.Selection.Options} applied to each stack in the layer. For callbacks, # the first argument is the stack object and the second argument is the index to the stack # In addition, the following options control stacking behaviour: # * **key** [Function] An accessor you can define to return a key that uniquely identifies which stack # a data element belongs to. If this is specified, then this callback is used to determine which stack # each data element is assigned to. Otherwise, the layer data array is used in full for each stack. # * **name** [Function] A callback you define to set the name of a stack that is passed the stack key as an argument. # * **offset** [String, Function] The name or a function for the stacking algorithm used to place the data. # See {https://github.com/mbostock/d3/wiki/Stack-Layout#wiki-offset d3.stack.offset()} for details. # * * `none` - Do not stack the groups. Useful for grouped line charts. # * * `zero` - The default for a zero baseline. # * * `expand` - Normalize all points to range from 0-1. # * **order** [String] Specify the mechanism to order the stacks. # See {https://github.com/mbostock/d3/wiki/Stack-Layout#wiki-order d3.stack.order()} for details. stack_options: undefined # [Array<{c3.Plot.Layer.Stackable.Stack}>] An array of {c3.Plot.Layer.Stackable.Stack stack} # objects that can be used to manually specify the set of stacks. # Stack objects may contain: # * **key** [String] The key for this stack # * **y** [Function] A y accessor to use for this stack overriding the one provided by the chart or layer. # * **data** [Array] Manually specified dataset for this stack instead of using the layer's `data`. # * **name** [String] Name for the stack # * **options** [{c3.Selection.Options}] Options to manually set the **class**, **classes**, # **styles**, **events**, and **title** of just this stack. stacks: undefined # [Boolean] Safe Mode. # Preform additional checks and fix up the data for situations such as: # * Data not sorted along X axis # * Remove data elements where X or Y values are undefined # * Pad missing values where stacks are not defined for all X values. # Note that this mode may cause the indexes passed to the accessors to match the # corrected data instead of the original data array. safe: true # Restack the data based on the **stack** and **stacks** options. _stack: => if @stack_options or @stacks? @stacks ?= [] x_values_set = {} # Helper function to setup the current stack data and populate a shadow structure # to hold the x, y, and y0 positioning so we avoid modifying the user's data. add_value = (stack, datum, i, j)=> x = @x(datum,i); x_values_set[x] = x stack.y = stack.y ? @y ? throw Error "Y accessor must be defined in stack, layer, or chart" y = stack.y(datum, i, j, stack) stack.values.push { x:x, y:y, datum:datum } for stack, j in @stacks stack.name ?= @stack_options?.name? stack.key # Clear any previous stacking stack.values = [] # Shadow array to hold stack positioning # Data was provided manually in the stack definition if stack.data? then for datum, i in stack.data add_value stack, datum, i, j # Data has been provided in @current_data that we need to assign it to a stack if @current_data.length # Use stack_options.key() to assign data to stacks if @stack_options?.key? stack_map = {} stack_index = {} for stack, j in @stacks # Refer to hard-coded stacks if defined if stack_map[stack.key]? then throw Error "Stacks provided with duplicate keys: "+stack.key stack_map[stack.key] = stack stack_index[stack.key] = j for datum, i in @current_data key = @stack_options.key(datum) if stack_map[key]? stack = stack_map[key] j = stack_index[key] else @stacks.push stack = stack_map[key] = { key:key, name:@stack_options.name?(key), current_data:[], values:[] } j = @stacks.length add_value stack, datum, i, j # Otherwise, assign all data to all stacks using each stack's y() accessor else if @stacks? then for stack, j in @stacks for datum, i in @current_data add_value stack, datum, i, j else throw Error "Either stacks or stack_options.key must be defined to create the set of stacks." if @safe # Ensure everything is sorted # NOTE: We sort based on the @h scale in case of ordinal or other odd scales if @h.range()[0] is @h.range()[1] then @h.range [0,1] x_values = c3.array.sort_up (v for k,v of x_values_set), @h for stack in @stacks c3.array.sort_up stack.values, (v)=> @h v.x # Splice in missing data and remove undefined data (Important for D3's stack layout) i=0; while i<x_values.length undef = 0 for stack in @stacks # Check for missing values # Compare using h scale to tolerate values such as Dates stack_h = @h stack.values[i]?.x layer_h = @h x_values[i] if stack_h isnt layer_h if stack_h < layer_h # Check for duplicate X values if @h.domain()[0] is @h.domain()[1] throw Error "Did you intend for an h scale with 0 domain? Duplicate X values, invalid stacking, or bad h scale" else throw Error "Multiple data elements with the same x value in the same stack, or invalid stacking" stack.values.splice i, 0, { x:x_values[i], y:0, datum:null } undef++ # Check for undefined y values else if not stack.values[i].y? stack.values[i].y = 0 undef++ # If item is undefined for all stacks, then remove it completely if undef is @stacks.length stack.values.splice(i,1) for stack in @stacks x_values.splice(i,1) i-- i++ # Prepare array of current data for each stack in case it is needed for binding (used by bar chart) for stack in @stacks stack.current_data = stack.values.map (v)->v.datum # Configure and run the D3 stack layout to generate y0 and y layout data for the elements. if @stack_options?.offset == 'none' for stack in @stacks for value in stack.values value.y0 = 0 else stacker = d3.layout.stack().values (stack)->stack.values if @stack_options?.offset? then stacker.offset @stack_options.offset if @stack_options?.order? then stacker.order @stack_options.order stacker @stacks _update: => # Ensure data is sorted and skip elements that do not have a defined x or y value @current_data = if not @safe then @data else if @data? # TODO: we could try to use this values array later as an optimization and for more # stable i parameters passed to user accessors. However, it will complicate the code. if @y? and not @stacks? and not @stack_options? values = ({x:@x(d,i), y:@y(d,i), datum:d} for d,i in @data) c3.array.sort_up values, (v)=> @h v.x # Use @h to accomodate date types (v.datum for v in values when v.x? and v.y?) else values = ({x:@x(d,i), datum:d} for d,i in @data) if @stacks? or @stack_options? # Sorting handled by _stack() c3.array.sort_up values, (v)=> @h v.x (v.datum for v in values when v.x?) @current_data ?= [] @_stack() @groups = @content.select('g.stack') .bind (@stacks ? [null]), if not @stacks?[0]?.key? then null else (stack)->stack.key .options @stack_options, (if @stacks?.some((stack)->stack.options?) then (stack)->stack.options) .update() _style: (style_new)=> @groups?.style(style_new) min_x: => if not @stacks? then super else d3.min @stacks[0]?.values, (v)-> v.x max_x: => if not @stacks? then super else d3.max @stacks[0]?.values, (v)-> v.x min_y: => if not @stacks? then super else d3.min @stacks, (stack)-> d3.min stack.values, (v)-> v.y0 + v.y max_y: => if not @stacks? then super else d3.max @stacks, (stack)-> d3.max stack.values, (v)-> v.y0 + v.y # A _struct-type_ convention class to describe a stack when manually specifying the set of stacks # to use for a stackable chart layer. class c3.Plot.Layer.Stackable.Stack @version: 0.1 # [String] The key for this stack key: undefined # [Function] A _y accessor_ to use for this stack, overriding the one provided by the chart or layer. y: undefined # [Array] An array of data elements to use for this stack instead of the layer or chart's `data`. data: undefined # [String] Name for the stack name: undefined # [{c3.Selection.Options}] Options to manually set the **class**, **classes**, # **styles**, **events**, and **title** of just this stack. options: undefined constructor: (opt)-> c3.util.extend this, opt ################################################################### # XY Plot Line and Area Layers ################################################################### # Abstract chart layer for the {c3.Plot XY Plot Chart}. # Please instantiate a {c3.Plot.Layer.Line} or {c3.Plot.Layer.Area} # @see c3.Plot.Layer.Line # @see c3.Plot.Layer.Area # # Define an `r` or `a` to create circles at the various data points along the path # with that associated radius or area. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **paths** - There will be an element in paths for each stack in the layer # * **circles** - Circles for each datapoint # * **labels** - Labels for each datapoint # # @abstract # @author PI:NAME:<NAME>END_PI class c3.Plot.Layer.Path extends c3.Plot.Layer.Stackable @version: 0.2 type: 'path' # [Function] Factory to generate an SVG path string generator function. _See {https://github.com/mbostock/d3/wiki/SVG-Shapes#path-data-generators} for details. path_generator_factory: undefined # [String] The type of D3 line interpolation to use. _See {https://github.com/mbostock/d3/wiki/SVG-Shapes#area_interpolate d3.svg.area.interpolate} for options._ Some useful examples: # * _linear_ - Straight lines between data points # * _basis_ - Smooth curve based on a B-spline, the curve may not touch the data points # * _cardinal_ - Smooth curve that intersects all data points. # * _step-before_ - A step function where the horizontal segments are to the left of the data points # * _step-after_ - A step function where the horizontal segments are to the right of the data points interpolate: undefined # [Number] The tension value [0,1] for cardinal interpolation. _See {https://github.com/mbostock/d3/wiki/SVG-Shapes#area_tension d3.svg.area.tension}._ tension: undefined # [Function] Accessor function you can return true or false if the data point in data[] is defined or should be skipped. _See {https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-area_defined d3.svg.area.defined}._ # Note that this will cause disjoint paths on either side of the missing element, # it will not render a continuous path that skips the undefined element. For that # behaviour simply enable `safe` mode and have the x or y accessor return undefined. defined: undefined # [Number, Function] Define to create circles at the data points along the path with this radius. r: undefined # [Number, Function] Define to create circles at the data points along the path with this area. # Takes precedence over r. a: undefined # [{c3.Selection.Options}] Options for the svg:path. For example, to enable animations. path_options: undefined # [{c3.Selection.Options}] If circles are created at the data points via `r` or `a`, then this # defines options used to style or extend them. circle_options: undefined # [{c3.Selection.Options}] Create labels for each datapoint with these options label_options: undefined _init: => if not @path_generator_factory? then throw Error "path_generator_factory must be defined for a path layer" @path_generator = @path_generator_factory() _update: (origin)=> if origin isnt 'zoom' super @paths = @groups.inherit('path.scaled').options(@path_options) # Bind the datapoint circles and labels if @r? or @a? @circles = @groups.select('circle').options(@circle_options).animate(origin is 'redraw') .bind(if @stacks? then (stack)->stack.current_data else @current_data).update() if @label_options? @labels = @groups.select('text').options(@label_options).animate(origin is 'redraw') .bind(if @stacks? then (stack)->stack.current_data else @current_data).update() _draw: (origin)=> # Only need to update the paths if the data has changed if origin isnt 'zoom' # Update the path generator based on the current settings if @interpolate? then @path_generator.interpolate @interpolate if @tension? then @path_generator.tension @tension if @defined? then @path_generator.defined @defined # Generate and render the paths. orig_h = @chart.orig_h ? @h # For rendering on the scaled layer @paths.animate(origin is 'redraw').position d: if @stacks? then (stack, stack_idx)=> @path_generator .x (d,i)=> orig_h stack.values[i].x .y (d,i)=> @v (stack.values[i].y0 + stack.values[i].y) .y0? if @baseline? and not stack_idx then (d,i)=> @v c3.functor(@baseline)(d,i) else (d,i)=> @v(stack.values[i].y0) @path_generator(stack.current_data) # Call the generator with this particular stack's data else => @path_generator .x (d,i)=> orig_h @x(d,i) .y (d,i)=> @v @y(d,i) .y0? if @baseline? then (d,i)=> @v c3.functor(@baseline)(d,i) else @height @path_generator(@current_data) # Position the circles @circles?.animate(origin is 'redraw').position cx: (d,i,s)=> @h @x(d,i,s) cy: if @stacks? then (d,i,s)=> values = @stacks[s].values[i]; @v values.y+values.y0 else (d,i)=> @v @y(d,i) r: if not @a? then @r else if typeof @a is 'function' then (d,i,s)=> Math.sqrt( @a(d,i,s) / Math.PI ) else Math.sqrt( @a / Math.PI ) # Set the labels @labels?.animate(origin is 'redraw').position transform: (d,i,s)=> 'translate('+(@h @x(d,i,s))+','+(@v @y(d,i,s))+')' _style: (style_new)=> super @paths.style(style_new) @circles?.style(style_new) @labels?.style(style_new) min_x: => if not @stacks? then (if @data.length then @x @data[0]) else @stacks[0]?.values[0]?.x max_x: => if not @stacks? then (if @data.length then @x @data.slice(-1)[0]) else @stacks[0]?.values.slice(-1)[0]?.x # Line graph layer for the {c3.Plot XY Plot Chart}. Please refer to {c3.Plot.Layer.Path} for documentation. # @see c3.Plot.Layer.Path # @author PI:NAME:<NAME>END_PI class c3.Plot.Layer.Line extends c3.Plot.Layer.Path type: 'line' path_generator_factory: d3.svg.line # Area graph layer for the {c3.Plot XY Plot Chart}. Please refer to {c3.Plot.Layer.Path} for documentation. # @see c3.Plot.Layer.Path # @author PI:NAME:<NAME>END_PI # @note The input data array should be sorted along the x axis. class c3.Plot.Layer.Area extends c3.Plot.Layer.Path type: 'area' path_generator_factory: d3.svg.area # [Number, Function] Base value or accessor for the bottom of the area chart. # _Defaults to the bottom of the chart._ baseline: undefined ################################################################### # XY Plot Bar Layer ################################################################### # Bar chart layer for the {c3.Plot XY Plot Chart} # # Bar charts may have positive or negative values unless they are stacked, # then they must be positive. # # When an orinal scale is used this layer will adjust it so that it provides padding # so the full bar on the left and right ends are fully visible. With other types of scales # the bars may have arbitrary x values from the user and may overlap. In this case, it is up # to the user to set the domain so bars are fully visible. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **rects** # # @todo Support negative y values for bar layers # @author PI:NAME:<NAME>END_PI class c3.Plot.Layer.Bar extends c3.Plot.Layer.Stackable @version: 0.2 type: 'bar' # [Function] A callback to describe a unique key for each data element. # This is useful for animations during a redraw when updating the dataset. key: undefined # [Number, String, Function] Specify the width of the bars. # If this is a number it specifies the bar width in pixels. # If this is a string, such as `50%`, then it can specify the width of the bars as a # percentage of the available space for each bar based on proximity to each neighbor. # If this is a function it can set the width dynamically for each bar. bar_width: "50%" # [{c3.Selection.Options}] Options for the svg:rect's. # The callbacks are called with the user data for the rect as the first argument, the index of that # datum as the second argument, and the index of the stack for this rect as the third argument. # `stack.options` can be used instead to apply the same options to an entire stack. rect_options: undefined _update: => super @rects = @groups.select('rect').options(@rect_options).animate('origin is redraw') .bind((if @stacks? then ((stack)->stack.current_data) else @current_data), @key).update() _draw: (origin)=> baseline = @v(0) # Set bar_width and bar_shift if typeof @bar_width is 'function' bar_width = @bar_width bar_shift = -> bar_width(arguments...) / 2 else bar_width = +@bar_width if !isNaN bar_width # The user provided a simple number of pixels @h.rangeBands? @h.rangeExtent(), 1, 0.5 # Provide padding for an ordinal D3 scale bar_shift = bar_width/2 else # The user provided a percentage if @bar_width.charAt?(@bar_width.length-1) is '%' # Use charAt to confirm this is a string bar_ratio = +@bar_width[..-2] / 100 if isNaN bar_ratio then throw "Invalid bar_width percentage "+@bar_width[0..-2] if @h.rangeBands? # Setup padding for an ordinal D3 scale @h.rangeBands @h.rangeExtent(), 1-bar_ratio, 1-bar_ratio bar_width = @h.rangeBand() bar_shift = 0 else # Dynamically compute widths based on proximity to neighbors bar_width = if @stacks? then (d,i,j)=> values = @stacks[j].values mid = @h values[i].x left = @h if !i then (@chart.orig_h ? @h).domain()[0] else values[i-1].x right = @h if i==values.length-1 then (@chart.orig_h ? @h).domain()[1] else values[i+1].x width = Math.min((mid-left), (right-mid)) * bar_ratio if width >= 0 then width else 0 else (d,i)=> mid = @h @x(d,i) left = @h if !i then (@chart.orig_h ? @h).domain()[0] else @x(@current_data[i-1],i-1) right = @h if i==@current_data.length-1 then (@chart.orig_h ? @h).domain()[1] else @x(@current_data[i+1],i+1) width = Math.min((mid-left), (right-mid)) * bar_ratio if width >= 0 then width else 0 bar_shift = -> bar_width(arguments...) / 2 else throw "Invalid bar_width "+@bar_width if @stacks? x = (d,i,j)=> @h( @stacks[j].values[i].x ) y = (d,i,j)=> @v( @stacks[j].values[i].y0 + @stacks[j].values[i].y ) height = (d,i,j)=> baseline - (@v @stacks[j].values[i].y) else x = (d,i)=> @h @x(d,i) y = (d,i)=> y=@y(d,i); if y>0 then @v(y) else baseline height = (d,i)=> Math.abs( baseline - (@v @y(d,i)) ) @rects.animate(origin is 'redraw').position x: if not bar_shift then x else if typeof bar_shift isnt 'function' then -> x(arguments...) - bar_shift else -> x(arguments...) - bar_shift(arguments...) y: y height: height width: bar_width _style: (style_new)=> super @rects.style(style_new) ################################################################### # XY Plot Straight Line Layers ################################################################### # Straight **horizontal** or **vertical** line layer for the # {c3.Plot XY Plot Chart}. This is an **abstract** layer, please instantiate a # {c3.Plot.Layer.Line.Horizontal} or {c3.Plot.Layer.Line.Vertical} # directly. # # A seperate line is drawn for each data element in the `data` array. # _Set `label_options.text` to define a **label** for each line._ # Straight line layers are not _{c3.Plot.Layer.Stackable stackable}_. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **vectors** # * **lines** # * **labels** # # ## Events # * **dragstart** # * **drag** # * **dragend** # # @abstract # @author PI:NAME:<NAME>END_PI class c3.Plot.Layer.Line.Straight extends c3.Plot.Layer @version: 0.1 type: 'straight' # [Function] Optional accessor to identify data elements when changing the dataset key: undefined # [Function] Accessor to get the value for each data element. # _Defaults to the identity function._ value: undefined # [Function] Accessor to determine if data elements are filtered in or not. filter: undefined # [Boolean] Enable lines to be draggable. # The drag event callbacks can be used to adjust the original data values draggable: false # [{c3.Selection.Options}] Options for the svg:g of the vector group nodes. # There is one node per data element. Use this option for animating line movement. vector_options: undefined # [{c3.Selection.Options}] Options for the svg:line lines. line_options: undefined # [{c3.Selection.Options}] Options for the svg:line lines for hidden lines # behind each line that is wider and easier for users to interact with # e.g. for click or drag events. grab_line_options: undefined # [{c3.Selection.Options}] Define this to render labels. Options for the svg:text labels. # This option also takes the following additional properties: # * **alignment** - [String] Alignment of label. # * * `left` or `right` for horizontal lines # * * `top` or `bottom` for vertical lines # * **dx** - [String] Relative placement for the label # * **dy** - [String] Relative placement for the label label_options: undefined _init: => @value ?= (d)-> d # Draggable lines if @draggable # NOTE: Because vertical lines are rotated, we are always dragging `y` self = this @dragger = d3.behavior.drag() drag_value = undefined #drag.origin (d,i)=> { y: @scale @value(d,i) } @dragger.on 'dragstart', (d,i)=> d3.event.sourceEvent.stopPropagation() # Prevent panning in zoomable charts @trigger 'dragstart', d, i @dragger.on 'drag', (d,i)-> domain = (self.chart.orig_h ? self.scale).domain() drag_value = Math.min(Math.max(self.scale.invert(d3.event.y), domain[0]), domain[1]) d3.select(this).attr 'transform', 'translate(0,'+self.scale(drag_value)+')' self.trigger 'drag', drag_value, d, i @dragger.on 'dragend', (d,i)=> @trigger 'dragend', drag_value, d, i _size: => @lines?.all?.attr 'x2', @line_length @grab_lines?.all?.attr 'x2', @line_length @labels?.all?.attr 'x', if @label_options.alignment is 'right' or @label_options.alignment is 'top' then @width else 0 _update: (origin)=> @current_data = if @filter? then (d for d,i in @data when @filter(d,i)) else @data @vectors = @content.select('g.vector').options(@vector_options).animate(origin is 'redraw') .bind(@current_data, @key).update() @lines = @vectors.inherit('line').options(@line_options).update() if @label_options? @label_options.dx ?= '0.25em' @label_options.dy ?= '-0.25em' @labels = @vectors.inherit('text').options(@label_options).update() # Add extra width for grabbable line area if @draggable or @grab_line_options @grab_lines = @vectors.inherit('line.grab') if @grab_line_options then @grab_lines.options(@grab_line_options).update() if @draggable @vectors.new.call @dragger _draw: (origin)=> @vectors.animate(origin is 'redraw').position transform: (d,i)=> 'translate(0,' + (@scale @value(d,i)) + ')' @lines.new.attr 'x2', @line_length @grab_lines?.new.attr 'x2', @line_length if @labels? far_labels = @label_options.alignment is 'right' or @label_options.alignment is 'top' @g.style 'text-anchor', if far_labels then 'end' else 'start' @labels.position dx: if far_labels then '-'+@label_options.dx else @label_options.dx dy: @label_options.dy x: if far_labels then @line_length else 0 _style: (style_new)=> @g.classed 'draggable', @draggable @vectors.style(style_new) @lines.style(style_new) @grab_lines?.style?(style_new) @labels?.style?(style_new) # Horizontal line layer. Please refer to {c3.Plot.Layer.Line.Straight} for documentation. # @see c3.Plot.Layer.Line.Straight class c3.Plot.Layer.Line.Horizontal extends c3.Plot.Layer.Line.Straight type: 'horizontal' _init: => label_options?.alignment ?= 'left' super @scale = @v _size: => @line_length = @width super # Vertical line layer. Please refer to {c3.Plot.Layer.Line.Straight} for documentation. # @see c3.Plot.Layer.Line.Straight class c3.Plot.Layer.Line.Vertical extends c3.Plot.Layer.Line.Straight type: 'vertical' _init: => label_options?.alignment ?= 'top' super @scale = @h _size: => @g.attr transform: 'rotate(-90) translate('+-@height+',0)' @line_length = @height super ################################################################### # XY Plot Region Layers ################################################################### # Render a rectangular region in an {c3.Plot XY Plot Chart}. # # Define `x` and `x2` options for vertical regions, # `y` and `y2` for horizontal regions, or all four for rectangular regions. # # The regions may be enabled to be `draggable` and/or `resizable`. # The chart will move or resize the region interactively, however it is up to # the user code to modify the data elements based on the `drag` or `dragend` # events. These callbacks are called with a structure of the new values and # the data element as parameters. The structure of new values is an object # with `x`, `x2` and `y`, `y2` members. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **regions** # * **rects** # # ## Events # * **dragstart** - called with the data element. # * **drag** - called with the new position and the data element. # * **dragend** - called with the new position and the data element. # # @author PI:NAME:<NAME>END_PI class c3.Plot.Layer.Region extends c3.Plot.Layer type: 'region' _init: => if (@x? and !@x2?) or (!@x? and @x2?) or (@y? and !@y2?) or (!@y? and @y2?) throw Error "x and x2 options or y and y2 options must either be both defined or undefined" # Draggable lines if @draggable or @resizable drag_value = undefined origin = undefined self = this @dragger = d3.behavior.drag() .origin (d,i)=> x: if @x? then @h @x d,i else 0 y: if @y? then @v @y d,i else 0 .on 'drag', (d,i)-> h_domain = (self.orig_h ? self.h).domain() v_domain = self.v.domain() if self.x? width = self.x2(d) - self.x(d) x = Math.min(Math.max(self.h.invert(d3.event.x), h_domain[0]), h_domain[1]-width) if self.y? height = self.y2(d) - self.y(d) y = Math.min(Math.max(self.v.invert(d3.event.y), v_domain[0]), v_domain[1]-height) # Run values through scale round-trip in case it is a time scale. drag_value = x: if x? then self.h.invert self.h x x2: if x? then self.h.invert self.h x + width y: if y? then self.v.invert self.v y y2: if y? then self.v.invert self.v y + height if self.x? then d3.select(this).attr 'x', self.h drag_value.x if self.y? then d3.select(this).attr 'y', self.v drag_value.y2 self.trigger 'drag', drag_value, d, i @left_resizer = d3.behavior.drag() .origin (d,i)=> x: @h @x d, i .on 'drag', (d,i)-> h_domain = (self.orig_h ? self.h).domain() x = Math.min(Math.max(self.h.invert(d3.event.x), h_domain[0]), h_domain[1]) x2 = self.x2 d drag_value = x: self.h.invert self.h Math.min(x, x2) x2: self.h.invert self.h Math.max(x, x2) y: if self.y? then self.y(d) y2: if self.y2? then self.y2(d) d3.select(this.parentNode).select('rect').attr x: self.h drag_value.x width: self.h(drag_value.x2) - self.h(drag_value.x) self.trigger 'drag', drag_value, d, i @right_resizer = d3.behavior.drag() .origin (d,i)=> x: @h @x2 d, i .on 'drag', (d,i)-> h_domain = (self.orig_h ? self.h).domain() x = Math.min(Math.max(self.h.invert(d3.event.x), h_domain[0]), h_domain[1]) x2 = self.x d drag_value = x: self.h.invert self.h Math.min(x, x2) x2: self.h.invert self.h Math.max(x, x2) y: if self.y? then self.y(d) y2: if self.y2? then self.y2(d) d3.select(this.parentNode).select('rect').attr x: self.h drag_value.x width: self.h(drag_value.x2) - self.h(drag_value.x) self.trigger 'drag', drag_value, d, i @top_resizer = d3.behavior.drag() .origin (d,i)=> y: @v @y2 d, i .on 'drag', (d,i)-> v_domain = self.v.domain() y = Math.min(Math.max(self.v.invert(d3.event.y), v_domain[0]), v_domain[1]) y2 = self.y d drag_value = x: if self.x? then self.x(d) x2: if self.x2? then self.x2(d) y: self.v.invert self.v Math.min(y, y2) y2: self.v.invert self.v Math.max(y, y2) d3.select(this.parentNode).select('rect').attr y: self.v drag_value.y2 height: self.v(drag_value.y) - self.v(drag_value.y2) self.trigger 'drag', drag_value, d, i @bottom_resizer = d3.behavior.drag() .origin (d,i)=> y: @v @y d, i .on 'drag', (d,i)-> v_domain = self.v.domain() y = Math.min(Math.max(self.v.invert(d3.event.y), v_domain[0]), v_domain[1]) y2 = self.y2 d drag_value = x: if self.x? then self.x(d) x2: if self.x2? then self.x2(d) y: self.v.invert self.v Math.min(y, y2) y2: self.v.invert self.v Math.max(y, y2) d3.select(this.parentNode).select('rect').attr y: self.v drag_value.y2 height: self.v(drag_value.y) - self.v(drag_value.y2) self.trigger 'drag', drag_value, d, i for dragger in [@dragger, @left_resizer, @right_resizer, @top_resizer, @bottom_resizer] dragger .on 'dragstart', (d,i)=> d3.event.sourceEvent.stopPropagation() # Prevent panning in zoomable charts @trigger 'dragstart', d, i .on 'dragend', (d,i)=> @trigger 'dragend', drag_value, d, i @_draw() # reposition the grab lines for the moved region _size: => if not @x? @rects?.all.attr 'width', @width @left_grab_lines?.all.attr 'width', @width @right_grab_lines?.all.attr 'width', @width if not @y? @rects?.all.attr 'height', @height @top_grab_lines?.all.attr 'height', @height @bottom_grab_lines?.all.attr 'height', @height _update: (origin)=> @current_data = if @filter? then (d for d,i in @data when @filter(d,i)) else @data @regions = @content.select('g.region').options(@region_options).animate(origin is 'redraw') .bind(@current_data, @key).update() @rects = @regions.inherit('rect').options(@rect_options).update() if @draggable @rects.new.call @dragger # Add extra lines for resizing regions if @resizable if @x? @left_grab_lines = @regions.inherit('line.grab.left') @left_grab_lines.new.call @left_resizer if @x2? @right_grab_lines = @regions.inherit('line.grab.right') @right_grab_lines.new.call @right_resizer if @y? @top_grab_lines = @regions.inherit('line.grab.top') @top_grab_lines.new.call @top_resizer if @y2? @bottom_grab_lines = @regions.inherit('line.grab.bottom') @bottom_grab_lines.new.call @bottom_resizer _draw: (origin)=> @rects.animate(origin is 'redraw').position x: (d)=> if @x? then @h @x d else 0 width: (d)=> if @x2? then @h(@x2(d))-@h(@x(d)) else @width y: (d)=> if @y2? then @v @y2 d else 0 height: (d)=> if @y? then @v(@y(d))-@v(@y2(d)) else @height if @resizable @left_grab_lines?.animate(origin is 'redraw').position x1: (d)=> @h @x d x2: (d)=> @h @x d y1: (d)=> if @y? then @v @y d else 0 y2: (d)=> if @y2? then @v @y2 d else @height @right_grab_lines?.animate(origin is 'redraw').position x1: (d)=> @h @x2 d x2: (d)=> @h @x2 d y1: (d)=> if @y? then @v @y d else 0 y2: (d)=> if @y2? then @v @y2 d else @height @top_grab_lines?.animate(origin is 'redraw').position x1: (d)=> if @x? then @h @x d else 0 x2: (d)=> if @x2? then @h @x2 d else @width y1: (d)=> @v @y2 d y2: (d)=> @v @y2 d @bottom_grab_lines?.animate(origin is 'redraw').position x1: (d)=> if @x? then @h @x d else 0 x2: (d)=> if @x2? then @h @x2 d else @width y1: (d)=> @v @y d y2: (d)=> @v @y d _style: (style_new)=> @g.classed 'draggable': @draggable 'horizontal': not @x? 'vertical': not @y? @regions.style style_new @rects.style style_new ################################################################### # XY Plot Scatter Layer ################################################################### # Scatter plot layer for the {c3.Plot XY Plot Chart} # # Datapoints include a circle and an optional label. # _Set `label_options.text` to define the label for each point._ # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **points** - Representing svg:g nodes for each datapoint # * **circles** - Representing svg:circle nodes for each datapoint # * **labels** - Representing svg:text labels for each datapoint # @author PI:NAME:<NAME>END_PI # @todo Only render datapoints within the current zoomed domain. class c3.Plot.Layer.Scatter extends c3.Plot.Layer @version: 0.1 type: 'scatter' # [Function] Accessor function to define a unique key to each data point. This has performance implications. # _This is required to enable **animations**._ key: undefined # [Function, Number] Accessor or value to set the value for each data point. # This is used when limiting the number of elements. value: undefined # [Function, Number] Accessor or value to set the circle radius r: 1 # [Function, Number] Accessor or value to set the circle area. _Takes precedence over r._ a: undefined # [Boolean] Safe mode will not render data where a positioning accessor returns undefined. # _This may cause the index passed to accessors to not match the original data array._ safe: true # [Function] Accessor to determine if the data point should be drawn or not # _This may cause the index passed to accessors to not match the original data array._ filter: undefined # [Number] Limit the number of data points. # _This may cause the index passed to accessors to not match the original data array._ limit_elements: undefined # [{c3.Selection.Options}] Options for svg:g nodes for each datapoint. point_options: undefined # [{c3.Selection.Options}] Options for the svg:circle of each datapoint circle_options: undefined # [{c3.Selection.Options}] Options for the svg:text lables of each datapoint. label_options: undefined _init: => if not @x? then throw Error "x must be defined for a scatter plot layer" if not @y? then throw Error "y must be defined for a scatter plot layer" if not @h? then throw Error "h must be defined for a scatter plot layer" if not @v? then throw Error "v must be defined for a scatter plot layer" _update: (origin)=> if not @data then throw Error "Data must be defined for scatter layer." # Filter the data for safety @current_data = if @filter? and @key? then (d for d,i in @data when @filter(d,i)) else @data if @safe then @current_data = (d for d in @current_data when ( @x(d)? and @y(d)? and (!@a? or typeof @a!='function' or @a(d)?) and (typeof @r!='function' or @r(d)?) )) # Limit the number of elements? if @limit_elements? if @value? @current_data = @current_data[..] # Copy the array to avoid messing up the user's order c3.array.sort_up @current_data, (d)=> -@value(d) # Sort by negative to avoid reversing array @current_data = @current_data[..@limit_elements] else @current_data = @current_data[..@limit_elements] # Bind and create the elements @points = @content.select('g.point').options(@point_options).animate(origin is 'redraw') .bind(@current_data, @key).update() # If there is no key, then hide the elements that are filtered if @filter? and not @key? @points.all.attr 'display', (d,i)=> if not @filter(d,i) then 'none' # Add circles to the data points @circles = @points.inherit('circle').options(@circle_options).animate(origin is 'redraw').update() # Add labels to the data points if @label_options? @labels = @points.inherit('text').options(@label_options).update() _draw: (origin)=> @points.animate(origin is 'redraw').position transform: (d,i)=> 'translate('+(@h @x(d,i))+','+(@v @y(d,i))+')' @circles.animate(origin is 'redraw').position r: if not @a? then @r else if typeof @a is 'function' then (d,i)=> Math.sqrt( @a(d,i) / Math.PI ) else Math.sqrt( @a / Math.PI ) _style: (style_new)=> @points.style(style_new) @circles.style(style_new) @labels?.style(style_new) ################################################################### # XY Plot Swimlane Layers ################################################################### # Base abstract class for {c3.Plot XY Plot} {c3.Plot.Layer layers} with horizontal swim lanes. # Swimlanes are numbered based on the vertical scale domain for the layer. # The first entry in the domain is the top swimlane and the last entry is the bottom swimlane plus 1. # If the first and last domain values are equal, then there are no swimlanes rendered. # # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **lanes** - svg:rect's for each swimlane # * **tip** - HTML hover content # @abstract # @author PI:NAME:<NAME>END_PI class c3.Plot.Layer.Swimlane extends c3.Plot.Layer type: 'swimlane' # [String] `top` for 0 to be at the top, `bottom` for the bottom. # Swimlanes default to 0 at the top. v_orient: 'top' # [Number] Height of a swimlane in pixels. # Chart height will be adjusted if number of swimlanes changes in a redraw() dy: undefined # [Function] Provide HTML content for a hover div when mousing over the layer # This callback will be called with the datum and index of the item being hovered over. # It will be called with null when hovering over the layer but not any data items. hover: undefined # [{c3.Selection.Options}] Options for the lane svg:rect nodes for swimlanes lane_options: undefined _init: => if @lane_options? then @lanes = @content.select('rect.lane',':first-child').options(@lane_options) # Support html hover tooltips if @hover? anchor = d3.select(@chart.anchor) @tip = c3.select( anchor, 'div.c3.hover' ).singleton() layer = this mousemove = -> [layerX,layerY] = d3.mouse(this) # Get swimlane and ensure it is properly in range (mouse may be over last pixel) swimlane = Math.floor layer.v.invert layerY swimlane = Math.min swimlane, Math.max layer.v.domain()[0], layer.v.domain()[1]-1 x = layer.h.invert layerX hover_datum = layer._hover_datum(x, swimlane) hover_html = (c3.functor layer.hover)( hover_datum, (if hover_datum then layer.data.indexOf(hover_datum) else null), swimlane ) if not hover_html layer.tip.all.style 'display', 'none' else layer.tip.all.html hover_html layer.tip.all.style display: 'block' left: d3.event.clientX+'px' top: d3.event.clientY+'px' # Manage tooltip event handlers, disable while zooming/panning @chart.content.all.on 'mouseleave.hover', => layer.tip.all.style 'display', 'none' @chart.content.all.on 'mousedown.hover', => layer.tip.all.style 'display', 'none' @chart.content.all.on 'mousemove.hover', null @chart.content.all.on 'mouseup.hover', => @chart.content.all.on 'mousemove.hover', mousemove @chart.content.all.on 'mouseenter.hover', => if !d3.event.buttons then @chart.content.all.on 'mousemove.hover', mousemove @chart.content.all.on 'mousemove.hover', mousemove _size: => # If @dy is not defined, we determine it based on the chart height if not @y? then @dy = @height else @dy ?= Math.round @height / (Math.abs(@v.domain()[1]-@v.domain()[0])) # If a swimlane starts at the bottom, then shift up by dy because SVG always # renders the height of element downward. @g.attr 'transform', if @v_orient is 'bottom' then 'translate(0,-'+@dy+')' else '' _update: => # Support constant values and accessors @x = c3.functor @x @dx = c3.functor @dx @lanes?.bind([@v.domain()[0]...@v.domain()[1]]).update() # Update chart height to fit current number of swimlanes based on current v domain if @y? then @chart.size null, @dy*(Math.abs(@v.domain()[1]-@v.domain()[0])) + @chart.margins.top + @chart.margins.bottom _draw: (origin)=> if origin is 'resize' or origin is 'render' @lanes?.position y: (lane)=> @v lane width: @chart.orig_h.range()[1] height: @dy _style: => @lanes?.style() ################################################################### # XY Plot Segment Swimlane Layer ################################################################### # A {c3.Plot.Layer.Swimlane swimlane layer} for drawing horizontal segments in each swimlane. # # _Set `label_options.text` to define labels for the segments._ # The following {c3.Selection} members are made available if appropriate: # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **rects** - svg:rect for each segment # @todo Better threshold for determining which segments get labels. _Currently it is any segment > 50 pixels wide._ # @author PI:NAME:<NAME>END_PI class c3.Plot.Layer.Swimlane.Segment extends c3.Plot.Layer.Swimlane @version: 0.1 type: 'segment' # **REQUIRED** [Function] Accessor to get the width of the segment dx: null # [Function] Key accessor to uniquely identify the segment. # Defining this improves performance for redraws. key: undefined # [Function] Accessor to determine if an element should be rendered filter: undefined # [Function] Value accessor for each segment. Used when limiting the number of elements. _Defaults to dx._ value: undefined # [Number] Specifies the maximum number of segments this layer will draw. Smaller segments are elided first. limit_elements: undefined # [{c3.Selection.Options}] Options for the svg:rect nodes for each segment rect_options: undefined # [{c3.Selection.Options}] Options for the label svg:text nodes for each segment label_options: undefined # IE10/11 doesn't support vector-effects: non-scaling-stroke, so avoid using scaled SVG. # This is a performance hit, because then we have to adjust the position of all rects for each redraw # TODO: Investigate if they added support for this in Edge. #scaled = !window.navigator.userAgent.match(/MSIE|Trident/) # MSIE==IE10, Trident==IE11, Edge==Edge # [3/18/2016] Disable the SVG scaled layer optimization completely for now. # If there are very large domains (e.g. a billion) then there is a floating-point precision problem # relying on SVG transformations to do the scaling/translation. # This doesn't seem to be a problem if we do the scaling ourselves in JavaScript. scaled = false _init: => super @g.classed 'segment', true # Manually do this so inherited types also have this class if scaled then @scaled_g = @g.append('g').attr('class','scaled') @rects_group = c3.select((@scaled_g ? @g),'g.segments').singleton() if @label_options? then @labels_clip = c3.select(@g,'g.labels').singleton().select('svg') _hover_datum: (x, swimlane)=> right = @h.invert @h(x)+1 # Get the pixel width for datum,idx in @current_data if (!@y? or @y(datum)==swimlane) and (_x=@x(datum)) <= right and x <= _x+@dx(datum) then break return if idx==@current_data.length then null else datum _update: => super # Pull filtered data elements @current_data = if not @filter? then @data else (d for d,i in @data when @filter(d,i)) # Pre-sort data by "value" for limiting to the most important elements if @limit_elements? if not @filter? then @current_data = @current_data[..] c3.array.sort_down @current_data, (@value ? @dx) _draw: (origin)=> super # Gather data for the current viewport domain [left_edge, right_edge] = @h.domain() half_pixel_width = (right_edge-left_edge) / ((@h.range()[1]-@h.range()[0]) || 1) / 2 data = [] for datum in @current_data when (x=@x(datum)) < right_edge and (x+(dx=@dx(datum))) > left_edge if dx < half_pixel_width if @limit_elements? then break else continue data.push datum if data.length == @limit_elements then break # Bind here because the current data set is dynamic based on zooming @rects = @rects_group.select('rect.segment').options(@rect_options).bind(data, @key).update() # Position the rects h = if @scaled_g? then (@chart.orig_h ? @h) else @h zero_pos = h(0) (if origin is 'resize' then @rects.all else @rects.new).attr 'height', @dy (if !scaled or !@key? or origin=='resize' or (origin=='redraw' and this instanceof c3.Plot.Layer.Swimlane.Flamechart) then @rects.all else @rects.new).attr x: (d)=> h @x(d) width: (d)=> (h @dx(d)) - zero_pos y: if not @y? then 0 else (d)=> @v @y(d) # Bind and render lables here (not in _update() since the set is dynamic based on zooming and resizing) if @label_options? # Create labels in a nested SVG node so we can crop them based on the segment size. zero_pos = @h(0) current_labels = (datum for datum in data when (@h @dx datum)-zero_pos>50) @labels_clip.bind(current_labels, @key) @labels = @labels_clip.inherit('text').options(@label_options).update() (if origin is 'resize' then @labels_clip.all else @labels_clip.new).attr 'height', @dy @labels_clip.position x: (d)=> @h @x(d) y: if not @y? then 0 else (d,i)=> @v @y(d,i) width: (d)=> (@h @dx(d)) - zero_pos self = this (if origin is 'resize' then @labels.all else @labels.new).attr 'y', self.dy/2 @labels.position x: (d)-> x = self.x(d) dx = self.dx(d) left = Math.max x, self.h.domain()[0] right = Math.min x+dx, self.h.domain()[1] return self.h( (right-left)/2 + (left-x) ) - zero_pos # x: (d)-> # x = self.x(d) # dx = self.dx(d) # left = Math.max x, self.h.domain()[0] # right = Math.min x+dx, self.h.domain()[1] # # NOTE: This is expensive. Chrome was faster with offsetWidth, but Firefox and IE11 didn't support it # text_width = this.offsetWidth ? this.getBBox().width # if self.h(right-left)-zero_pos > text_width # return self.h( (right-left)/2 + (left-x) ) - zero_pos - (text_width/2) # else # return if x < left then self.h(left-x)-zero_pos+1 else 1 else c3.select(@g,'g.labels').all.remove() delete @labels # Style any new elements we added by resizing larger that allowed new relevant elements to be drawn if origin is 'resize' and (not @rects.new.empty() or (@labels? and not @labels.new.empty())) @_style true _style: (style_new)=> super @rects.style(style_new) @labels?.style(style_new) ################################################################### # Flamechart ################################################################### # A {c3.Plot.Layer.Swimlane swimlane layer} for rendering _flamecharts_ or _flamegraphs_. # # In C3, both a {c3.Plot.Layer.Swimlane.Flamechart Flamechart} and an # {c3.Plot.Layer.Swimlane.Icicle Icicle} can actually grow either up or down # depending if you set `v_orient` as `top` or `bottom`. # A _Flamechart_ defaults to growing up and an _Icicle_ defaults to growing down. # In C3, a {c3.Plot.Layer.Swimlane.Flamechart Flamechart} visualizes a timeline # of instances of nested events over time, while an {c3.Plot.Layer.Swimlane.Icicle Icicle} # visualizes an aggregated tree hierarchy of nodes. The {c3.Polar.Layer.Sunburst Sunburst} # is the equivalent of an _Icicle_ rendered on a polar axis. # # A `key()` is required for this layer. # You should not define `y`, but you must define a `x`, `dx`, and `dy`. # # @author PI:NAME:<NAME>END_PI class c3.Plot.Layer.Swimlane.Flamechart extends c3.Plot.Layer.Swimlane.Segment @version: 0.1 type: 'flamechart' # [String] `top` for 0 to be at the top, `bottom` for the bottom. # Flamechart defaults to bottom-up. v_orient: 'bottom' _init: => super if not @key? then throw Error "`key()` accessor function is required for Flamechart layers" if not @dy? then throw Error "`dy` option is required for Flamechart layers" if @y? then throw Error "`y` option cannot be defined for Flamechart layers" @y = (d)=> @depths[@key d] @depths = {} _update: (origin)=> super # Compute depths for each data element data = @current_data[..] c3.array.sort_up data, @x max_depth = 0 stack = [] for datum in data frame = x: @x datum dx: @dx datum while stack.length and frame.x >= (_frame=stack[stack.length-1]).x + _frame.dx stack.length-- stack.push frame max_depth = Math.max max_depth, stack.length # stack.length is starting from 0, so don't reduce by one. @depths[@key datum] = stack.length - 1 # Set the vertical domain and resize chart based on maximum flamechart depth @v.domain [0, max_depth] c3.Plot.Layer.Swimlane::_update.call this, origin ################################################################### # Icicle ################################################################### # A {c3.Plot.Layer.Swimlane swimlane layer} for rendering _icicle_ charts. # # In C3, both a {c3.Plot.Layer.Swimlane.Flamechart Flamechart} and an # {c3.Plot.Layer.Swimlane.Icicle Icicle} can actually grow either up or down # depending if you set `v_orient` as `top` or `bottom`. # A _Flamechart_ defaults to growing up and an _Icicle_ defaults to growing down. # In C3, a {c3.Plot.Layer.Swimlane.Flamechart Flamechart} visualizes a timeline # of instances of nested events over time, while an {c3.Plot.Layer.Swimlane.Icicle Icicle} # visualizes an aggregated tree hierarchy of nodes. The {c3.Polar.Layer.Sunburst Sunburst} # is the equivalent of an _Icicle_ rendered on a polar axis. # # A `key()` is required for this layer. # You should not define `x` or `y`, but you must define `dy`. # Specify a callback for either `parent_key`, # `children`, or `children_keys` to describe the hierarchy. # If using `parent_key` or `children_keys` the `data` array shoud include all nodes, # if using `children` it only should include the root nodes. # Define either `value()` or `self_value()` to value the nodes in the hierarchy. # # If you care about performance, you can pass the # parameter `revalue` to `redraw('revalue')` if you are keeping the same dataset # hierarchy, and only changing the element's values. # The Icicle layer can use a more optimized algorithm in this situation. # # ## Events # * **rebase** Called with the datum of a node when it becomes the new root # or with `null` if reverting to the top of the hierarchy. # # @author PI:NAME:<NAME>END_PI class c3.Plot.Layer.Swimlane.Icicle extends c3.Plot.Layer.Swimlane @version: 0.1 type: 'icicle' # **REQUIRED** [Function] Accessor function to define a unique key for each data element. # _This has performance implications and is required for some layers and **animations**._ key: undefined # [Function] Accessor to get the "_total_" value of the data element. # That is the total value of the element itself inclusive of all of it's children's value. # You can define either _value_ or _self_value_. value: undefined # [Function] The `value` accessor defines the "_total_" value for an element, that is the value of # the element itself plus that of all of its children. If you know the "self" value of an # element without the value of its children, then define this callback accessor instead. # The `value` option will then also be defined for you, which you can use to get the total value # of an element after the layer has been drawn. self_value: undefined # [Function] A callback that should return the key of the parent of an element. # It is called with a data element as the first parameter. parent_key: undefined # [Function] A callback that should return an array of child keys of an element. # The returned array may be empty or null. # It is called with a data element as the first parameter. children_keys: undefined # [Function] A callback that should return an array of children elements of an element. # The returned array may be empty or null. # It is called with a data element as the first parameter. children: undefined # [Boolean, Function] How to sort the partitioned tree segments. # `true` sorts based on _total_ value, or you can define an alternative # accessor function to be used for sorting. sort: false # [Number] Limit the number of data elements to render based on their value. # _This affects the callback index parameter_ limit_elements: undefined # [Number] Don't bother rendering segments whose value is smaller than this # percentage of the current domain focus. (1==100%) limit_min_percent: 0.001 # Data element that represents the root of the hierarchy to render. # If this is specified, then only this root and its parents and children will be rendered # When {c3.Plot.Layer.Icicle#rebase rebase()} is called or a node is clicked on # it will animate the transition to a new root node, if animation is enabled. root_datum: null # [{c3.Selection.Options}] Options for the svg:rect nodes for each segment rect_options: undefined # [{c3.Selection.Options}] Options for the label svg:text nodes for each segment label_options: undefined _init: => super if not @key? then throw Error "`key()` accessor function is required for Icicle layers" if not @dy? then throw Error "`dy` option is required for Icicle layers" if @x? then throw Error "`x` option cannot be defined for Icicle layers" if @y? then throw Error "`y` option cannot be defined for Icicle layers" @y = (datum)=> @nodes[@key datum].y1 @segments_g = c3.select(@g, 'g.segments').singleton() @segment_options = { events: { click: (d)=> @rebase if d isnt @root_datum then d else (if @parent_key? then @nodes[@parent_key d] else @nodes[@key d].parent)?.datum } } @label_clip_options = {} if @label_options? @label_options.animate ?= @rect_options.animate @label_options.duration ?= @rect_options.duration @label_clip_options.animate ?= @rect_options.animate @label_clip_options.duration ?= @rect_options.duration _hover_datum: (x, swimlane)=> right = @h.invert @h(x)+1 # Get the pixel width for key,node of @nodes if node.y1 is swimlane and node.x1 <= right and x <= node.x2 return node.datum return null _update: (origin)=> super # Construct the tree hierarchy if origin isnt 'revalue' and origin isnt 'rebase' @tree = new c3.Layout.Tree key: @key, parent_key: @parent_key, children_keys: @children_keys, children: @children value: @value, self_value: @self_value @nodes = @tree.construct @data # Set the vertical domain and resize chart based on maximum flamechart depth @v.domain [0, d3.max Object.keys(@nodes), (key)=> @nodes[key].y2] c3.Plot.Layer.Swimlane::_update.call this, origin # Compute the "total value" of each node if origin isnt 'rebase' @value = @tree.revalue() # Partition the arc segments based on the node values # We need to do this even for 'rebase' in case we shot-circuited previous paritioning @current_data = @tree.layout( if origin isnt 'revalue' and origin isnt 'rebase' then @sort else false @limit_min_percent @root_datum ) # Limit the number of elements to bind to the DOM if @current_data.length > @limit_elements c3.array.sort_up @current_data, @value # sort_up is more efficient than sort_down @current_data = @current_data[-@limit_elements..] # Bind data elements to the DOM @segment_options.animate = @rect_options?.animate @segment_options.animate_old = @rect_options?.animate @segment_options.duration = @rect_options?.duration @segments = @segments_g.select('g.segment').options(@segment_options) .animate(origin is 'redraw' or origin is 'revalue' or origin is 'rebase') .bind(@current_data, @key).update() @rect_options?.animate_old ?= @rect_options?.animate @rects = @segments.inherit('rect').options(@rect_options).update() if @label_options? @label_clip_options.animate_old = @label_options?.animate @label_clips = @segments.inherit('svg.label').options(@label_clip_options) _draw: (origin)=> super # Set the horizontal domain based on the root node. prev_h = @h.copy() prev_zero_pos = prev_h(0) root_node = @nodes[@key @root_datum] if @root_datum? @h.domain [root_node?.x1 ? 0, root_node?.x2 ? 1] zero_pos = @h(0) # Position the segments. # Place any new segments where they would have been if not decimated. (if origin is 'resize' then @rects.all else @rects.new).attr 'height', @dy @rects.animate(origin is 'redraw' or origin is 'revalue' or origin is 'rebase').position { x: (d)=> @h @nodes[@key d].x1 y: (d)=> @v @nodes[@key d].y1 width: (d)=> @h((node=@nodes[@key d]).x2 - node.x1) - zero_pos }, { x: (d)=> prev_h @nodes[@key d].px1 y: (d)=> @v @nodes[@key d].py1 width: (d)=> prev_h((node=@nodes[@key d]).px2 - node.px1) - prev_zero_pos } if @label_options? (if origin is 'resize' then @rects.all else @rects.new).attr 'height', @dy @label_clips.animate(origin is 'redraw' or origin is 'revalue' or origin is 'rebase').position { x: (d)=> @h @nodes[@key d].x1 y: (d)=> @v @nodes[@key d].y1 width: (d)=> @h((node=@nodes[@key d]).x2 - node.x1) - zero_pos }, { x: (d)=> prev_h @nodes[@key d].px1 y: (d)=> @v @nodes[@key d].py1 width: (d)=> prev_h((node=@nodes[@key d]).px2 - node.px1) - prev_zero_pos } # Bind and position labels for larger segments. @labels = c3.select( @label_clips.all.filter((d)=> @h((node=@nodes[@key d]).x2 - node.x1) - zero_pos >= 50) ).inherit('text', 'restore') .options(@label_options).update() .animate(origin is 'redraw' or origin is 'revalue' or origin is 'rebase').position y: @dy / 2 x: (d)=> node = @nodes[@key d] left = Math.max node.x1, @h.domain()[0] right = Math.min node.x2, @h.domain()[1] return @h( (right-left)/2 + (left-node.x1) ) - zero_pos # Remove any stale labels from segments that are now too small @segments.all .filter((d)=> @h((node=@nodes[@key d]).x2 - node.x1) - zero_pos < 50) .selectAll('text') .transition('fade').duration(@label_options.duration).style('opacity',0) .remove() else @segments.all.selectAll('text').remove() delete @labels # Style any new elements we added by resizing larger that allowed new relevant elements to be drawn if origin is 'resize' and (not @rects.new.empty() or (@labels? and not @labels.new.empty())) @_style true _style: (style_new)=> super @rects.style(style_new) @labels?.style(style_new) # Navigate to a new root node in the hierarchy representing the `datum` element rebase: (@root_datum)=> @trigger 'rebase_start', @root_datum @chart.redraw 'rebase' # redraw all layers, since the scales will change @trigger 'rebase', @root_datum # Navigate to a new root node in the hierarchy represented by `key` rebase_key: (root_key)=> @rebase @nodes[root_key]?.datum ################################################################### # XY Plot Sampled Swimlane Layers ################################################################### # A {c3.Plot.Layer.Swimlane swimlane layer} that will sample for each pixel in each swimlane. # @abstract # @author PI:NAME:<NAME>END_PI class c3.Plot.Layer.Swimlane.Sampled extends c3.Plot.Layer.Swimlane @version: 0.0 type: 'sampled' # **REQUIRED** [Function] Accessor to get the width of the segment dx: null # [Function] Callback to determine if the data element should be rendered or not filter: undefined # [Boolean] If safe mode is off then it is assumed the data is sorted by the x-axis safe: true _hover_datum: (x, swimlane)=> data = @swimlane_data[swimlane] right = @h.invert @h(x)+1 # Get the pixel width idx = d3.bisector(@x).right(data, x) - 1 return if idx<0 then null else if x < @x(datum=data[idx])+@dx(datum) then datum else if ++idx<data.length and @x(datum=data[idx]) <= right then datum else null _update: => super # Arrange data by swimlane and remove filtered items @swimlane_data = [] @swimlane_data[swimlane] = [] for swimlane in [@v.domain()[0]...@v.domain()[1]] [top_edge, bottom_edge] = @v.domain() for datum, i in @data when (!@filter? or @filter(datum,i)) swimlane = @y datum, i if top_edge <= swimlane < bottom_edge then @swimlane_data[swimlane].push datum # Sort data in safe mode if @safe c3.array.sort_up(data,@x) for data in @swimlane_data _sample: (sample)=> # Sample data points for each pixel in each swimlane bisector = d3.bisector(@x).right for swimlane in [@v.domain()[0]...@v.domain()[1]] v = @v swimlane data = @swimlane_data[swimlane] if not data.length then continue # Optimized to find the left starting point prev_idx = bisector(data, @h.domain()[0]) if not prev_idx pixel = Math.round @h @x @data[prev_idx] else prev_idx-- pixel = if @h(@x(@data[prev_idx])+@dx(@data[prev_idx])) > 0 then 0 else Math.round @h @x data[prev_idx] # Iterate through each pixel in this swimlane while pixel < @width x = @h.invert(pixel) # Find the next data element for this pixel, or skip to the next pixel if there is a gap idx = prev_idx while idx < data.length datum = data[idx] prev_idx = idx if (datum_x=@x(datum)) > x pixel = Math.round @h datum_x break if x <= datum_x+@dx(datum) then break idx++ if idx==data.length then break sample pixel, v, datum pixel++ return # avoid returning a comprehension # A {c3.Plot.Layer.Swimlane.Sampled sampled swimlane layer} implemented via SVG lines # ## Extensibility # The following {c3.Selection} members are made available if appropriate: # * **lines** - svg:rect's for each swimlane # @todo Optimize by generating pixel data array once in _size() and reusing it in _draw() class c3.Plot.Layer.Swimlane.Sampled.SVG extends c3.Plot.Layer.Swimlane.Sampled @version: 0.0 type: 'svg' # [{c3.Selection.Options}] Options for the svg:line's in each swimlane line_options: undefined _draw: (origin)=> super # Gather sampled pixels to bind to SVG linex current_data = [] pixels = [] @_sample (x,y,datum)-> current_data.push datum pixels.push { x:x, y:y } # Bind data in _draw without a key because it is based on pixel sampling @lines = c3.select(@g,'line').options(@line_options).bind(current_data).update() @lines.position x1: (d,i)-> pixels[i].x + 0.5 # Center line on pixels to avoid anti-aliasing x2: (d,i)-> pixels[i].x + 0.5 y1: if not @y? then 0 else (d,i)-> pixels[i].y - 0.5 y2: if not @y? then @height else (d,i)=> pixels[i].y + @dy - 0.5 _style: => super @lines.style() # A {c3.Plot.Layer.Swimlane.Sampled sampled swimlane layer} implemented via HTML5 Canvas # This layer supports `line_options.styles.stroke` and HTML `hover` "tooltips". class c3.Plot.Layer.Swimlane.Sampled.Canvas extends c3.Plot.Layer.Swimlane.Sampled @version: 0.0 type: 'canvas' # [{c3.Selection.Options}] Options for the svg:line's in each swimlane line_options: undefined _init: => super foreignObject = c3.select(@g,'foreignObject').singleton().position({height:'100%',width:'100%'}) @canvas = foreignObject.select('xhtml|canvas').singleton() #@canvas = document.createElement('canvas') #@image = c3.select(@g,'svg|image').singleton() _size: => super @canvas.position height: @height width: @width __draw: => context = @canvas.node().getContext('2d') context.clearRect 0,0, @width,@height # Translate by 0.5 so lines are centered on pixels to avoid anti-aliasing which causes transparency context.translate 0.5, 0.5 # Sample pixels to render onto canvas stroke = c3.functor @line_options?.styles?.stroke @_sample (x,y,datum)=> context.beginPath() context.moveTo x, y context.lineTo x, y+@dy context.strokeStyle = stroke datum context.stroke() context.translate -0.5, -0.5 #@image.all.attr('href',@canvas.toDataURL('image/png')) #@image.all.node().setAttributeNS('http://www.w3.org/1999/xlink','xlink:href',@canvas.toDataURL('image/png')) _draw: (origin)=> super; @__draw(origin) _style: (style_new)=> super; if not style_new then @__draw('restyle') # For the sampled layer, draw and style are the same. By default zoom does both, so just do one. zoom: => @__draw('zoom') #################################################################### ## XY Plot Decimated Layer #################################################################### # ## A decimated layer may be created to assist certain layer types to manage large datasets. ## When using a decimated layer pass into the constructor an array of the data at different ## detail granularities as well as a layer object instance that will be used as a "prototype" to ## construct a different layer for each detail level of data. This layer will only show one ## of the levels at a time and will automatically transition between them as the user zooms in and out. ## ## _When using a decimated layer, the **data** option does not need to be set for the layer prototype._ ## @example Creating a decimated layer ## mychart = new c3.Plot.horiz_zoom { ## anchor: '#chart_div' ## h: d3.scale.linear().domain [0, 1] ## v: d3.scale.linear().domain [0, 100] ## x: (d)-> d.x ## layers: [ ## new c3.Layer.decimated mylevels, new c3.Layer.area { ## y: (d)-> d.y ## interpolate: 'basis' ## } ## ] ## } ## mychart.render() ## @todo Should this be implemented as a mix-in instead? ## @todo A built-in helper for users to construct decimated groups using CrossFilter ## @author PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI #class c3.Plot.Layer.Decimated extends c3.Plot.Layer # @version: 0.1 # type: 'decimated' # # # [Number] The maximum number of data elements to render at a given time when preparing sections for smooth panning. # renderport_elements: 8000 # # [Number] If a decimated element spans more than this number of pixels after zooming then switch to the next level of detail. # pixels_per_bucket_limit: 2 # # # @param levels [Array] An Array of detail levels. Each entry in the array should be an array of data elements. # # Each level should also add a **granulairty** property which specified how many X domain units are combined into a single element for this level of detail. # # @param proto_layer [c3.Plot.Layer] A layer instance to use as a prototype to make layers for each level of detail. # constructor: (@levels, @proto_layer)-> ## @type += ' '+@proto_layer.type # for level, i in @levels # level.index = i # level.renderport = [0,0] # # _init: => # for level, i in @levels # level.layer = new @proto_layer.constructor() # c3.util.defaults level.layer, @proto_layer # level.layer.data = level # level.layer.g = @g.append('g').attr('class', 'level _'+i+' layer') # level.layer.init @chart # # _size: => # for level in @levels # level.layer.size @width, @height # # _update: => # # Invalidate the non-visible levels # for level in @levels when level isnt @current_level # level.renderport = [0,0] # @current_level?.layer.update() # # _draw: => # if not @current_level? then @zoom() # else @current_level.layer.draw() # # zoom: => # # Find the optimal decimation level for this viewport # view_width = @chart.h.domain()[1] - @chart.h.domain()[0] # for level in @levels # visible_buckets = view_width / level.granularity # if visible_buckets*@pixels_per_bucket_limit > @width # new_level = level # break # if !new_level? then new_level = @levels[@levels.length-1] # # # Did we change decimation levels? # if @current_level != new_level # @current_level = new_level # @g.selectAll('g.level').style('display','none') # @g.select('g.level[class~=_'+@current_level.index+']').style('display',null) # # # Determine if current viewport is outside current renderport and we need to redraw # if @chart.h.domain()[0] < @current_level.renderport[0] or # @chart.h.domain()[1] > @current_level.renderport[1] # # # Limit number of elements to render, centered on the current viewport # center = (@chart.h.domain()[0]+@chart.h.domain()[1]) / 2 # bisector = d3.bisector (d)->d.key # center_element = bisector.left @current_level, center # element_domain = [] # element_domain[0] = center_element - @renderport_elements/2 - 1 # element_domain[1] = center_element + @renderport_elements/2 # if element_domain[0]<0 then element_domain[0] = 0 # if element_domain[1]>@current_level.length-1 then element_domain[1] = @current_level.length-1 # # @current_level.renderport = (@current_level[i].key for i in element_domain) # # # Swap data for the new renderport and redraw # @current_level.layer.data = @current_level[element_domain[0]..element_domain[1]] # @current_level.layer.redraw()
[ { "context": "isRootBlip = true\n doc.contributors = 'some_dudes'\n doc.isFoldedByDefault = false\n ", "end": 3602, "score": 0.9623859524726868, "start": 3592, "tag": "USERNAME", "value": "some_dudes" }, { "context": " isRootBlip: true\n con...
src/tests/server/ot/test_couch_converter.coffee
LaPingvino/rizzoma
88
testCase = require('nodeunit').testCase sinon = require('sinon') DocumentCouchOtConverter = require('../../../server/ot/couch_converter').DocumentCouchOtConverter WaveCouchOtConverter = require('../../../server/ot/couch_converter').WaveCouchOtConverter BlipCouchOtConverter = require('../../../server/ot/couch_converter').BlipCouchOtConverter OperationCouchOtConverter = require('../../../server/ot/couch_converter').OperationCouchOtConverter getTestDataToEntity = () -> doc = id: 'some_id' version: 'some_version' _rev: 'some_rev' timestamp: 'some_timestamp' type: 'some_type' expected = id: 'some_id' v: 'some_version' meta: _rev: 'some_rev' ts: 'some_timestamp' type: 'some_type' return [doc, expected] getTestDataToCouch = () -> entity = id: 'some_id' v: 'some_version' meta: _rev: 'some_rev' ts: 'some_timestamp' type: 'some_type' expected = id: 'some_id' version: 'some_version' _rev: 'some_rev' timestamp: 'some_timestamp' type: 'some_type' return [entity, expected] module.exports = TestDocumentCouchOtConverter: testCase setUp: (callback) -> callback() tearDown: (callback) -> callback() testFromCouchToOtEntity: (test) -> getEntityInstanceStub = sinon.stub(DocumentCouchOtConverter, '_getEntityInstance') getEntityInstanceStub.returns({meta: {}}) [doc, expected] = getTestDataToEntity() entity = DocumentCouchOtConverter.fromCouchToOtEntity(doc) test.deepEqual(entity, expected) getEntityInstanceStub.restore() test.done() testFromOtEntityToCouch: (test) -> [entity, expected] = getTestDataToCouch() doc = DocumentCouchOtConverter.fromOtEntityToCouch(entity) test.deepEqual(doc, expected) test.done() TestWaveCouchOtConverter: testCase setUp: (callback) -> callback() tearDown: (callback) -> callback() testFromCouchToOtEntity: (test) -> [doc, expected] = getTestDataToEntity() doc.participants = 'some_participants' doc.rootBlipId = 'some_blip' doc.sharedState = 'public' expected.snapshot = participants: 'some_participants' rootBlipId: 'some_blip' sharedState: 'public' entity = WaveCouchOtConverter.fromCouchToOtEntity(doc) test.deepEqual(entity, expected) test.done() testFromOtEntityToCouch: (test) -> [entity, expected] = getTestDataToCouch() entity.snapshot = participants: 'some_participants' rootBlipId: 'some_blip' sharedState: 'public' expected.participants = 'some_participants' expected.rootBlipId = 'some_blip' expected.sharedState = 'public' doc = WaveCouchOtConverter.fromOtEntityToCouch(entity) test.deepEqual(doc, expected) test.done() TestBlipCouchOtConverter: testCase setUp: (callback) -> callback() tearDown: (callback) -> callback() testFromCouchToOtEntity: (test) -> [doc, expected] = getTestDataToEntity() doc.content = 'content' doc.isRootBlip = true doc.contributors = 'some_dudes' doc.isFoldedByDefault = false doc.removed = true doc.waveId = 'some_wave_id' doc.readers = 'some_another_id' expected.snapshot = content: 'content' isRootBlip: true contributors: 'some_dudes' isFoldedByDefault: false removed: true expected.meta.waveId = 'some_wave_id' expected.meta.readers = 'some_another_id' entity = BlipCouchOtConverter.fromCouchToOtEntity(doc) test.deepEqual(entity, expected) test.done() testFromOtEntityToCouch: (test) -> [entity, expected] = getTestDataToCouch() entity.snapshot = content: 'content' isRootBlip: true contributors: 'some_dudes' isFoldedByDefault: false removed: true entity.meta.waveId = 'some_wave_id' entity.meta.readers = 'some_another_id' expected.content = 'content' expected.isRootBlip = true expected.contributors = 'some_dudes' expected.isFoldedByDefault = false expected.removed = true expected.waveId = 'some_wave_id' expected.readers = 'some_another_id' doc = BlipCouchOtConverter.fromOtEntityToCouch(entity) test.deepEqual(doc, expected) test.done() TestOperationCouchOtConverter: testCase setUp: (callback) -> callback() tearDown: (callback) -> callback() testFromCouchToOtEntity: (test) -> doc = docId: 'some_name' op: 'op' v: 'some_version' expected = docId: 'some_name' op: 'op' v: 'some_version' meta: type: 'operation' entity = OperationCouchOtConverter.fromCouchToOtEntity(doc) test.deepEqual(entity, expected) test.done() testFromOtEntityToCouch: (test) -> entity = docId: 'some_name' op: 'op' v: 'some_version' expected = type: 'operation' docId: 'some_name' op: 'op' v: 'some_version' doc = OperationCouchOtConverter.fromOtEntityToCouch(entity) test.done()
27228
testCase = require('nodeunit').testCase sinon = require('sinon') DocumentCouchOtConverter = require('../../../server/ot/couch_converter').DocumentCouchOtConverter WaveCouchOtConverter = require('../../../server/ot/couch_converter').WaveCouchOtConverter BlipCouchOtConverter = require('../../../server/ot/couch_converter').BlipCouchOtConverter OperationCouchOtConverter = require('../../../server/ot/couch_converter').OperationCouchOtConverter getTestDataToEntity = () -> doc = id: 'some_id' version: 'some_version' _rev: 'some_rev' timestamp: 'some_timestamp' type: 'some_type' expected = id: 'some_id' v: 'some_version' meta: _rev: 'some_rev' ts: 'some_timestamp' type: 'some_type' return [doc, expected] getTestDataToCouch = () -> entity = id: 'some_id' v: 'some_version' meta: _rev: 'some_rev' ts: 'some_timestamp' type: 'some_type' expected = id: 'some_id' version: 'some_version' _rev: 'some_rev' timestamp: 'some_timestamp' type: 'some_type' return [entity, expected] module.exports = TestDocumentCouchOtConverter: testCase setUp: (callback) -> callback() tearDown: (callback) -> callback() testFromCouchToOtEntity: (test) -> getEntityInstanceStub = sinon.stub(DocumentCouchOtConverter, '_getEntityInstance') getEntityInstanceStub.returns({meta: {}}) [doc, expected] = getTestDataToEntity() entity = DocumentCouchOtConverter.fromCouchToOtEntity(doc) test.deepEqual(entity, expected) getEntityInstanceStub.restore() test.done() testFromOtEntityToCouch: (test) -> [entity, expected] = getTestDataToCouch() doc = DocumentCouchOtConverter.fromOtEntityToCouch(entity) test.deepEqual(doc, expected) test.done() TestWaveCouchOtConverter: testCase setUp: (callback) -> callback() tearDown: (callback) -> callback() testFromCouchToOtEntity: (test) -> [doc, expected] = getTestDataToEntity() doc.participants = 'some_participants' doc.rootBlipId = 'some_blip' doc.sharedState = 'public' expected.snapshot = participants: 'some_participants' rootBlipId: 'some_blip' sharedState: 'public' entity = WaveCouchOtConverter.fromCouchToOtEntity(doc) test.deepEqual(entity, expected) test.done() testFromOtEntityToCouch: (test) -> [entity, expected] = getTestDataToCouch() entity.snapshot = participants: 'some_participants' rootBlipId: 'some_blip' sharedState: 'public' expected.participants = 'some_participants' expected.rootBlipId = 'some_blip' expected.sharedState = 'public' doc = WaveCouchOtConverter.fromOtEntityToCouch(entity) test.deepEqual(doc, expected) test.done() TestBlipCouchOtConverter: testCase setUp: (callback) -> callback() tearDown: (callback) -> callback() testFromCouchToOtEntity: (test) -> [doc, expected] = getTestDataToEntity() doc.content = 'content' doc.isRootBlip = true doc.contributors = 'some_dudes' doc.isFoldedByDefault = false doc.removed = true doc.waveId = 'some_wave_id' doc.readers = 'some_another_id' expected.snapshot = content: 'content' isRootBlip: true contributors: 'some_dudes' isFoldedByDefault: false removed: true expected.meta.waveId = 'some_wave_id' expected.meta.readers = 'some_another_id' entity = BlipCouchOtConverter.fromCouchToOtEntity(doc) test.deepEqual(entity, expected) test.done() testFromOtEntityToCouch: (test) -> [entity, expected] = getTestDataToCouch() entity.snapshot = content: 'content' isRootBlip: true contributors: 'some_dudes' isFoldedByDefault: false removed: true entity.meta.waveId = 'some_wave_id' entity.meta.readers = 'some_another_id' expected.content = 'content' expected.isRootBlip = true expected.contributors = 'some_dudes' expected.isFoldedByDefault = false expected.removed = true expected.waveId = 'some_wave_id' expected.readers = 'some_another_id' doc = BlipCouchOtConverter.fromOtEntityToCouch(entity) test.deepEqual(doc, expected) test.done() TestOperationCouchOtConverter: testCase setUp: (callback) -> callback() tearDown: (callback) -> callback() testFromCouchToOtEntity: (test) -> doc = docId: '<NAME>_<NAME>' op: 'op' v: 'some_version' expected = docId: '<NAME>' op: 'op' v: 'some_version' meta: type: 'operation' entity = OperationCouchOtConverter.fromCouchToOtEntity(doc) test.deepEqual(entity, expected) test.done() testFromOtEntityToCouch: (test) -> entity = docId: '<NAME>' op: 'op' v: 'some_version' expected = type: 'operation' docId: '<NAME>' op: 'op' v: 'some_version' doc = OperationCouchOtConverter.fromOtEntityToCouch(entity) test.done()
true
testCase = require('nodeunit').testCase sinon = require('sinon') DocumentCouchOtConverter = require('../../../server/ot/couch_converter').DocumentCouchOtConverter WaveCouchOtConverter = require('../../../server/ot/couch_converter').WaveCouchOtConverter BlipCouchOtConverter = require('../../../server/ot/couch_converter').BlipCouchOtConverter OperationCouchOtConverter = require('../../../server/ot/couch_converter').OperationCouchOtConverter getTestDataToEntity = () -> doc = id: 'some_id' version: 'some_version' _rev: 'some_rev' timestamp: 'some_timestamp' type: 'some_type' expected = id: 'some_id' v: 'some_version' meta: _rev: 'some_rev' ts: 'some_timestamp' type: 'some_type' return [doc, expected] getTestDataToCouch = () -> entity = id: 'some_id' v: 'some_version' meta: _rev: 'some_rev' ts: 'some_timestamp' type: 'some_type' expected = id: 'some_id' version: 'some_version' _rev: 'some_rev' timestamp: 'some_timestamp' type: 'some_type' return [entity, expected] module.exports = TestDocumentCouchOtConverter: testCase setUp: (callback) -> callback() tearDown: (callback) -> callback() testFromCouchToOtEntity: (test) -> getEntityInstanceStub = sinon.stub(DocumentCouchOtConverter, '_getEntityInstance') getEntityInstanceStub.returns({meta: {}}) [doc, expected] = getTestDataToEntity() entity = DocumentCouchOtConverter.fromCouchToOtEntity(doc) test.deepEqual(entity, expected) getEntityInstanceStub.restore() test.done() testFromOtEntityToCouch: (test) -> [entity, expected] = getTestDataToCouch() doc = DocumentCouchOtConverter.fromOtEntityToCouch(entity) test.deepEqual(doc, expected) test.done() TestWaveCouchOtConverter: testCase setUp: (callback) -> callback() tearDown: (callback) -> callback() testFromCouchToOtEntity: (test) -> [doc, expected] = getTestDataToEntity() doc.participants = 'some_participants' doc.rootBlipId = 'some_blip' doc.sharedState = 'public' expected.snapshot = participants: 'some_participants' rootBlipId: 'some_blip' sharedState: 'public' entity = WaveCouchOtConverter.fromCouchToOtEntity(doc) test.deepEqual(entity, expected) test.done() testFromOtEntityToCouch: (test) -> [entity, expected] = getTestDataToCouch() entity.snapshot = participants: 'some_participants' rootBlipId: 'some_blip' sharedState: 'public' expected.participants = 'some_participants' expected.rootBlipId = 'some_blip' expected.sharedState = 'public' doc = WaveCouchOtConverter.fromOtEntityToCouch(entity) test.deepEqual(doc, expected) test.done() TestBlipCouchOtConverter: testCase setUp: (callback) -> callback() tearDown: (callback) -> callback() testFromCouchToOtEntity: (test) -> [doc, expected] = getTestDataToEntity() doc.content = 'content' doc.isRootBlip = true doc.contributors = 'some_dudes' doc.isFoldedByDefault = false doc.removed = true doc.waveId = 'some_wave_id' doc.readers = 'some_another_id' expected.snapshot = content: 'content' isRootBlip: true contributors: 'some_dudes' isFoldedByDefault: false removed: true expected.meta.waveId = 'some_wave_id' expected.meta.readers = 'some_another_id' entity = BlipCouchOtConverter.fromCouchToOtEntity(doc) test.deepEqual(entity, expected) test.done() testFromOtEntityToCouch: (test) -> [entity, expected] = getTestDataToCouch() entity.snapshot = content: 'content' isRootBlip: true contributors: 'some_dudes' isFoldedByDefault: false removed: true entity.meta.waveId = 'some_wave_id' entity.meta.readers = 'some_another_id' expected.content = 'content' expected.isRootBlip = true expected.contributors = 'some_dudes' expected.isFoldedByDefault = false expected.removed = true expected.waveId = 'some_wave_id' expected.readers = 'some_another_id' doc = BlipCouchOtConverter.fromOtEntityToCouch(entity) test.deepEqual(doc, expected) test.done() TestOperationCouchOtConverter: testCase setUp: (callback) -> callback() tearDown: (callback) -> callback() testFromCouchToOtEntity: (test) -> doc = docId: 'PI:NAME:<NAME>END_PI_PI:NAME:<NAME>END_PI' op: 'op' v: 'some_version' expected = docId: 'PI:NAME:<NAME>END_PI' op: 'op' v: 'some_version' meta: type: 'operation' entity = OperationCouchOtConverter.fromCouchToOtEntity(doc) test.deepEqual(entity, expected) test.done() testFromOtEntityToCouch: (test) -> entity = docId: 'PI:NAME:<NAME>END_PI' op: 'op' v: 'some_version' expected = type: 'operation' docId: 'PI:NAME:<NAME>END_PI' op: 'op' v: 'some_version' doc = OperationCouchOtConverter.fromOtEntityToCouch(entity) test.done()
[ { "context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje", "end": 22, "score": 0.9791520237922668, "start": 16, "tag": "NAME", "value": "Konode" } ]
src/eventTypesDropdown.coffee
LogicalOutcomes/KoNote
1
# Copyright (c) Konode. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # View component for displaying event types in a dropdown load = (win) -> React = win.React R = React.DOM B = require('./utils/reactBootstrap').load(win, 'DropdownButton', 'MenuItem') {FaIcon} = require('./utils').load(win) EventTypesDropdown = ({eventTypes, selectedEventType, onSelect, canSelectNone, typeId}) -> noneIsSelected = typeId is '' title = if selectedEventType? selectedEventType.get('name') else if noneIsSelected "None" else "Select Type" # Discard inactive eventTypes eventTypes = eventTypes.filter (eventType) => eventType.get('status') is 'default' B.DropdownButton({ title id: 'eventTypesDropdown' }, (if selectedEventType or canSelectNone and not noneIsSelected B.MenuItem({ onClick: onSelect.bind null, '' }, "None " FaIcon('ban') ) ) (if selectedEventType or canSelectNone and not noneIsSelected B.MenuItem({divider: true}) ) (eventTypes.map (eventType) => B.MenuItem({ key: eventType.get('id') onClick: onSelect.bind null, eventType.get('id') # ? }, R.div({ style: borderRight: "5px solid #{eventType.get('colorKeyHex')}" }, eventType.get('name') ) ) ) ) return EventTypesDropdown module.exports = {load}
115564
# Copyright (c) <NAME>. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # View component for displaying event types in a dropdown load = (win) -> React = win.React R = React.DOM B = require('./utils/reactBootstrap').load(win, 'DropdownButton', 'MenuItem') {FaIcon} = require('./utils').load(win) EventTypesDropdown = ({eventTypes, selectedEventType, onSelect, canSelectNone, typeId}) -> noneIsSelected = typeId is '' title = if selectedEventType? selectedEventType.get('name') else if noneIsSelected "None" else "Select Type" # Discard inactive eventTypes eventTypes = eventTypes.filter (eventType) => eventType.get('status') is 'default' B.DropdownButton({ title id: 'eventTypesDropdown' }, (if selectedEventType or canSelectNone and not noneIsSelected B.MenuItem({ onClick: onSelect.bind null, '' }, "None " FaIcon('ban') ) ) (if selectedEventType or canSelectNone and not noneIsSelected B.MenuItem({divider: true}) ) (eventTypes.map (eventType) => B.MenuItem({ key: eventType.get('id') onClick: onSelect.bind null, eventType.get('id') # ? }, R.div({ style: borderRight: "5px solid #{eventType.get('colorKeyHex')}" }, eventType.get('name') ) ) ) ) return EventTypesDropdown module.exports = {load}
true
# Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # View component for displaying event types in a dropdown load = (win) -> React = win.React R = React.DOM B = require('./utils/reactBootstrap').load(win, 'DropdownButton', 'MenuItem') {FaIcon} = require('./utils').load(win) EventTypesDropdown = ({eventTypes, selectedEventType, onSelect, canSelectNone, typeId}) -> noneIsSelected = typeId is '' title = if selectedEventType? selectedEventType.get('name') else if noneIsSelected "None" else "Select Type" # Discard inactive eventTypes eventTypes = eventTypes.filter (eventType) => eventType.get('status') is 'default' B.DropdownButton({ title id: 'eventTypesDropdown' }, (if selectedEventType or canSelectNone and not noneIsSelected B.MenuItem({ onClick: onSelect.bind null, '' }, "None " FaIcon('ban') ) ) (if selectedEventType or canSelectNone and not noneIsSelected B.MenuItem({divider: true}) ) (eventTypes.map (eventType) => B.MenuItem({ key: eventType.get('id') onClick: onSelect.bind null, eventType.get('id') # ? }, R.div({ style: borderRight: "5px solid #{eventType.get('colorKeyHex')}" }, eventType.get('name') ) ) ) ) return EventTypesDropdown module.exports = {load}
[ { "context": "word, options)->\n @save {email:email, password:password}, options\n logout:(options)->\n @destroy()\n r", "end": 1075, "score": 0.9734715819358826, "start": 1067, "tag": "PASSWORD", "value": "password" } ]
test/server/node_modules/api-hero/node_modules/rikki-tikki-client/src/classes/login.coffee
vancarney/apihero-module-socket.io
0
#### $scope.Login # > Implements Login functionality class $scope.Login extends $scope.Object idAttribute:'token' defaults: email:String password:String constructor:-> Login.__super__.constructor.apply @, arguments # overrides default pluralized upper-case classname @className = "login" validate:(o)-> email = o.email || @attributes.email || null password = o.token || @attributes.password || null token = o.token || @attributes.token || null # tests for basic authentication if email? # invalidates if password IS NOT set return "password required" unless password? # invalidates if token IS set return "password required" if token? # tests for bearer token authentication if token? # invalidates if email IS set return "token based authentication does not use email address" if email? # invalidates if password IS set return "token based authentication does not use password" if password? login:(email, password, options)-> @save {email:email, password:password}, options logout:(options)-> @destroy() restore:(token, options)-> @fetch token:token, options isAuthenticated:-> @attributes[@idAttribute]?
196940
#### $scope.Login # > Implements Login functionality class $scope.Login extends $scope.Object idAttribute:'token' defaults: email:String password:String constructor:-> Login.__super__.constructor.apply @, arguments # overrides default pluralized upper-case classname @className = "login" validate:(o)-> email = o.email || @attributes.email || null password = o.token || @attributes.password || null token = o.token || @attributes.token || null # tests for basic authentication if email? # invalidates if password IS NOT set return "password required" unless password? # invalidates if token IS set return "password required" if token? # tests for bearer token authentication if token? # invalidates if email IS set return "token based authentication does not use email address" if email? # invalidates if password IS set return "token based authentication does not use password" if password? login:(email, password, options)-> @save {email:email, password:<PASSWORD>}, options logout:(options)-> @destroy() restore:(token, options)-> @fetch token:token, options isAuthenticated:-> @attributes[@idAttribute]?
true
#### $scope.Login # > Implements Login functionality class $scope.Login extends $scope.Object idAttribute:'token' defaults: email:String password:String constructor:-> Login.__super__.constructor.apply @, arguments # overrides default pluralized upper-case classname @className = "login" validate:(o)-> email = o.email || @attributes.email || null password = o.token || @attributes.password || null token = o.token || @attributes.token || null # tests for basic authentication if email? # invalidates if password IS NOT set return "password required" unless password? # invalidates if token IS set return "password required" if token? # tests for bearer token authentication if token? # invalidates if email IS set return "token based authentication does not use email address" if email? # invalidates if password IS set return "token based authentication does not use password" if password? login:(email, password, options)-> @save {email:email, password:PI:PASSWORD:<PASSWORD>END_PI}, options logout:(options)-> @destroy() restore:(token, options)-> @fetch token:token, options isAuthenticated:-> @attributes[@idAttribute]?
[ { "context": "ts =\n id: 'artists'\n name: 'Artists'\n type: 'collection:artist'\n ", "end": 2259, "score": 0.8805512189865112, "start": 2252, "tag": "NAME", "value": "Artists" } ]
cloudtunes-webapp/app/views/search/search_form_view.coffee
skymemoryGit/cloudtunes
529
{View, Model, Collection} = require 'mvc' {escapeRegExp} = require 'utils' template = require 'templates/search/search_suggest' pubsub = require 'pubsub' FocusContextView = require 'views/ui/focus_context_view' class SuggestedItem extends Model class SuggestedItems extends Collection model: SuggestedItem class SearchFormView extends View events: 'focus #q': 'activity' 'keyup #q': 'activity' #'blur #q': 'end' initialize: (options)-> super(options) @$q = @$('input') @suggest = new SuggestView el: @$ '.suggest' model: @model @suggest.hide() activity: => @$el.addClass('active') @updateSuggestions($.trim(@$q.val())) activity: _.debounce(@::.activity, 500) end: => @$el.removeClass('active') @suggest.hide() updateSuggestions: (query)=> if query @suggest.show() if query != @prevQuery @prevQuery = query @suggest.render(query) else @suggest.hide() class Query extends Model initialize: -> query = @get('value') @res = (new RegExp(escapeRegExp(re), 'i') \ for re in query.split(/\s+/g)) matches: (text)=> _.all @res, (re) -> re.test(text) getTagText: -> @get('value') filter: (coll)-> model for model in coll when @matches(model) class BaseSourceSuggestView extends View class CollectionSuggestView extends BaseSourceSuggestView className: 'suggest-collection' initialize: (options)-> super options @artistNames = @model.library.tracklist.getArtistList() @albums = @model.library.tracklist.getAlbumList() @tracks = @model.library.tracklist render: (query)-> mixes = _.map @model.library.playlists.models, (mix)-> _.pick(mix.attributes, 'name', 'id') playlists = id: 'playlists' name: 'Playlists' type: 'collection:playlist' items: for mix in @filterItems(query, 3, mixes, 'name') value: mix.id text: mix.name artists = id: 'artists' name: 'Artists' type: 'collection:artist' items: for artist in @filterItems(query, 3, @artistNames.getResult()) value: artist text: artist albums = id: 'albums' name: 'Albums' type: 'collection:album' items: for album in @filterItems(query, 3, @albums.getResult(), 'album') value: album.album text: album.album note: "by #{album.artist}" tracks = id: 'tracks' name: 'Tracks' type: 'collection:track' items: for track in @filterItems(query, 3, @tracks.getResult(), 'title') value: track.id text: track.get('title') note: "by #{track.get('artist')} from #{track.get('album')}" source = id: 'collection' name: 'Collection' showAllLabel: 'Show All Results…' sections: [] for section in [playlists, artists, albums, tracks] if section.items.length @collection.add(section.items) source.sections.push(section) if not source.sections.length @$el.hide() no else @$el.html(template(source)) @$el.show() yes filterItems: (query, limit, items, textField=null)-> q = new Query value: query count = 0 matched = [] for item in items text = if textField then item[textField] else item if q.matches text matched.push item if ++count is limit break matched class ExternalSuggestView extends BaseSourceSuggestView className: 'suggest-external' initialize: (options)-> @render = _.debounce(@render, 500) render: (query)=> $.get '/api/search/suggest', q: query, (data)=> source = id: 'external' name: 'Elsewhere' showAllLabel: 'Show All Results…' sections: [] if data.artists.length artistsSection = id: 'artists' type: 'external:artist' name: 'Artists' items: for artist in data.artists id: artist.id text: artist.artist note: artist.note @collection.add(artistsSection.items) source.sections.push(artistsSection) if data.tracks.length tracksSection = id: 'tracks' type: 'external:track' name: 'Tracks' items: for track in data.tracks id: track.id text: track.title note: "by #{track.artist}" @collection.add(tracksSection.items) source.sections.push(tracksSection) if not source.sections.length @$el.hide() no else @$el.html(template(source)) @$el.show() yes class SuggestView extends View events: 'click .item': 'handleItemClick' 'mouseover .item': 'handleItemHover' initialize: (options)-> super options @subview(new FocusContextView(delegate: @)) @collection = new SuggestedItems cv = @subview( 'collection', new CollectionSuggestView({@model, @collection}) ) ex = @subview( 'external', new ExternalSuggestView({@model, @collection}) ) @$el.append(cv.el) @$el.append(ex.el) render: (query)-> #@focus() query = $.trim query if query.length > 1 _.invoke(@subviews, 'render', query) else @hide() hide: => @$el.hide() show: -> @$el.show() selectItem: ($item)-> @$selectedItem?.removeClass('selected') if $item?.length $item.addClass('selected') @$selectedItem = $item selectPrevItem: -> if @$selectedItem $items = @$('.items') $toSelect = $($items.get($items.index(@$selectedItem) - 1)) if $toSelect.length @selectedItem($toSelect) selectNextItem: -> if not @$selectedItem @selectItem(@$('.item:first')) else $items = @$('.items') $toSelect = $($items.get($items.index(@$selectedItem) + 1)) if $toSelect.length @selectedItem($toSelect) handleItemHover: (e)-> @selectItem($(e.currentTarget)) handleItemClick: (e)=> $item = $(e.currentTarget) @navigateToItem( $item.data('type'), $item.data('item') ) navigateToItem: (type, item)=> Backbone.history.navigate '/', true switch type when 'collection:playlist' @model.library.playlists.selected( @model.library.playlists.get(item)) when 'collection:artist' pubsub.publish('select:artist', artist: item) when 'collection:album' pubsub.publish('select:album', item) when 'collection:track' track = @model.library.get(item) pubsub.publish('select:track', track) when 'external:artist' pubsub.router.navigate('/artist/' + item, yes) else throw 'Unknown item ' + type @hide() module.exports = SearchFormView
173967
{View, Model, Collection} = require 'mvc' {escapeRegExp} = require 'utils' template = require 'templates/search/search_suggest' pubsub = require 'pubsub' FocusContextView = require 'views/ui/focus_context_view' class SuggestedItem extends Model class SuggestedItems extends Collection model: SuggestedItem class SearchFormView extends View events: 'focus #q': 'activity' 'keyup #q': 'activity' #'blur #q': 'end' initialize: (options)-> super(options) @$q = @$('input') @suggest = new SuggestView el: @$ '.suggest' model: @model @suggest.hide() activity: => @$el.addClass('active') @updateSuggestions($.trim(@$q.val())) activity: _.debounce(@::.activity, 500) end: => @$el.removeClass('active') @suggest.hide() updateSuggestions: (query)=> if query @suggest.show() if query != @prevQuery @prevQuery = query @suggest.render(query) else @suggest.hide() class Query extends Model initialize: -> query = @get('value') @res = (new RegExp(escapeRegExp(re), 'i') \ for re in query.split(/\s+/g)) matches: (text)=> _.all @res, (re) -> re.test(text) getTagText: -> @get('value') filter: (coll)-> model for model in coll when @matches(model) class BaseSourceSuggestView extends View class CollectionSuggestView extends BaseSourceSuggestView className: 'suggest-collection' initialize: (options)-> super options @artistNames = @model.library.tracklist.getArtistList() @albums = @model.library.tracklist.getAlbumList() @tracks = @model.library.tracklist render: (query)-> mixes = _.map @model.library.playlists.models, (mix)-> _.pick(mix.attributes, 'name', 'id') playlists = id: 'playlists' name: 'Playlists' type: 'collection:playlist' items: for mix in @filterItems(query, 3, mixes, 'name') value: mix.id text: mix.name artists = id: 'artists' name: '<NAME>' type: 'collection:artist' items: for artist in @filterItems(query, 3, @artistNames.getResult()) value: artist text: artist albums = id: 'albums' name: 'Albums' type: 'collection:album' items: for album in @filterItems(query, 3, @albums.getResult(), 'album') value: album.album text: album.album note: "by #{album.artist}" tracks = id: 'tracks' name: 'Tracks' type: 'collection:track' items: for track in @filterItems(query, 3, @tracks.getResult(), 'title') value: track.id text: track.get('title') note: "by #{track.get('artist')} from #{track.get('album')}" source = id: 'collection' name: 'Collection' showAllLabel: 'Show All Results…' sections: [] for section in [playlists, artists, albums, tracks] if section.items.length @collection.add(section.items) source.sections.push(section) if not source.sections.length @$el.hide() no else @$el.html(template(source)) @$el.show() yes filterItems: (query, limit, items, textField=null)-> q = new Query value: query count = 0 matched = [] for item in items text = if textField then item[textField] else item if q.matches text matched.push item if ++count is limit break matched class ExternalSuggestView extends BaseSourceSuggestView className: 'suggest-external' initialize: (options)-> @render = _.debounce(@render, 500) render: (query)=> $.get '/api/search/suggest', q: query, (data)=> source = id: 'external' name: 'Elsewhere' showAllLabel: 'Show All Results…' sections: [] if data.artists.length artistsSection = id: 'artists' type: 'external:artist' name: 'Artists' items: for artist in data.artists id: artist.id text: artist.artist note: artist.note @collection.add(artistsSection.items) source.sections.push(artistsSection) if data.tracks.length tracksSection = id: 'tracks' type: 'external:track' name: 'Tracks' items: for track in data.tracks id: track.id text: track.title note: "by #{track.artist}" @collection.add(tracksSection.items) source.sections.push(tracksSection) if not source.sections.length @$el.hide() no else @$el.html(template(source)) @$el.show() yes class SuggestView extends View events: 'click .item': 'handleItemClick' 'mouseover .item': 'handleItemHover' initialize: (options)-> super options @subview(new FocusContextView(delegate: @)) @collection = new SuggestedItems cv = @subview( 'collection', new CollectionSuggestView({@model, @collection}) ) ex = @subview( 'external', new ExternalSuggestView({@model, @collection}) ) @$el.append(cv.el) @$el.append(ex.el) render: (query)-> #@focus() query = $.trim query if query.length > 1 _.invoke(@subviews, 'render', query) else @hide() hide: => @$el.hide() show: -> @$el.show() selectItem: ($item)-> @$selectedItem?.removeClass('selected') if $item?.length $item.addClass('selected') @$selectedItem = $item selectPrevItem: -> if @$selectedItem $items = @$('.items') $toSelect = $($items.get($items.index(@$selectedItem) - 1)) if $toSelect.length @selectedItem($toSelect) selectNextItem: -> if not @$selectedItem @selectItem(@$('.item:first')) else $items = @$('.items') $toSelect = $($items.get($items.index(@$selectedItem) + 1)) if $toSelect.length @selectedItem($toSelect) handleItemHover: (e)-> @selectItem($(e.currentTarget)) handleItemClick: (e)=> $item = $(e.currentTarget) @navigateToItem( $item.data('type'), $item.data('item') ) navigateToItem: (type, item)=> Backbone.history.navigate '/', true switch type when 'collection:playlist' @model.library.playlists.selected( @model.library.playlists.get(item)) when 'collection:artist' pubsub.publish('select:artist', artist: item) when 'collection:album' pubsub.publish('select:album', item) when 'collection:track' track = @model.library.get(item) pubsub.publish('select:track', track) when 'external:artist' pubsub.router.navigate('/artist/' + item, yes) else throw 'Unknown item ' + type @hide() module.exports = SearchFormView
true
{View, Model, Collection} = require 'mvc' {escapeRegExp} = require 'utils' template = require 'templates/search/search_suggest' pubsub = require 'pubsub' FocusContextView = require 'views/ui/focus_context_view' class SuggestedItem extends Model class SuggestedItems extends Collection model: SuggestedItem class SearchFormView extends View events: 'focus #q': 'activity' 'keyup #q': 'activity' #'blur #q': 'end' initialize: (options)-> super(options) @$q = @$('input') @suggest = new SuggestView el: @$ '.suggest' model: @model @suggest.hide() activity: => @$el.addClass('active') @updateSuggestions($.trim(@$q.val())) activity: _.debounce(@::.activity, 500) end: => @$el.removeClass('active') @suggest.hide() updateSuggestions: (query)=> if query @suggest.show() if query != @prevQuery @prevQuery = query @suggest.render(query) else @suggest.hide() class Query extends Model initialize: -> query = @get('value') @res = (new RegExp(escapeRegExp(re), 'i') \ for re in query.split(/\s+/g)) matches: (text)=> _.all @res, (re) -> re.test(text) getTagText: -> @get('value') filter: (coll)-> model for model in coll when @matches(model) class BaseSourceSuggestView extends View class CollectionSuggestView extends BaseSourceSuggestView className: 'suggest-collection' initialize: (options)-> super options @artistNames = @model.library.tracklist.getArtistList() @albums = @model.library.tracklist.getAlbumList() @tracks = @model.library.tracklist render: (query)-> mixes = _.map @model.library.playlists.models, (mix)-> _.pick(mix.attributes, 'name', 'id') playlists = id: 'playlists' name: 'Playlists' type: 'collection:playlist' items: for mix in @filterItems(query, 3, mixes, 'name') value: mix.id text: mix.name artists = id: 'artists' name: 'PI:NAME:<NAME>END_PI' type: 'collection:artist' items: for artist in @filterItems(query, 3, @artistNames.getResult()) value: artist text: artist albums = id: 'albums' name: 'Albums' type: 'collection:album' items: for album in @filterItems(query, 3, @albums.getResult(), 'album') value: album.album text: album.album note: "by #{album.artist}" tracks = id: 'tracks' name: 'Tracks' type: 'collection:track' items: for track in @filterItems(query, 3, @tracks.getResult(), 'title') value: track.id text: track.get('title') note: "by #{track.get('artist')} from #{track.get('album')}" source = id: 'collection' name: 'Collection' showAllLabel: 'Show All Results…' sections: [] for section in [playlists, artists, albums, tracks] if section.items.length @collection.add(section.items) source.sections.push(section) if not source.sections.length @$el.hide() no else @$el.html(template(source)) @$el.show() yes filterItems: (query, limit, items, textField=null)-> q = new Query value: query count = 0 matched = [] for item in items text = if textField then item[textField] else item if q.matches text matched.push item if ++count is limit break matched class ExternalSuggestView extends BaseSourceSuggestView className: 'suggest-external' initialize: (options)-> @render = _.debounce(@render, 500) render: (query)=> $.get '/api/search/suggest', q: query, (data)=> source = id: 'external' name: 'Elsewhere' showAllLabel: 'Show All Results…' sections: [] if data.artists.length artistsSection = id: 'artists' type: 'external:artist' name: 'Artists' items: for artist in data.artists id: artist.id text: artist.artist note: artist.note @collection.add(artistsSection.items) source.sections.push(artistsSection) if data.tracks.length tracksSection = id: 'tracks' type: 'external:track' name: 'Tracks' items: for track in data.tracks id: track.id text: track.title note: "by #{track.artist}" @collection.add(tracksSection.items) source.sections.push(tracksSection) if not source.sections.length @$el.hide() no else @$el.html(template(source)) @$el.show() yes class SuggestView extends View events: 'click .item': 'handleItemClick' 'mouseover .item': 'handleItemHover' initialize: (options)-> super options @subview(new FocusContextView(delegate: @)) @collection = new SuggestedItems cv = @subview( 'collection', new CollectionSuggestView({@model, @collection}) ) ex = @subview( 'external', new ExternalSuggestView({@model, @collection}) ) @$el.append(cv.el) @$el.append(ex.el) render: (query)-> #@focus() query = $.trim query if query.length > 1 _.invoke(@subviews, 'render', query) else @hide() hide: => @$el.hide() show: -> @$el.show() selectItem: ($item)-> @$selectedItem?.removeClass('selected') if $item?.length $item.addClass('selected') @$selectedItem = $item selectPrevItem: -> if @$selectedItem $items = @$('.items') $toSelect = $($items.get($items.index(@$selectedItem) - 1)) if $toSelect.length @selectedItem($toSelect) selectNextItem: -> if not @$selectedItem @selectItem(@$('.item:first')) else $items = @$('.items') $toSelect = $($items.get($items.index(@$selectedItem) + 1)) if $toSelect.length @selectedItem($toSelect) handleItemHover: (e)-> @selectItem($(e.currentTarget)) handleItemClick: (e)=> $item = $(e.currentTarget) @navigateToItem( $item.data('type'), $item.data('item') ) navigateToItem: (type, item)=> Backbone.history.navigate '/', true switch type when 'collection:playlist' @model.library.playlists.selected( @model.library.playlists.get(item)) when 'collection:artist' pubsub.publish('select:artist', artist: item) when 'collection:album' pubsub.publish('select:album', item) when 'collection:track' track = @model.library.get(item) pubsub.publish('select:track', track) when 'external:artist' pubsub.router.navigate('/artist/' + item, yes) else throw 'Unknown item ' + type @hide() module.exports = SearchFormView
[ { "context": " <search> - Display Campus Experts\n#\n# Author:\n# Gustavo Cevallos - WGCV\n\n\n# It would be great to connect to api ", "end": 289, "score": 0.9998417496681213, "start": 273, "tag": "NAME", "value": "Gustavo Cevallos" } ]
src/GitHubCampusExpert.coffee
wgcv/Hubot-CampusExpert
0
# Description: # Check the GitHub Campus Experts information # # # Dependencies: # None # # Configuration: # None # # Commands: # hubot list of campus experts - Display all the GitHub Campus Experts # hubot about <search> - Display Campus Experts # # Author: # Gustavo Cevallos - WGCV # It would be great to connect to api of GitHub Campus Experts campusExperts = require('./CampusExperts.json') searchCE = (v) -> aboutCES = [] v = v.toUpperCase() for i in campusExperts if i.name.toUpperCase().indexOf(v) > -1 or i.lastname.toUpperCase().indexOf(v) > -1 or i.username.toUpperCase().indexOf(v) > -1 or i.university.toUpperCase().indexOf(v) >-1 or i.address.toUpperCase().indexOf(v) > -1 aboutCES.push(i) if aboutCES.length > 0 return aboutCES else return false module.exports = (robot) -> robot.respond /about (.*)/i, (res) -> search = res.match[1] aboutCES = searchCE(search) replay = '' if aboutCES for i in aboutCES replay += '\nName: ' + i.name + ' ' + i.lastname replay += '\nUsername: ' + i.username replay += '\nUniversity: ' + i.university replay += '\nAddress: ' + i.address + ' (https://www.google.com/maps/?q=' + i.coordinates[1] + ',' + i.coordinates[0] + ')' replay += '\nMail: ' + i.email replay += '\nAbout: ' + i.description replay += '\n ---------- \n' res.reply replay else res.reply "Theres is not a Campus Expert with " + search robot.respond /list of campus experts/i, (res) -> list = "" for i in campusExperts list += '\nName: ' + i.name + ' ' + i.lastname list += '\nUsername: ' + i.username list += '\nUniversity: ' + i.university list += '\nAddress: ' + i.address + ' (https://www.google.com/maps/?q=' + i.coordinates[1] + ',' + i.coordinates[0] + ')' list += '\nMail: ' + i.email list += '\nAbout: ' + i.description list += '\n ---------- \n' res.reply "This is all the Campus Experts: #{list}"
63302
# Description: # Check the GitHub Campus Experts information # # # Dependencies: # None # # Configuration: # None # # Commands: # hubot list of campus experts - Display all the GitHub Campus Experts # hubot about <search> - Display Campus Experts # # Author: # <NAME> - WGCV # It would be great to connect to api of GitHub Campus Experts campusExperts = require('./CampusExperts.json') searchCE = (v) -> aboutCES = [] v = v.toUpperCase() for i in campusExperts if i.name.toUpperCase().indexOf(v) > -1 or i.lastname.toUpperCase().indexOf(v) > -1 or i.username.toUpperCase().indexOf(v) > -1 or i.university.toUpperCase().indexOf(v) >-1 or i.address.toUpperCase().indexOf(v) > -1 aboutCES.push(i) if aboutCES.length > 0 return aboutCES else return false module.exports = (robot) -> robot.respond /about (.*)/i, (res) -> search = res.match[1] aboutCES = searchCE(search) replay = '' if aboutCES for i in aboutCES replay += '\nName: ' + i.name + ' ' + i.lastname replay += '\nUsername: ' + i.username replay += '\nUniversity: ' + i.university replay += '\nAddress: ' + i.address + ' (https://www.google.com/maps/?q=' + i.coordinates[1] + ',' + i.coordinates[0] + ')' replay += '\nMail: ' + i.email replay += '\nAbout: ' + i.description replay += '\n ---------- \n' res.reply replay else res.reply "Theres is not a Campus Expert with " + search robot.respond /list of campus experts/i, (res) -> list = "" for i in campusExperts list += '\nName: ' + i.name + ' ' + i.lastname list += '\nUsername: ' + i.username list += '\nUniversity: ' + i.university list += '\nAddress: ' + i.address + ' (https://www.google.com/maps/?q=' + i.coordinates[1] + ',' + i.coordinates[0] + ')' list += '\nMail: ' + i.email list += '\nAbout: ' + i.description list += '\n ---------- \n' res.reply "This is all the Campus Experts: #{list}"
true
# Description: # Check the GitHub Campus Experts information # # # Dependencies: # None # # Configuration: # None # # Commands: # hubot list of campus experts - Display all the GitHub Campus Experts # hubot about <search> - Display Campus Experts # # Author: # PI:NAME:<NAME>END_PI - WGCV # It would be great to connect to api of GitHub Campus Experts campusExperts = require('./CampusExperts.json') searchCE = (v) -> aboutCES = [] v = v.toUpperCase() for i in campusExperts if i.name.toUpperCase().indexOf(v) > -1 or i.lastname.toUpperCase().indexOf(v) > -1 or i.username.toUpperCase().indexOf(v) > -1 or i.university.toUpperCase().indexOf(v) >-1 or i.address.toUpperCase().indexOf(v) > -1 aboutCES.push(i) if aboutCES.length > 0 return aboutCES else return false module.exports = (robot) -> robot.respond /about (.*)/i, (res) -> search = res.match[1] aboutCES = searchCE(search) replay = '' if aboutCES for i in aboutCES replay += '\nName: ' + i.name + ' ' + i.lastname replay += '\nUsername: ' + i.username replay += '\nUniversity: ' + i.university replay += '\nAddress: ' + i.address + ' (https://www.google.com/maps/?q=' + i.coordinates[1] + ',' + i.coordinates[0] + ')' replay += '\nMail: ' + i.email replay += '\nAbout: ' + i.description replay += '\n ---------- \n' res.reply replay else res.reply "Theres is not a Campus Expert with " + search robot.respond /list of campus experts/i, (res) -> list = "" for i in campusExperts list += '\nName: ' + i.name + ' ' + i.lastname list += '\nUsername: ' + i.username list += '\nUniversity: ' + i.university list += '\nAddress: ' + i.address + ' (https://www.google.com/maps/?q=' + i.coordinates[1] + ',' + i.coordinates[0] + ')' list += '\nMail: ' + i.email list += '\nAbout: ' + i.description list += '\n ---------- \n' res.reply "This is all the Campus Experts: #{list}"
[ { "context": "# color-tunes.coffee, Copyright 2012 Shao-Chung Chen.\n# Licensed under the MIT license (http://www.ope", "end": 52, "score": 0.999794065952301, "start": 37, "tag": "NAME", "value": "Shao-Chung Chen" } ]
color-tunes.coffee
mikestecker/ColorTunes
92
# color-tunes.coffee, Copyright 2012 Shao-Chung Chen. # Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) class ColorTunes @getColorMap: (canvas, sx, sy, w, h, nc=8) -> pdata = canvas.getContext("2d").getImageData(sx, sy, w, h).data pixels = [] for y in [sy...(sy + h)] by 1 indexBase = (y * w * 4) for x in [sx...(sx + w)] by 1 index = (indexBase + (x * 4)) pixels.push [pdata[index], pdata[index+1], pdata[index+2]] # [r, g, b] (new MMCQ).quantize pixels, nc @colorDist: (a, b) -> square = (n) -> (n * n) (square(a[0] - b[0]) + square(a[1] - b[1]) + square(a[2] - b[2])) @fadeout: (canvas, width, height, opa=0.5, color=[0, 0, 0]) -> idata = canvas.getContext("2d").getImageData 0, 0, width, height pdata = idata.data for y in [0...height] for x in [0...width] idx = (y * width + x) * 4 pdata[idx+0] = opa * pdata[idx+0] + (1 - opa) * color[0] pdata[idx+1] = opa * pdata[idx+1] + (1 - opa) * color[1] pdata[idx+2] = opa * pdata[idx+2] + (1 - opa) * color[2] canvas.getContext("2d").putImageData idata, 0, 0 @feathering: (canvas, width, height, size=50, color=[0, 0, 0]) -> idata = canvas.getContext("2d").getImageData 0, 0, width, height pdata = idata.data conv = (x, y, p) -> p = 0 if p < 0 p = 1 if p > 1 idx = (y * width + x) * 4 pdata[idx+0] = p * pdata[idx+0] + (1 - p) * color[0] pdata[idx+1] = p * pdata[idx+1] + (1 - p) * color[1] pdata[idx+2] = p * pdata[idx+2] + (1 - p) * color[2] dist = (xa, ya, xb, yb) -> Math.sqrt((xb-xa)*(xb-xa) + (yb-ya)*(yb-ya)) for x in [0...width] by 1 for y in [0...size] by 1 p = y / size p = 1 - dist(x, y, size, size) / size if x < size conv x, y, p for y in [(0 + size)...height] by 1 for x in [0...size] by 1 p = x / size conv x, y, p canvas.getContext("2d").putImageData idata, 0, 0 @mirror: (canvas, sy, height, color=[0, 0, 0]) -> width = canvas.width idata = canvas.getContext("2d").getImageData 0, (sy - height), width, (height * 2) pdata = idata.data for y in [height...(height * 2)] by 1 for x in [0...width] by 1 idx = (y * width + x) * 4 idxu = ((height * 2 - y) * width + x) * 4 p = (y - height) / height + 0.33 p = 1 if p > 1 pdata[idx+0] = (1 - p) * pdata[idxu+0] + p * color[0] pdata[idx+1] = (1 - p) * pdata[idxu+1] + p * color[1] pdata[idx+2] = (1 - p) * pdata[idxu+2] + p * color[2] pdata[idx+3] = 255 canvas.getContext("2d").putImageData idata, 0, (sy - height) @launch: (image, canvas) -> $(image).on "load", -> image.height = Math.round (image.height * (300 / image.width)) image.width = 300 canvas.width = image.width canvas.height = image.height + 150 canvas.getContext("2d").drawImage image, 0, 0, image.width, image.height bgColorMap = ColorTunes.getColorMap canvas, 0, 0, (image.width * 0.5), (image.height), 4 bgPalette = bgColorMap.cboxes.map (cbox) -> { count: cbox.cbox.count(), rgb: cbox.color } bgPalette.sort (a, b) -> (b.count - a.count) bgColor = bgPalette[0].rgb fgColorMap = ColorTunes.getColorMap canvas, 0, 0, image.width, image.height, 10 fgPalette = fgColorMap.cboxes.map (cbox) -> { count: cbox.cbox.count(), rgb: cbox.color } fgPalette.sort (a, b) -> (b.count - a. count) maxDist = 0 for color in fgPalette dist = ColorTunes.colorDist bgColor, color.rgb if dist > maxDist maxDist = dist fgColor = color.rgb maxDist = 0 for color in fgPalette dist = ColorTunes.colorDist bgColor, color.rgb if dist > maxDist and color.rgb != fgColor maxDist = dist fgColor2 = color.rgb ColorTunes.fadeout canvas, image.width, image.height, 0.5, bgColor ColorTunes.feathering canvas, image.width, image.height, 60, bgColor ColorTunes.mirror canvas, (image.height - 1), 150, bgColor rgbToCssString = (color) -> "rgb(#{color[0]}, #{color[1]}, #{color[2]})" $(".playlist").css "color", "#{rgbToCssString fgColor2}" $(".track-title").css "color", "#{rgbToCssString fgColor}" $(".playlist").css "background-color", "#{rgbToCssString bgColor}" $(".playlist-indicator").css "border-bottom-color", "#{rgbToCssString bgColor}"
497
# color-tunes.coffee, Copyright 2012 <NAME>. # Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) class ColorTunes @getColorMap: (canvas, sx, sy, w, h, nc=8) -> pdata = canvas.getContext("2d").getImageData(sx, sy, w, h).data pixels = [] for y in [sy...(sy + h)] by 1 indexBase = (y * w * 4) for x in [sx...(sx + w)] by 1 index = (indexBase + (x * 4)) pixels.push [pdata[index], pdata[index+1], pdata[index+2]] # [r, g, b] (new MMCQ).quantize pixels, nc @colorDist: (a, b) -> square = (n) -> (n * n) (square(a[0] - b[0]) + square(a[1] - b[1]) + square(a[2] - b[2])) @fadeout: (canvas, width, height, opa=0.5, color=[0, 0, 0]) -> idata = canvas.getContext("2d").getImageData 0, 0, width, height pdata = idata.data for y in [0...height] for x in [0...width] idx = (y * width + x) * 4 pdata[idx+0] = opa * pdata[idx+0] + (1 - opa) * color[0] pdata[idx+1] = opa * pdata[idx+1] + (1 - opa) * color[1] pdata[idx+2] = opa * pdata[idx+2] + (1 - opa) * color[2] canvas.getContext("2d").putImageData idata, 0, 0 @feathering: (canvas, width, height, size=50, color=[0, 0, 0]) -> idata = canvas.getContext("2d").getImageData 0, 0, width, height pdata = idata.data conv = (x, y, p) -> p = 0 if p < 0 p = 1 if p > 1 idx = (y * width + x) * 4 pdata[idx+0] = p * pdata[idx+0] + (1 - p) * color[0] pdata[idx+1] = p * pdata[idx+1] + (1 - p) * color[1] pdata[idx+2] = p * pdata[idx+2] + (1 - p) * color[2] dist = (xa, ya, xb, yb) -> Math.sqrt((xb-xa)*(xb-xa) + (yb-ya)*(yb-ya)) for x in [0...width] by 1 for y in [0...size] by 1 p = y / size p = 1 - dist(x, y, size, size) / size if x < size conv x, y, p for y in [(0 + size)...height] by 1 for x in [0...size] by 1 p = x / size conv x, y, p canvas.getContext("2d").putImageData idata, 0, 0 @mirror: (canvas, sy, height, color=[0, 0, 0]) -> width = canvas.width idata = canvas.getContext("2d").getImageData 0, (sy - height), width, (height * 2) pdata = idata.data for y in [height...(height * 2)] by 1 for x in [0...width] by 1 idx = (y * width + x) * 4 idxu = ((height * 2 - y) * width + x) * 4 p = (y - height) / height + 0.33 p = 1 if p > 1 pdata[idx+0] = (1 - p) * pdata[idxu+0] + p * color[0] pdata[idx+1] = (1 - p) * pdata[idxu+1] + p * color[1] pdata[idx+2] = (1 - p) * pdata[idxu+2] + p * color[2] pdata[idx+3] = 255 canvas.getContext("2d").putImageData idata, 0, (sy - height) @launch: (image, canvas) -> $(image).on "load", -> image.height = Math.round (image.height * (300 / image.width)) image.width = 300 canvas.width = image.width canvas.height = image.height + 150 canvas.getContext("2d").drawImage image, 0, 0, image.width, image.height bgColorMap = ColorTunes.getColorMap canvas, 0, 0, (image.width * 0.5), (image.height), 4 bgPalette = bgColorMap.cboxes.map (cbox) -> { count: cbox.cbox.count(), rgb: cbox.color } bgPalette.sort (a, b) -> (b.count - a.count) bgColor = bgPalette[0].rgb fgColorMap = ColorTunes.getColorMap canvas, 0, 0, image.width, image.height, 10 fgPalette = fgColorMap.cboxes.map (cbox) -> { count: cbox.cbox.count(), rgb: cbox.color } fgPalette.sort (a, b) -> (b.count - a. count) maxDist = 0 for color in fgPalette dist = ColorTunes.colorDist bgColor, color.rgb if dist > maxDist maxDist = dist fgColor = color.rgb maxDist = 0 for color in fgPalette dist = ColorTunes.colorDist bgColor, color.rgb if dist > maxDist and color.rgb != fgColor maxDist = dist fgColor2 = color.rgb ColorTunes.fadeout canvas, image.width, image.height, 0.5, bgColor ColorTunes.feathering canvas, image.width, image.height, 60, bgColor ColorTunes.mirror canvas, (image.height - 1), 150, bgColor rgbToCssString = (color) -> "rgb(#{color[0]}, #{color[1]}, #{color[2]})" $(".playlist").css "color", "#{rgbToCssString fgColor2}" $(".track-title").css "color", "#{rgbToCssString fgColor}" $(".playlist").css "background-color", "#{rgbToCssString bgColor}" $(".playlist-indicator").css "border-bottom-color", "#{rgbToCssString bgColor}"
true
# color-tunes.coffee, Copyright 2012 PI:NAME:<NAME>END_PI. # Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) class ColorTunes @getColorMap: (canvas, sx, sy, w, h, nc=8) -> pdata = canvas.getContext("2d").getImageData(sx, sy, w, h).data pixels = [] for y in [sy...(sy + h)] by 1 indexBase = (y * w * 4) for x in [sx...(sx + w)] by 1 index = (indexBase + (x * 4)) pixels.push [pdata[index], pdata[index+1], pdata[index+2]] # [r, g, b] (new MMCQ).quantize pixels, nc @colorDist: (a, b) -> square = (n) -> (n * n) (square(a[0] - b[0]) + square(a[1] - b[1]) + square(a[2] - b[2])) @fadeout: (canvas, width, height, opa=0.5, color=[0, 0, 0]) -> idata = canvas.getContext("2d").getImageData 0, 0, width, height pdata = idata.data for y in [0...height] for x in [0...width] idx = (y * width + x) * 4 pdata[idx+0] = opa * pdata[idx+0] + (1 - opa) * color[0] pdata[idx+1] = opa * pdata[idx+1] + (1 - opa) * color[1] pdata[idx+2] = opa * pdata[idx+2] + (1 - opa) * color[2] canvas.getContext("2d").putImageData idata, 0, 0 @feathering: (canvas, width, height, size=50, color=[0, 0, 0]) -> idata = canvas.getContext("2d").getImageData 0, 0, width, height pdata = idata.data conv = (x, y, p) -> p = 0 if p < 0 p = 1 if p > 1 idx = (y * width + x) * 4 pdata[idx+0] = p * pdata[idx+0] + (1 - p) * color[0] pdata[idx+1] = p * pdata[idx+1] + (1 - p) * color[1] pdata[idx+2] = p * pdata[idx+2] + (1 - p) * color[2] dist = (xa, ya, xb, yb) -> Math.sqrt((xb-xa)*(xb-xa) + (yb-ya)*(yb-ya)) for x in [0...width] by 1 for y in [0...size] by 1 p = y / size p = 1 - dist(x, y, size, size) / size if x < size conv x, y, p for y in [(0 + size)...height] by 1 for x in [0...size] by 1 p = x / size conv x, y, p canvas.getContext("2d").putImageData idata, 0, 0 @mirror: (canvas, sy, height, color=[0, 0, 0]) -> width = canvas.width idata = canvas.getContext("2d").getImageData 0, (sy - height), width, (height * 2) pdata = idata.data for y in [height...(height * 2)] by 1 for x in [0...width] by 1 idx = (y * width + x) * 4 idxu = ((height * 2 - y) * width + x) * 4 p = (y - height) / height + 0.33 p = 1 if p > 1 pdata[idx+0] = (1 - p) * pdata[idxu+0] + p * color[0] pdata[idx+1] = (1 - p) * pdata[idxu+1] + p * color[1] pdata[idx+2] = (1 - p) * pdata[idxu+2] + p * color[2] pdata[idx+3] = 255 canvas.getContext("2d").putImageData idata, 0, (sy - height) @launch: (image, canvas) -> $(image).on "load", -> image.height = Math.round (image.height * (300 / image.width)) image.width = 300 canvas.width = image.width canvas.height = image.height + 150 canvas.getContext("2d").drawImage image, 0, 0, image.width, image.height bgColorMap = ColorTunes.getColorMap canvas, 0, 0, (image.width * 0.5), (image.height), 4 bgPalette = bgColorMap.cboxes.map (cbox) -> { count: cbox.cbox.count(), rgb: cbox.color } bgPalette.sort (a, b) -> (b.count - a.count) bgColor = bgPalette[0].rgb fgColorMap = ColorTunes.getColorMap canvas, 0, 0, image.width, image.height, 10 fgPalette = fgColorMap.cboxes.map (cbox) -> { count: cbox.cbox.count(), rgb: cbox.color } fgPalette.sort (a, b) -> (b.count - a. count) maxDist = 0 for color in fgPalette dist = ColorTunes.colorDist bgColor, color.rgb if dist > maxDist maxDist = dist fgColor = color.rgb maxDist = 0 for color in fgPalette dist = ColorTunes.colorDist bgColor, color.rgb if dist > maxDist and color.rgb != fgColor maxDist = dist fgColor2 = color.rgb ColorTunes.fadeout canvas, image.width, image.height, 0.5, bgColor ColorTunes.feathering canvas, image.width, image.height, 60, bgColor ColorTunes.mirror canvas, (image.height - 1), 150, bgColor rgbToCssString = (color) -> "rgb(#{color[0]}, #{color[1]}, #{color[2]})" $(".playlist").css "color", "#{rgbToCssString fgColor2}" $(".track-title").css "color", "#{rgbToCssString fgColor}" $(".playlist").css "background-color", "#{rgbToCssString bgColor}" $(".playlist-indicator").css "border-bottom-color", "#{rgbToCssString bgColor}"
[ { "context": "se\n Oman:\n countryISO: 'OM'\n countryName: 'Oman'\n locationFormat: 'City'\n usesPostalCode", "end": 30497, "score": 0.5836635828018188, "start": 30496, "tag": "NAME", "value": "O" } ]
src/country-data.coffee
willpatera/country-data
1
countryData = Andorra: countryISO: 'AD' countryName: 'Andorra' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'United Arab Emirates': countryISO: 'AE' countryName: 'United Arab Emirates' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Abu Dhabi' inEU: false Afghanistan: countryISO: 'AF' countryName: 'Afghanistan' locationFormat: 'Suburb' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kabul' inEU: false Antigua: countryISO: 'AG' countryName: 'Antigua' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'St Johns' inEU: false Anguilla: countryISO: 'AI' countryName: 'Anguilla' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'The Valley' inEU: false Albania: countryISO: 'AL' countryName: 'Albania' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Tirana' inEU: false Armenia: countryISO: 'AM' countryName: 'Armenia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'Netherlands Antilles': countryISO: 'AN' countryName: 'Netherlands Antilles' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Willemstad' inEU: false Angola: countryISO: 'AO' countryName: 'Angola' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Luanda' inEU: false Argentina: countryISO: 'AR' countryName: 'Argentina' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'American Samoa': countryISO: 'AS' countryName: 'American Samoa' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Austria: countryISO: 'AT' countryName: 'Austria' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Australia: countryISO: 'AU' countryName: 'Australia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Aruba: countryISO: 'AW' countryName: 'Aruba' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Oranjestad' inEU: false Azerbaijan: countryISO: 'AZ' countryName: 'Azerbaijan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999, 9999' capitalCity: null inEU: false 'Bosnia and Herzegovina': countryISO: 'BA' countryName: 'Bosnia and Herzegovina' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Barbados: countryISO: 'BB' countryName: 'Barbados' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bridgetown' inEU: false Bangladesh: countryISO: 'BD' countryName: 'Bangladesh' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Belgium: countryISO: 'BE' countryName: 'Belgium' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true 'Burkina Faso': countryISO: 'BF' countryName: 'Burkina Faso' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Ouagadougou' inEU: false Bulgaria: countryISO: 'BG' countryName: 'Bulgaria' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Bahrain: countryISO: 'BH' countryName: 'Bahrain' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Manama' inEU: false Burundi: countryISO: 'BI' countryName: 'Burundi' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bujumbura' inEU: false Benin: countryISO: 'BJ' countryName: 'Benin' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Porto Novo' inEU: false Bermuda: countryISO: 'BM' countryName: 'Bermuda' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Hamilton' inEU: false Brunei: countryISO: 'BN' countryName: 'Brunei' locationFormat: 'City' usesPostalCode: true postalCodeFormat: 'AA9999' capitalCity: null inEU: false Bolivia: countryISO: 'BO' countryName: 'Bolivia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Sucre' inEU: false Brazil: countryISO: 'BR' countryName: 'Brazil' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999,99999-999' capitalCity: null inEU: false Bahamas: countryISO: 'BS' countryName: 'Bahamas' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Nassau' inEU: false Bhutan: countryISO: 'BT' countryName: 'Bhutan' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Thimphu' inEU: false Botswana: countryISO: 'BW' countryName: 'Botswana' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Gaborone' inEU: false Belarus: countryISO: 'BY' countryName: 'Belarus' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Belize: countryISO: 'BZ' countryName: 'Belize' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Belmopan' inEU: false Canada: countryISO: 'CA' countryName: 'Canada' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: 'A9A 9A9,A9A 9A' capitalCity: null inEU: false 'Congo, The Democratic Republic of': countryISO: 'CD' countryName: 'Congo, The Democratic Republic of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kinshasa' inEU: false 'Central African Republic': countryISO: 'CF' countryName: 'Central African Republic' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bangui' inEU: false Congo: countryISO: 'CG' countryName: 'Congo' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kinshasa' inEU: false Switzerland: countryISO: 'CH' countryName: 'Switzerland' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'Cote d\'Ivoire': countryISO: 'CI' countryName: 'Cote d\'Ivoire' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Yamoussoukro' inEU: false 'Cook Islands': countryISO: 'CK' countryName: 'Cook Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Avarua' inEU: false Chile: countryISO: 'CL' countryName: 'Chile' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Santiago' inEU: false Cameroon: countryISO: 'CM' countryName: 'Cameroon' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Yaoune' inEU: false 'China, People\'s Republic': countryISO: 'CN' countryName: 'China, People\'s Republic' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Colombia: countryISO: 'CO' countryName: 'Colombia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bogota' inEU: false 'Costa Rica': countryISO: 'CR' countryName: 'Costa Rica' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'San Jose' inEU: false Cuba: countryISO: 'CU' countryName: 'Cuba' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Cape Verde': countryISO: 'CV' countryName: 'Cape Verde' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Praia' inEU: false Cyprus: countryISO: 'CY' countryName: 'Cyprus' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true 'Czech Republic, The': countryISO: 'CZ' countryName: 'Czech Republic, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999 99' capitalCity: null inEU: true Germany: countryISO: 'DE' countryName: 'Germany' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Djibouti: countryISO: 'DJ' countryName: 'Djibouti' locationFormat: 'Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dijbouti' inEU: false Denmark: countryISO: 'DK' countryName: 'Denmark' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Dominica: countryISO: 'DM' countryName: 'Dominica' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Roseau' inEU: false 'Dominican Rep.': countryISO: 'DO' countryName: 'Dominican Rep.' locationFormat: '' usesPostalCode: false postalCodeFormat: null capitalCity: 'Santo Domingo' inEU: false Algeria: countryISO: 'DZ' countryName: 'Algeria' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Ecuador: countryISO: 'EC' countryName: 'Ecuador' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Quito' inEU: false Estonia: countryISO: 'EE' countryName: 'Estonia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Egypt: countryISO: 'EG' countryName: 'Egypt' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Cairo' inEU: false Eritrea: countryISO: 'ER' countryName: 'Eritrea' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Asmara' inEU: false Spain: countryISO: 'ES' countryName: 'Spain' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Ethiopia: countryISO: 'ET' countryName: 'Ethiopia' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Addis Ababa' inEU: false Finland: countryISO: 'FI' countryName: 'Finland' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Fiji: countryISO: 'FJ' countryName: 'Fiji' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Suva' inEU: false 'Falkland Islands': countryISO: 'FK' countryName: 'Falkland Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Stanley' inEU: false 'Micronesia, Federated States Of': countryISO: 'FM' countryName: 'Micronesia, Federated States Of' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Faroe Islands': countryISO: 'FO' countryName: 'Faroe Islands' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999' capitalCity: null inEU: false France: countryISO: 'FR' countryName: 'France' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Gabon: countryISO: 'GA' countryName: 'Gabon' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Libreville' inEU: false 'United Kingdom': countryISO: 'GB' countryName: 'United Kingdom' locationFormat: 'City' usesPostalCode: true postalCodeFormat: 'A9 9AA, A99 9AA, A9A 9AA, AA9 9AA, AA99 9AA, AA9A 9AA' capitalCity: null inEU: true Grenada: countryISO: 'GD' countryName: 'Grenada' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'St Georges' inEU: false Georgia: countryISO: 'GE' countryName: 'Georgia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'French Guyana': countryISO: 'GF' countryName: 'French Guyana' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Guernsey: countryISO: 'GG' countryName: 'Guernsey' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: 'AA9 9AA' capitalCity: null inEU: false Ghana: countryISO: 'GH' countryName: 'Ghana' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Accra' inEU: false Gibraltar: countryISO: 'GI' countryName: 'Gibraltar' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'GIBRALTAR' inEU: false Greenland: countryISO: 'GL' countryName: 'Greenland' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Gambia: countryISO: 'GM' countryName: 'Gambia' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Banjul' inEU: false 'Guinea Republic': countryISO: 'GN' countryName: 'Guinea Republic' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Conakry' inEU: false Guadeloupe: countryISO: 'GP' countryName: 'Guadeloupe' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Guinea-Equatorial': countryISO: 'GQ' countryName: 'Guinea-Equatorial' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Malabo' inEU: false Greece: countryISO: 'GR' countryName: 'Greece' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999 99' capitalCity: null inEU: true Guatemala: countryISO: 'GT' countryName: 'Guatemala' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Guatemala City' inEU: false Guam: countryISO: 'GU' countryName: 'Guam' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Guinea-Bissau': countryISO: 'GW' countryName: 'Guinea-Bissau' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bissau' inEU: false 'Guyana (British)': countryISO: 'GY' countryName: 'Guyana (British)' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Georgetown' inEU: false 'Hong Kong': countryISO: 'HK' countryName: 'Hong Kong' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Hong Kong' inEU: false Honduras: countryISO: 'HN' countryName: 'Honduras' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Tegucigalpa' inEU: false Croatia: countryISO: 'HR' countryName: 'Croatia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Haiti: countryISO: 'HT' countryName: 'Haiti' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Port-au-Prince' inEU: false Hungary: countryISO: 'HU' countryName: 'Hungary' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true 'Canary Islands, The': countryISO: 'IC' countryName: 'Canary Islands, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Indonesia: countryISO: 'ID' countryName: 'Indonesia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Ireland, Republic Of': countryISO: 'IE' countryName: 'Ireland, Republic Of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dublin' inEU: true Israel: countryISO: 'IL' countryName: 'Israel' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false India: countryISO: 'IN' countryName: 'India' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Iraq: countryISO: 'IQ' countryName: 'Iraq' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Baghdad' inEU: false 'Iran (Islamic Republic of)': countryISO: 'IR' countryName: 'Iran (Islamic Republic of)' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Tehran' inEU: false Iceland: countryISO: 'IS' countryName: 'Iceland' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999' capitalCity: null inEU: true Italy: countryISO: 'IT' countryName: 'Italy' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Jersey: countryISO: 'JE' countryName: 'Jersey' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: 'AA9 9AA' capitalCity: null inEU: false Jamaica: countryISO: 'JM' countryName: 'Jamaica' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kingston' inEU: false Jordan: countryISO: 'JO' countryName: 'Jordan' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Amman' inEU: false Japan: countryISO: 'JP' countryName: 'Japan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999-9999' capitalCity: null inEU: false Kenya: countryISO: 'KE' countryName: 'Kenya' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Nairobi' inEU: false Kyrgyzstan: countryISO: 'KG' countryName: 'Kyrgyzstan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Cambodia: countryISO: 'KH' countryName: 'Cambodia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Phnom Penh' inEU: false Kiribati: countryISO: 'KI' countryName: 'Kiribati' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'South Tarawa' inEU: false Comoros: countryISO: 'KM' countryName: 'Comoros' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Moroni' inEU: false 'St. Kitts': countryISO: 'KN' countryName: 'St. Kitts' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Basseterre' inEU: false 'Korea, The D.P.R of': countryISO: 'KP' countryName: 'Korea, The D.P.R of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Pyongyang' inEU: false 'Korea, Republic Of': countryISO: 'KR' countryName: 'Korea, Republic Of' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999-999' capitalCity: null inEU: false Kosovo: countryISO: 'KV' countryName: 'Kosovo' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Kuwait: countryISO: 'KW' countryName: 'Kuwait' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kuwait City' inEU: false 'Cayman Islands': countryISO: 'KY' countryName: 'Cayman Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'George Town' inEU: false Kazakhstan: countryISO: 'KZ' countryName: 'Kazakhstan' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false 'Lao People\'s Democratic Republic': countryISO: 'LA' countryName: 'Lao People\'s Democratic Republic' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Vientiane' inEU: false Lebanon: countryISO: 'LB' countryName: 'Lebanon' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Beirut' inEU: false 'St. Lucia': countryISO: 'LC' countryName: 'St. Lucia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Castries' inEU: false Liechtenstein: countryISO: 'LI' countryName: 'Liechtenstein' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true 'Sri Lanka': countryISO: 'LK' countryName: 'Sri Lanka' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Colombo' inEU: false Liberia: countryISO: 'LR' countryName: 'Liberia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Monrovia' inEU: false Lesotho: countryISO: 'LS' countryName: 'Lesotho' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Maseru' inEU: false Lithuania: countryISO: 'LT' countryName: 'Lithuania' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Luxembourg: countryISO: 'LU' countryName: 'Luxembourg' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Latvia: countryISO: 'LV' countryName: 'Latvia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Libya: countryISO: 'LY' countryName: 'Libya' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Tripoli' inEU: false Morocco: countryISO: 'MA' countryName: 'Morocco' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Monaco: countryISO: 'MC' countryName: 'Monaco' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Moldova, Republic Of': countryISO: 'MD' countryName: 'Moldova, Republic Of' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'Montenegro, Republic of': countryISO: 'ME' countryName: 'Montenegro, Republic of' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Madagascar: countryISO: 'MG' countryName: 'Madagascar' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999' capitalCity: null inEU: false 'Marshall Islands': countryISO: 'MH' countryName: 'Marshall Islands' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Macedonia, Rep. of (FYROM)': countryISO: 'MK' countryName: 'Macedonia, Rep. of (FYROM)' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Mali: countryISO: 'ML' countryName: 'Mali' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bamako' inEU: false Myanmar: countryISO: 'MM' countryName: 'Myanmar' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Yangon' inEU: false Mongolia: countryISO: 'MN' countryName: 'Mongolia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999, 99999' capitalCity: null inEU: false Macau: countryISO: 'MO' countryName: 'Macau' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Macau' inEU: false Saipan: countryISO: 'MP' countryName: 'Saipan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Martinique: countryISO: 'MQ' countryName: 'Martinique' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Mauritania: countryISO: 'MR' countryName: 'Mauritania' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Nouakchott' inEU: false Montserrat: countryISO: 'MS' countryName: 'Montserrat' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Plymouth' inEU: false Malta: countryISO: 'MT' countryName: 'Malta' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Valletta' inEU: true Mauritius: countryISO: 'MU' countryName: 'Mauritius' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Port Louis' inEU: false Maldives: countryISO: 'MV' countryName: 'Maldives' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999, 9999' capitalCity: null inEU: false Malawi: countryISO: 'MW' countryName: 'Malawi' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Lilongwe' inEU: false Mexico: countryISO: 'MX' countryName: 'Mexico' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Malaysia: countryISO: 'MY' countryName: 'Malaysia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Mozambique: countryISO: 'MZ' countryName: 'Mozambique' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Maputo' inEU: false Namibia: countryISO: 'NA' countryName: 'Namibia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Windhoek' inEU: false 'New Caledonia': countryISO: 'NC' countryName: 'New Caledonia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Niger: countryISO: 'NE' countryName: 'Niger' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Niamey' inEU: false Nigeria: countryISO: 'NG' countryName: 'Nigeria' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Abuja' inEU: false Nicaragua: countryISO: 'NI' countryName: 'Nicaragua' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Managua' inEU: false 'Netherlands, The': countryISO: 'NL' countryName: 'Netherlands, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Norway: countryISO: 'NO' countryName: 'Norway' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Nepal: countryISO: 'NP' countryName: 'Nepal' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kathmandu' inEU: false 'Nauru, Republic Of': countryISO: 'NR' countryName: 'Nauru, Republic Of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Yaren District' inEU: false Niue: countryISO: 'NU' countryName: 'Niue' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Alofi' inEU: false 'New Zealand': countryISO: 'NZ' countryName: 'New Zealand' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Oman: countryISO: 'OM' countryName: 'Oman' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Muscat' inEU: false Panama: countryISO: 'PA' countryName: 'Panama' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Panama City' inEU: false Peru: countryISO: 'PE' countryName: 'Peru' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Lima' inEU: false Tahiti: countryISO: 'PF' countryName: 'Tahiti' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Papeete' inEU: false 'Papua New Guinea': countryISO: 'PG' countryName: 'Papua New Guinea' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999' capitalCity: null inEU: false 'Philippines, The': countryISO: 'PH' countryName: 'Philippines, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Pakistan: countryISO: 'PK' countryName: 'Pakistan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Poland: countryISO: 'PL' countryName: 'Poland' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99-999' capitalCity: null inEU: true 'Puerto Rico': countryISO: 'PR' countryName: 'Puerto Rico' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Portugal: countryISO: 'PT' countryName: 'Portugal' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999, 9999-999' capitalCity: null inEU: true Palau: countryISO: 'PW' countryName: 'Palau' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Paraguay: countryISO: 'PY' countryName: 'Paraguay' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Asuncion' inEU: false Qatar: countryISO: 'QA' countryName: 'Qatar' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Doha' inEU: false 'Reunion, Island Of': countryISO: 'RE' countryName: 'Reunion, Island Of' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Romania: countryISO: 'RO' countryName: 'Romania' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: true 'Serbia, Republic of': countryISO: 'RS' countryName: 'Serbia, Republic of' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Russian Federation, The': countryISO: 'RU' countryName: 'Russian Federation, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Rwanda: countryISO: 'RW' countryName: 'Rwanda' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kigali' inEU: false 'Saudi Arabia': countryISO: 'SA' countryName: 'Saudi Arabia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Riyadh' inEU: false 'Solomon Islands': countryISO: 'SB' countryName: 'Solomon Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Honiara' inEU: false Seychelles: countryISO: 'SC' countryName: 'Seychelles' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Victoria' inEU: false Sudan: countryISO: 'SD' countryName: 'Sudan' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Khartoum' inEU: false Sweden: countryISO: 'SE' countryName: 'Sweden' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999 99' capitalCity: null inEU: true Singapore: countryISO: 'SG' countryName: 'Singapore' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false 'SAINT HELENA': countryISO: 'SH' countryName: 'SAINT HELENA' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: null inEU: false Slovenia: countryISO: 'SI' countryName: 'Slovenia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Slovakia: countryISO: 'SK' countryName: 'Slovakia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999 99' capitalCity: null inEU: true 'Sierra Leone': countryISO: 'SL' countryName: 'Sierra Leone' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Freetown' inEU: false 'San Marino': countryISO: 'SM' countryName: 'San Marino' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Senegal: countryISO: 'SN' countryName: 'Senegal' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dakar' inEU: false Somalia: countryISO: 'SO' countryName: 'Somalia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Mogadishu' inEU: false Suriname: countryISO: 'SR' countryName: 'Suriname' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Paramaribo' inEU: false 'South Sudan': countryISO: 'SS' countryName: 'South Sudan' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Juba' inEU: false 'Sao Tome and Principe': countryISO: 'ST' countryName: 'Sao Tome and Principe' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Sao Tome' inEU: false 'El Salvador': countryISO: 'SV' countryName: 'El Salvador' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'San Salvador' inEU: false Syria: countryISO: 'SY' countryName: 'Syria' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Damascus' inEU: false Swaziland: countryISO: 'SZ' countryName: 'Swaziland' locationFormat: 'City' usesPostalCode: true postalCodeFormat: 'A999' capitalCity: null inEU: false 'Turks and Caicos Islands': countryISO: 'TC' countryName: 'Turks and Caicos Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Cockburn Town' inEU: false Chad: countryISO: 'TD' countryName: 'Chad' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'N Djamena' inEU: false Togo: countryISO: 'TG' countryName: 'Togo' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Lome' inEU: false Thailand: countryISO: 'TH' countryName: 'Thailand' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Tajikistan: countryISO: 'TJ' countryName: 'Tajikistan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false 'East Timor': countryISO: 'TL' countryName: 'East Timor' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dili' inEU: false Tunisia: countryISO: 'TN' countryName: 'Tunisia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Tonga: countryISO: 'TO' countryName: 'Tonga' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Nuku alofa' inEU: false Turkey: countryISO: 'TR' countryName: 'Turkey' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Trinidad and Tobago': countryISO: 'TT' countryName: 'Trinidad and Tobago' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Port of Spain' inEU: false Tuvalu: countryISO: 'TV' countryName: 'Tuvalu' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Funafuti' inEU: false Taiwan: countryISO: 'TW' countryName: 'Taiwan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999, 99999' capitalCity: null inEU: false Tanzania: countryISO: 'TZ' countryName: 'Tanzania' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dodoma' inEU: false Ukraine: countryISO: 'UA' countryName: 'Ukraine' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Uganda: countryISO: 'UG' countryName: 'Uganda' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kampala' inEU: false 'United States Of America': countryISO: 'US' countryName: 'United States Of America' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999, 99999-9999' capitalCity: null inEU: false Uruguay: countryISO: 'UY' countryName: 'Uruguay' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Montevideo' inEU: false Uzbekistan: countryISO: 'UZ' countryName: 'Uzbekistan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false 'St. Vincent': countryISO: 'VC' countryName: 'St. Vincent' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kingstown' inEU: false Venezuela: countryISO: 'VE' countryName: 'Venezuela' locationFormat: 'Suburb' usesPostalCode: false postalCodeFormat: null capitalCity: 'Caracas' inEU: false 'Virgin Islands (British)': countryISO: 'VG' countryName: 'Virgin Islands (British)' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Road Town' inEU: false 'Virgin Islands (US)': countryISO: 'VI' countryName: 'Virgin Islands (US)' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Vietnam: countryISO: 'VN' countryName: 'Vietnam' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Hanoi' inEU: false Vanuatu: countryISO: 'VU' countryName: 'Vanuatu' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Port Vila' inEU: false Samoa: countryISO: 'WS' countryName: 'Samoa' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Apia' inEU: false Bonaire: countryISO: 'XB' countryName: 'Bonaire' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kralendijk' inEU: false Curacao: countryISO: 'XC' countryName: 'Curacao' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Willemstad' inEU: false 'St. Eustatius': countryISO: 'XE' countryName: 'St. Eustatius' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Oranjestad' inEU: false 'St. Maarten': countryISO: 'XM' countryName: 'St. Maarten' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Philipsburg' inEU: false Nevis: countryISO: 'XN' countryName: 'Nevis' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Basseterre' inEU: false 'Somaliland, Rep of (North Somalia)': countryISO: 'XS' countryName: 'Somaliland, Rep of (North Somalia)' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Hargeisa' inEU: false 'St. Barthelemy': countryISO: 'XY' countryName: 'St. Barthelemy' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Yemen, Republic of': countryISO: 'YE' countryName: 'Yemen, Republic of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Sana a' inEU: false Mayotte: countryISO: 'YT' countryName: 'Mayotte' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'South Africa': countryISO: 'ZA' countryName: 'South Africa' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Zambia: countryISO: 'ZM' countryName: 'Zambia' locationFormat: 'Suburb' usesPostalCode: false postalCodeFormat: null capitalCity: 'Lusaka' inEU: false Zimbabwe: countryISO: 'ZW' countryName: 'Zimbabwe' locationFormat: 'Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Harare' inEU: false
37674
countryData = Andorra: countryISO: 'AD' countryName: 'Andorra' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'United Arab Emirates': countryISO: 'AE' countryName: 'United Arab Emirates' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Abu Dhabi' inEU: false Afghanistan: countryISO: 'AF' countryName: 'Afghanistan' locationFormat: 'Suburb' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kabul' inEU: false Antigua: countryISO: 'AG' countryName: 'Antigua' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'St Johns' inEU: false Anguilla: countryISO: 'AI' countryName: 'Anguilla' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'The Valley' inEU: false Albania: countryISO: 'AL' countryName: 'Albania' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Tirana' inEU: false Armenia: countryISO: 'AM' countryName: 'Armenia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'Netherlands Antilles': countryISO: 'AN' countryName: 'Netherlands Antilles' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Willemstad' inEU: false Angola: countryISO: 'AO' countryName: 'Angola' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Luanda' inEU: false Argentina: countryISO: 'AR' countryName: 'Argentina' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'American Samoa': countryISO: 'AS' countryName: 'American Samoa' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Austria: countryISO: 'AT' countryName: 'Austria' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Australia: countryISO: 'AU' countryName: 'Australia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Aruba: countryISO: 'AW' countryName: 'Aruba' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Oranjestad' inEU: false Azerbaijan: countryISO: 'AZ' countryName: 'Azerbaijan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999, 9999' capitalCity: null inEU: false 'Bosnia and Herzegovina': countryISO: 'BA' countryName: 'Bosnia and Herzegovina' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Barbados: countryISO: 'BB' countryName: 'Barbados' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bridgetown' inEU: false Bangladesh: countryISO: 'BD' countryName: 'Bangladesh' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Belgium: countryISO: 'BE' countryName: 'Belgium' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true 'Burkina Faso': countryISO: 'BF' countryName: 'Burkina Faso' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Ouagadougou' inEU: false Bulgaria: countryISO: 'BG' countryName: 'Bulgaria' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Bahrain: countryISO: 'BH' countryName: 'Bahrain' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Manama' inEU: false Burundi: countryISO: 'BI' countryName: 'Burundi' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bujumbura' inEU: false Benin: countryISO: 'BJ' countryName: 'Benin' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Porto Novo' inEU: false Bermuda: countryISO: 'BM' countryName: 'Bermuda' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Hamilton' inEU: false Brunei: countryISO: 'BN' countryName: 'Brunei' locationFormat: 'City' usesPostalCode: true postalCodeFormat: 'AA9999' capitalCity: null inEU: false Bolivia: countryISO: 'BO' countryName: 'Bolivia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Sucre' inEU: false Brazil: countryISO: 'BR' countryName: 'Brazil' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999,99999-999' capitalCity: null inEU: false Bahamas: countryISO: 'BS' countryName: 'Bahamas' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Nassau' inEU: false Bhutan: countryISO: 'BT' countryName: 'Bhutan' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Thimphu' inEU: false Botswana: countryISO: 'BW' countryName: 'Botswana' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Gaborone' inEU: false Belarus: countryISO: 'BY' countryName: 'Belarus' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Belize: countryISO: 'BZ' countryName: 'Belize' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Belmopan' inEU: false Canada: countryISO: 'CA' countryName: 'Canada' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: 'A9A 9A9,A9A 9A' capitalCity: null inEU: false 'Congo, The Democratic Republic of': countryISO: 'CD' countryName: 'Congo, The Democratic Republic of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kinshasa' inEU: false 'Central African Republic': countryISO: 'CF' countryName: 'Central African Republic' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bangui' inEU: false Congo: countryISO: 'CG' countryName: 'Congo' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kinshasa' inEU: false Switzerland: countryISO: 'CH' countryName: 'Switzerland' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'Cote d\'Ivoire': countryISO: 'CI' countryName: 'Cote d\'Ivoire' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Yamoussoukro' inEU: false 'Cook Islands': countryISO: 'CK' countryName: 'Cook Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Avarua' inEU: false Chile: countryISO: 'CL' countryName: 'Chile' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Santiago' inEU: false Cameroon: countryISO: 'CM' countryName: 'Cameroon' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Yaoune' inEU: false 'China, People\'s Republic': countryISO: 'CN' countryName: 'China, People\'s Republic' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Colombia: countryISO: 'CO' countryName: 'Colombia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bogota' inEU: false 'Costa Rica': countryISO: 'CR' countryName: 'Costa Rica' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'San Jose' inEU: false Cuba: countryISO: 'CU' countryName: 'Cuba' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Cape Verde': countryISO: 'CV' countryName: 'Cape Verde' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Praia' inEU: false Cyprus: countryISO: 'CY' countryName: 'Cyprus' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true 'Czech Republic, The': countryISO: 'CZ' countryName: 'Czech Republic, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999 99' capitalCity: null inEU: true Germany: countryISO: 'DE' countryName: 'Germany' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Djibouti: countryISO: 'DJ' countryName: 'Djibouti' locationFormat: 'Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dijbouti' inEU: false Denmark: countryISO: 'DK' countryName: 'Denmark' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Dominica: countryISO: 'DM' countryName: 'Dominica' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Roseau' inEU: false 'Dominican Rep.': countryISO: 'DO' countryName: 'Dominican Rep.' locationFormat: '' usesPostalCode: false postalCodeFormat: null capitalCity: 'Santo Domingo' inEU: false Algeria: countryISO: 'DZ' countryName: 'Algeria' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Ecuador: countryISO: 'EC' countryName: 'Ecuador' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Quito' inEU: false Estonia: countryISO: 'EE' countryName: 'Estonia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Egypt: countryISO: 'EG' countryName: 'Egypt' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Cairo' inEU: false Eritrea: countryISO: 'ER' countryName: 'Eritrea' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Asmara' inEU: false Spain: countryISO: 'ES' countryName: 'Spain' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Ethiopia: countryISO: 'ET' countryName: 'Ethiopia' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Addis Ababa' inEU: false Finland: countryISO: 'FI' countryName: 'Finland' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Fiji: countryISO: 'FJ' countryName: 'Fiji' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Suva' inEU: false 'Falkland Islands': countryISO: 'FK' countryName: 'Falkland Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Stanley' inEU: false 'Micronesia, Federated States Of': countryISO: 'FM' countryName: 'Micronesia, Federated States Of' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Faroe Islands': countryISO: 'FO' countryName: 'Faroe Islands' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999' capitalCity: null inEU: false France: countryISO: 'FR' countryName: 'France' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Gabon: countryISO: 'GA' countryName: 'Gabon' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Libreville' inEU: false 'United Kingdom': countryISO: 'GB' countryName: 'United Kingdom' locationFormat: 'City' usesPostalCode: true postalCodeFormat: 'A9 9AA, A99 9AA, A9A 9AA, AA9 9AA, AA99 9AA, AA9A 9AA' capitalCity: null inEU: true Grenada: countryISO: 'GD' countryName: 'Grenada' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'St Georges' inEU: false Georgia: countryISO: 'GE' countryName: 'Georgia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'French Guyana': countryISO: 'GF' countryName: 'French Guyana' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Guernsey: countryISO: 'GG' countryName: 'Guernsey' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: 'AA9 9AA' capitalCity: null inEU: false Ghana: countryISO: 'GH' countryName: 'Ghana' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Accra' inEU: false Gibraltar: countryISO: 'GI' countryName: 'Gibraltar' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'GIBRALTAR' inEU: false Greenland: countryISO: 'GL' countryName: 'Greenland' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Gambia: countryISO: 'GM' countryName: 'Gambia' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Banjul' inEU: false 'Guinea Republic': countryISO: 'GN' countryName: 'Guinea Republic' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Conakry' inEU: false Guadeloupe: countryISO: 'GP' countryName: 'Guadeloupe' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Guinea-Equatorial': countryISO: 'GQ' countryName: 'Guinea-Equatorial' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Malabo' inEU: false Greece: countryISO: 'GR' countryName: 'Greece' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999 99' capitalCity: null inEU: true Guatemala: countryISO: 'GT' countryName: 'Guatemala' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Guatemala City' inEU: false Guam: countryISO: 'GU' countryName: 'Guam' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Guinea-Bissau': countryISO: 'GW' countryName: 'Guinea-Bissau' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bissau' inEU: false 'Guyana (British)': countryISO: 'GY' countryName: 'Guyana (British)' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Georgetown' inEU: false 'Hong Kong': countryISO: 'HK' countryName: 'Hong Kong' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Hong Kong' inEU: false Honduras: countryISO: 'HN' countryName: 'Honduras' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Tegucigalpa' inEU: false Croatia: countryISO: 'HR' countryName: 'Croatia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Haiti: countryISO: 'HT' countryName: 'Haiti' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Port-au-Prince' inEU: false Hungary: countryISO: 'HU' countryName: 'Hungary' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true 'Canary Islands, The': countryISO: 'IC' countryName: 'Canary Islands, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Indonesia: countryISO: 'ID' countryName: 'Indonesia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Ireland, Republic Of': countryISO: 'IE' countryName: 'Ireland, Republic Of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dublin' inEU: true Israel: countryISO: 'IL' countryName: 'Israel' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false India: countryISO: 'IN' countryName: 'India' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Iraq: countryISO: 'IQ' countryName: 'Iraq' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Baghdad' inEU: false 'Iran (Islamic Republic of)': countryISO: 'IR' countryName: 'Iran (Islamic Republic of)' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Tehran' inEU: false Iceland: countryISO: 'IS' countryName: 'Iceland' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999' capitalCity: null inEU: true Italy: countryISO: 'IT' countryName: 'Italy' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Jersey: countryISO: 'JE' countryName: 'Jersey' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: 'AA9 9AA' capitalCity: null inEU: false Jamaica: countryISO: 'JM' countryName: 'Jamaica' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kingston' inEU: false Jordan: countryISO: 'JO' countryName: 'Jordan' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Amman' inEU: false Japan: countryISO: 'JP' countryName: 'Japan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999-9999' capitalCity: null inEU: false Kenya: countryISO: 'KE' countryName: 'Kenya' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Nairobi' inEU: false Kyrgyzstan: countryISO: 'KG' countryName: 'Kyrgyzstan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Cambodia: countryISO: 'KH' countryName: 'Cambodia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Phnom Penh' inEU: false Kiribati: countryISO: 'KI' countryName: 'Kiribati' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'South Tarawa' inEU: false Comoros: countryISO: 'KM' countryName: 'Comoros' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Moroni' inEU: false 'St. Kitts': countryISO: 'KN' countryName: 'St. Kitts' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Basseterre' inEU: false 'Korea, The D.P.R of': countryISO: 'KP' countryName: 'Korea, The D.P.R of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Pyongyang' inEU: false 'Korea, Republic Of': countryISO: 'KR' countryName: 'Korea, Republic Of' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999-999' capitalCity: null inEU: false Kosovo: countryISO: 'KV' countryName: 'Kosovo' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Kuwait: countryISO: 'KW' countryName: 'Kuwait' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kuwait City' inEU: false 'Cayman Islands': countryISO: 'KY' countryName: 'Cayman Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'George Town' inEU: false Kazakhstan: countryISO: 'KZ' countryName: 'Kazakhstan' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false 'Lao People\'s Democratic Republic': countryISO: 'LA' countryName: 'Lao People\'s Democratic Republic' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Vientiane' inEU: false Lebanon: countryISO: 'LB' countryName: 'Lebanon' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Beirut' inEU: false 'St. Lucia': countryISO: 'LC' countryName: 'St. Lucia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Castries' inEU: false Liechtenstein: countryISO: 'LI' countryName: 'Liechtenstein' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true 'Sri Lanka': countryISO: 'LK' countryName: 'Sri Lanka' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Colombo' inEU: false Liberia: countryISO: 'LR' countryName: 'Liberia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Monrovia' inEU: false Lesotho: countryISO: 'LS' countryName: 'Lesotho' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Maseru' inEU: false Lithuania: countryISO: 'LT' countryName: 'Lithuania' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Luxembourg: countryISO: 'LU' countryName: 'Luxembourg' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Latvia: countryISO: 'LV' countryName: 'Latvia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Libya: countryISO: 'LY' countryName: 'Libya' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Tripoli' inEU: false Morocco: countryISO: 'MA' countryName: 'Morocco' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Monaco: countryISO: 'MC' countryName: 'Monaco' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Moldova, Republic Of': countryISO: 'MD' countryName: 'Moldova, Republic Of' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'Montenegro, Republic of': countryISO: 'ME' countryName: 'Montenegro, Republic of' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Madagascar: countryISO: 'MG' countryName: 'Madagascar' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999' capitalCity: null inEU: false 'Marshall Islands': countryISO: 'MH' countryName: 'Marshall Islands' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Macedonia, Rep. of (FYROM)': countryISO: 'MK' countryName: 'Macedonia, Rep. of (FYROM)' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Mali: countryISO: 'ML' countryName: 'Mali' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bamako' inEU: false Myanmar: countryISO: 'MM' countryName: 'Myanmar' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Yangon' inEU: false Mongolia: countryISO: 'MN' countryName: 'Mongolia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999, 99999' capitalCity: null inEU: false Macau: countryISO: 'MO' countryName: 'Macau' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Macau' inEU: false Saipan: countryISO: 'MP' countryName: 'Saipan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Martinique: countryISO: 'MQ' countryName: 'Martinique' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Mauritania: countryISO: 'MR' countryName: 'Mauritania' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Nouakchott' inEU: false Montserrat: countryISO: 'MS' countryName: 'Montserrat' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Plymouth' inEU: false Malta: countryISO: 'MT' countryName: 'Malta' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Valletta' inEU: true Mauritius: countryISO: 'MU' countryName: 'Mauritius' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Port Louis' inEU: false Maldives: countryISO: 'MV' countryName: 'Maldives' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999, 9999' capitalCity: null inEU: false Malawi: countryISO: 'MW' countryName: 'Malawi' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Lilongwe' inEU: false Mexico: countryISO: 'MX' countryName: 'Mexico' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Malaysia: countryISO: 'MY' countryName: 'Malaysia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Mozambique: countryISO: 'MZ' countryName: 'Mozambique' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Maputo' inEU: false Namibia: countryISO: 'NA' countryName: 'Namibia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Windhoek' inEU: false 'New Caledonia': countryISO: 'NC' countryName: 'New Caledonia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Niger: countryISO: 'NE' countryName: 'Niger' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Niamey' inEU: false Nigeria: countryISO: 'NG' countryName: 'Nigeria' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Abuja' inEU: false Nicaragua: countryISO: 'NI' countryName: 'Nicaragua' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Managua' inEU: false 'Netherlands, The': countryISO: 'NL' countryName: 'Netherlands, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Norway: countryISO: 'NO' countryName: 'Norway' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Nepal: countryISO: 'NP' countryName: 'Nepal' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kathmandu' inEU: false 'Nauru, Republic Of': countryISO: 'NR' countryName: 'Nauru, Republic Of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Yaren District' inEU: false Niue: countryISO: 'NU' countryName: 'Niue' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Alofi' inEU: false 'New Zealand': countryISO: 'NZ' countryName: 'New Zealand' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Oman: countryISO: 'OM' countryName: '<NAME>man' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Muscat' inEU: false Panama: countryISO: 'PA' countryName: 'Panama' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Panama City' inEU: false Peru: countryISO: 'PE' countryName: 'Peru' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Lima' inEU: false Tahiti: countryISO: 'PF' countryName: 'Tahiti' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Papeete' inEU: false 'Papua New Guinea': countryISO: 'PG' countryName: 'Papua New Guinea' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999' capitalCity: null inEU: false 'Philippines, The': countryISO: 'PH' countryName: 'Philippines, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Pakistan: countryISO: 'PK' countryName: 'Pakistan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Poland: countryISO: 'PL' countryName: 'Poland' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99-999' capitalCity: null inEU: true 'Puerto Rico': countryISO: 'PR' countryName: 'Puerto Rico' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Portugal: countryISO: 'PT' countryName: 'Portugal' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999, 9999-999' capitalCity: null inEU: true Palau: countryISO: 'PW' countryName: 'Palau' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Paraguay: countryISO: 'PY' countryName: 'Paraguay' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Asuncion' inEU: false Qatar: countryISO: 'QA' countryName: 'Qatar' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Doha' inEU: false 'Reunion, Island Of': countryISO: 'RE' countryName: 'Reunion, Island Of' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Romania: countryISO: 'RO' countryName: 'Romania' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: true 'Serbia, Republic of': countryISO: 'RS' countryName: 'Serbia, Republic of' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Russian Federation, The': countryISO: 'RU' countryName: 'Russian Federation, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Rwanda: countryISO: 'RW' countryName: 'Rwanda' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kigali' inEU: false 'Saudi Arabia': countryISO: 'SA' countryName: 'Saudi Arabia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Riyadh' inEU: false 'Solomon Islands': countryISO: 'SB' countryName: 'Solomon Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Honiara' inEU: false Seychelles: countryISO: 'SC' countryName: 'Seychelles' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Victoria' inEU: false Sudan: countryISO: 'SD' countryName: 'Sudan' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Khartoum' inEU: false Sweden: countryISO: 'SE' countryName: 'Sweden' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999 99' capitalCity: null inEU: true Singapore: countryISO: 'SG' countryName: 'Singapore' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false 'SAINT HELENA': countryISO: 'SH' countryName: 'SAINT HELENA' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: null inEU: false Slovenia: countryISO: 'SI' countryName: 'Slovenia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Slovakia: countryISO: 'SK' countryName: 'Slovakia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999 99' capitalCity: null inEU: true 'Sierra Leone': countryISO: 'SL' countryName: 'Sierra Leone' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Freetown' inEU: false 'San Marino': countryISO: 'SM' countryName: 'San Marino' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Senegal: countryISO: 'SN' countryName: 'Senegal' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dakar' inEU: false Somalia: countryISO: 'SO' countryName: 'Somalia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Mogadishu' inEU: false Suriname: countryISO: 'SR' countryName: 'Suriname' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Paramaribo' inEU: false 'South Sudan': countryISO: 'SS' countryName: 'South Sudan' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Juba' inEU: false 'Sao Tome and Principe': countryISO: 'ST' countryName: 'Sao Tome and Principe' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Sao Tome' inEU: false 'El Salvador': countryISO: 'SV' countryName: 'El Salvador' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'San Salvador' inEU: false Syria: countryISO: 'SY' countryName: 'Syria' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Damascus' inEU: false Swaziland: countryISO: 'SZ' countryName: 'Swaziland' locationFormat: 'City' usesPostalCode: true postalCodeFormat: 'A999' capitalCity: null inEU: false 'Turks and Caicos Islands': countryISO: 'TC' countryName: 'Turks and Caicos Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Cockburn Town' inEU: false Chad: countryISO: 'TD' countryName: 'Chad' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'N Djamena' inEU: false Togo: countryISO: 'TG' countryName: 'Togo' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Lome' inEU: false Thailand: countryISO: 'TH' countryName: 'Thailand' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Tajikistan: countryISO: 'TJ' countryName: 'Tajikistan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false 'East Timor': countryISO: 'TL' countryName: 'East Timor' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dili' inEU: false Tunisia: countryISO: 'TN' countryName: 'Tunisia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Tonga: countryISO: 'TO' countryName: 'Tonga' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Nuku alofa' inEU: false Turkey: countryISO: 'TR' countryName: 'Turkey' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Trinidad and Tobago': countryISO: 'TT' countryName: 'Trinidad and Tobago' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Port of Spain' inEU: false Tuvalu: countryISO: 'TV' countryName: 'Tuvalu' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Funafuti' inEU: false Taiwan: countryISO: 'TW' countryName: 'Taiwan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999, 99999' capitalCity: null inEU: false Tanzania: countryISO: 'TZ' countryName: 'Tanzania' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dodoma' inEU: false Ukraine: countryISO: 'UA' countryName: 'Ukraine' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Uganda: countryISO: 'UG' countryName: 'Uganda' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kampala' inEU: false 'United States Of America': countryISO: 'US' countryName: 'United States Of America' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999, 99999-9999' capitalCity: null inEU: false Uruguay: countryISO: 'UY' countryName: 'Uruguay' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Montevideo' inEU: false Uzbekistan: countryISO: 'UZ' countryName: 'Uzbekistan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false 'St. Vincent': countryISO: 'VC' countryName: 'St. Vincent' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kingstown' inEU: false Venezuela: countryISO: 'VE' countryName: 'Venezuela' locationFormat: 'Suburb' usesPostalCode: false postalCodeFormat: null capitalCity: 'Caracas' inEU: false 'Virgin Islands (British)': countryISO: 'VG' countryName: 'Virgin Islands (British)' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Road Town' inEU: false 'Virgin Islands (US)': countryISO: 'VI' countryName: 'Virgin Islands (US)' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Vietnam: countryISO: 'VN' countryName: 'Vietnam' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Hanoi' inEU: false Vanuatu: countryISO: 'VU' countryName: 'Vanuatu' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Port Vila' inEU: false Samoa: countryISO: 'WS' countryName: 'Samoa' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Apia' inEU: false Bonaire: countryISO: 'XB' countryName: 'Bonaire' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kralendijk' inEU: false Curacao: countryISO: 'XC' countryName: 'Curacao' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Willemstad' inEU: false 'St. Eustatius': countryISO: 'XE' countryName: 'St. Eustatius' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Oranjestad' inEU: false 'St. Maarten': countryISO: 'XM' countryName: 'St. Maarten' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Philipsburg' inEU: false Nevis: countryISO: 'XN' countryName: 'Nevis' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Basseterre' inEU: false 'Somaliland, Rep of (North Somalia)': countryISO: 'XS' countryName: 'Somaliland, Rep of (North Somalia)' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Hargeisa' inEU: false 'St. Barthelemy': countryISO: 'XY' countryName: 'St. Barthelemy' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Yemen, Republic of': countryISO: 'YE' countryName: 'Yemen, Republic of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Sana a' inEU: false Mayotte: countryISO: 'YT' countryName: 'Mayotte' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'South Africa': countryISO: 'ZA' countryName: 'South Africa' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Zambia: countryISO: 'ZM' countryName: 'Zambia' locationFormat: 'Suburb' usesPostalCode: false postalCodeFormat: null capitalCity: 'Lusaka' inEU: false Zimbabwe: countryISO: 'ZW' countryName: 'Zimbabwe' locationFormat: 'Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Harare' inEU: false
true
countryData = Andorra: countryISO: 'AD' countryName: 'Andorra' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'United Arab Emirates': countryISO: 'AE' countryName: 'United Arab Emirates' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Abu Dhabi' inEU: false Afghanistan: countryISO: 'AF' countryName: 'Afghanistan' locationFormat: 'Suburb' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kabul' inEU: false Antigua: countryISO: 'AG' countryName: 'Antigua' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'St Johns' inEU: false Anguilla: countryISO: 'AI' countryName: 'Anguilla' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'The Valley' inEU: false Albania: countryISO: 'AL' countryName: 'Albania' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Tirana' inEU: false Armenia: countryISO: 'AM' countryName: 'Armenia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'Netherlands Antilles': countryISO: 'AN' countryName: 'Netherlands Antilles' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Willemstad' inEU: false Angola: countryISO: 'AO' countryName: 'Angola' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Luanda' inEU: false Argentina: countryISO: 'AR' countryName: 'Argentina' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'American Samoa': countryISO: 'AS' countryName: 'American Samoa' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Austria: countryISO: 'AT' countryName: 'Austria' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Australia: countryISO: 'AU' countryName: 'Australia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Aruba: countryISO: 'AW' countryName: 'Aruba' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Oranjestad' inEU: false Azerbaijan: countryISO: 'AZ' countryName: 'Azerbaijan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999, 9999' capitalCity: null inEU: false 'Bosnia and Herzegovina': countryISO: 'BA' countryName: 'Bosnia and Herzegovina' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Barbados: countryISO: 'BB' countryName: 'Barbados' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bridgetown' inEU: false Bangladesh: countryISO: 'BD' countryName: 'Bangladesh' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Belgium: countryISO: 'BE' countryName: 'Belgium' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true 'Burkina Faso': countryISO: 'BF' countryName: 'Burkina Faso' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Ouagadougou' inEU: false Bulgaria: countryISO: 'BG' countryName: 'Bulgaria' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Bahrain: countryISO: 'BH' countryName: 'Bahrain' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Manama' inEU: false Burundi: countryISO: 'BI' countryName: 'Burundi' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bujumbura' inEU: false Benin: countryISO: 'BJ' countryName: 'Benin' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Porto Novo' inEU: false Bermuda: countryISO: 'BM' countryName: 'Bermuda' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Hamilton' inEU: false Brunei: countryISO: 'BN' countryName: 'Brunei' locationFormat: 'City' usesPostalCode: true postalCodeFormat: 'AA9999' capitalCity: null inEU: false Bolivia: countryISO: 'BO' countryName: 'Bolivia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Sucre' inEU: false Brazil: countryISO: 'BR' countryName: 'Brazil' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999,99999-999' capitalCity: null inEU: false Bahamas: countryISO: 'BS' countryName: 'Bahamas' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Nassau' inEU: false Bhutan: countryISO: 'BT' countryName: 'Bhutan' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Thimphu' inEU: false Botswana: countryISO: 'BW' countryName: 'Botswana' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Gaborone' inEU: false Belarus: countryISO: 'BY' countryName: 'Belarus' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Belize: countryISO: 'BZ' countryName: 'Belize' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Belmopan' inEU: false Canada: countryISO: 'CA' countryName: 'Canada' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: 'A9A 9A9,A9A 9A' capitalCity: null inEU: false 'Congo, The Democratic Republic of': countryISO: 'CD' countryName: 'Congo, The Democratic Republic of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kinshasa' inEU: false 'Central African Republic': countryISO: 'CF' countryName: 'Central African Republic' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bangui' inEU: false Congo: countryISO: 'CG' countryName: 'Congo' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kinshasa' inEU: false Switzerland: countryISO: 'CH' countryName: 'Switzerland' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'Cote d\'Ivoire': countryISO: 'CI' countryName: 'Cote d\'Ivoire' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Yamoussoukro' inEU: false 'Cook Islands': countryISO: 'CK' countryName: 'Cook Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Avarua' inEU: false Chile: countryISO: 'CL' countryName: 'Chile' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Santiago' inEU: false Cameroon: countryISO: 'CM' countryName: 'Cameroon' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Yaoune' inEU: false 'China, People\'s Republic': countryISO: 'CN' countryName: 'China, People\'s Republic' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Colombia: countryISO: 'CO' countryName: 'Colombia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bogota' inEU: false 'Costa Rica': countryISO: 'CR' countryName: 'Costa Rica' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'San Jose' inEU: false Cuba: countryISO: 'CU' countryName: 'Cuba' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Cape Verde': countryISO: 'CV' countryName: 'Cape Verde' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Praia' inEU: false Cyprus: countryISO: 'CY' countryName: 'Cyprus' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true 'Czech Republic, The': countryISO: 'CZ' countryName: 'Czech Republic, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999 99' capitalCity: null inEU: true Germany: countryISO: 'DE' countryName: 'Germany' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Djibouti: countryISO: 'DJ' countryName: 'Djibouti' locationFormat: 'Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dijbouti' inEU: false Denmark: countryISO: 'DK' countryName: 'Denmark' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Dominica: countryISO: 'DM' countryName: 'Dominica' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Roseau' inEU: false 'Dominican Rep.': countryISO: 'DO' countryName: 'Dominican Rep.' locationFormat: '' usesPostalCode: false postalCodeFormat: null capitalCity: 'Santo Domingo' inEU: false Algeria: countryISO: 'DZ' countryName: 'Algeria' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Ecuador: countryISO: 'EC' countryName: 'Ecuador' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Quito' inEU: false Estonia: countryISO: 'EE' countryName: 'Estonia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Egypt: countryISO: 'EG' countryName: 'Egypt' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Cairo' inEU: false Eritrea: countryISO: 'ER' countryName: 'Eritrea' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Asmara' inEU: false Spain: countryISO: 'ES' countryName: 'Spain' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Ethiopia: countryISO: 'ET' countryName: 'Ethiopia' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Addis Ababa' inEU: false Finland: countryISO: 'FI' countryName: 'Finland' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Fiji: countryISO: 'FJ' countryName: 'Fiji' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Suva' inEU: false 'Falkland Islands': countryISO: 'FK' countryName: 'Falkland Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Stanley' inEU: false 'Micronesia, Federated States Of': countryISO: 'FM' countryName: 'Micronesia, Federated States Of' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Faroe Islands': countryISO: 'FO' countryName: 'Faroe Islands' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999' capitalCity: null inEU: false France: countryISO: 'FR' countryName: 'France' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Gabon: countryISO: 'GA' countryName: 'Gabon' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Libreville' inEU: false 'United Kingdom': countryISO: 'GB' countryName: 'United Kingdom' locationFormat: 'City' usesPostalCode: true postalCodeFormat: 'A9 9AA, A99 9AA, A9A 9AA, AA9 9AA, AA99 9AA, AA9A 9AA' capitalCity: null inEU: true Grenada: countryISO: 'GD' countryName: 'Grenada' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'St Georges' inEU: false Georgia: countryISO: 'GE' countryName: 'Georgia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'French Guyana': countryISO: 'GF' countryName: 'French Guyana' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Guernsey: countryISO: 'GG' countryName: 'Guernsey' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: 'AA9 9AA' capitalCity: null inEU: false Ghana: countryISO: 'GH' countryName: 'Ghana' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Accra' inEU: false Gibraltar: countryISO: 'GI' countryName: 'Gibraltar' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'GIBRALTAR' inEU: false Greenland: countryISO: 'GL' countryName: 'Greenland' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Gambia: countryISO: 'GM' countryName: 'Gambia' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Banjul' inEU: false 'Guinea Republic': countryISO: 'GN' countryName: 'Guinea Republic' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Conakry' inEU: false Guadeloupe: countryISO: 'GP' countryName: 'Guadeloupe' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Guinea-Equatorial': countryISO: 'GQ' countryName: 'Guinea-Equatorial' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Malabo' inEU: false Greece: countryISO: 'GR' countryName: 'Greece' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999 99' capitalCity: null inEU: true Guatemala: countryISO: 'GT' countryName: 'Guatemala' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Guatemala City' inEU: false Guam: countryISO: 'GU' countryName: 'Guam' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Guinea-Bissau': countryISO: 'GW' countryName: 'Guinea-Bissau' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bissau' inEU: false 'Guyana (British)': countryISO: 'GY' countryName: 'Guyana (British)' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Georgetown' inEU: false 'Hong Kong': countryISO: 'HK' countryName: 'Hong Kong' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Hong Kong' inEU: false Honduras: countryISO: 'HN' countryName: 'Honduras' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Tegucigalpa' inEU: false Croatia: countryISO: 'HR' countryName: 'Croatia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Haiti: countryISO: 'HT' countryName: 'Haiti' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Port-au-Prince' inEU: false Hungary: countryISO: 'HU' countryName: 'Hungary' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true 'Canary Islands, The': countryISO: 'IC' countryName: 'Canary Islands, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Indonesia: countryISO: 'ID' countryName: 'Indonesia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Ireland, Republic Of': countryISO: 'IE' countryName: 'Ireland, Republic Of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dublin' inEU: true Israel: countryISO: 'IL' countryName: 'Israel' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false India: countryISO: 'IN' countryName: 'India' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Iraq: countryISO: 'IQ' countryName: 'Iraq' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Baghdad' inEU: false 'Iran (Islamic Republic of)': countryISO: 'IR' countryName: 'Iran (Islamic Republic of)' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Tehran' inEU: false Iceland: countryISO: 'IS' countryName: 'Iceland' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999' capitalCity: null inEU: true Italy: countryISO: 'IT' countryName: 'Italy' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Jersey: countryISO: 'JE' countryName: 'Jersey' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: 'AA9 9AA' capitalCity: null inEU: false Jamaica: countryISO: 'JM' countryName: 'Jamaica' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kingston' inEU: false Jordan: countryISO: 'JO' countryName: 'Jordan' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Amman' inEU: false Japan: countryISO: 'JP' countryName: 'Japan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999-9999' capitalCity: null inEU: false Kenya: countryISO: 'KE' countryName: 'Kenya' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Nairobi' inEU: false Kyrgyzstan: countryISO: 'KG' countryName: 'Kyrgyzstan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Cambodia: countryISO: 'KH' countryName: 'Cambodia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Phnom Penh' inEU: false Kiribati: countryISO: 'KI' countryName: 'Kiribati' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'South Tarawa' inEU: false Comoros: countryISO: 'KM' countryName: 'Comoros' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Moroni' inEU: false 'St. Kitts': countryISO: 'KN' countryName: 'St. Kitts' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Basseterre' inEU: false 'Korea, The D.P.R of': countryISO: 'KP' countryName: 'Korea, The D.P.R of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Pyongyang' inEU: false 'Korea, Republic Of': countryISO: 'KR' countryName: 'Korea, Republic Of' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999-999' capitalCity: null inEU: false Kosovo: countryISO: 'KV' countryName: 'Kosovo' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Kuwait: countryISO: 'KW' countryName: 'Kuwait' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kuwait City' inEU: false 'Cayman Islands': countryISO: 'KY' countryName: 'Cayman Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'George Town' inEU: false Kazakhstan: countryISO: 'KZ' countryName: 'Kazakhstan' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false 'Lao People\'s Democratic Republic': countryISO: 'LA' countryName: 'Lao People\'s Democratic Republic' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Vientiane' inEU: false Lebanon: countryISO: 'LB' countryName: 'Lebanon' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Beirut' inEU: false 'St. Lucia': countryISO: 'LC' countryName: 'St. Lucia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Castries' inEU: false Liechtenstein: countryISO: 'LI' countryName: 'Liechtenstein' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true 'Sri Lanka': countryISO: 'LK' countryName: 'Sri Lanka' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Colombo' inEU: false Liberia: countryISO: 'LR' countryName: 'Liberia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Monrovia' inEU: false Lesotho: countryISO: 'LS' countryName: 'Lesotho' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Maseru' inEU: false Lithuania: countryISO: 'LT' countryName: 'Lithuania' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: true Luxembourg: countryISO: 'LU' countryName: 'Luxembourg' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Latvia: countryISO: 'LV' countryName: 'Latvia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Libya: countryISO: 'LY' countryName: 'Libya' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Tripoli' inEU: false Morocco: countryISO: 'MA' countryName: 'Morocco' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Monaco: countryISO: 'MC' countryName: 'Monaco' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Moldova, Republic Of': countryISO: 'MD' countryName: 'Moldova, Republic Of' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false 'Montenegro, Republic of': countryISO: 'ME' countryName: 'Montenegro, Republic of' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Madagascar: countryISO: 'MG' countryName: 'Madagascar' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999' capitalCity: null inEU: false 'Marshall Islands': countryISO: 'MH' countryName: 'Marshall Islands' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Macedonia, Rep. of (FYROM)': countryISO: 'MK' countryName: 'Macedonia, Rep. of (FYROM)' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Mali: countryISO: 'ML' countryName: 'Mali' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Bamako' inEU: false Myanmar: countryISO: 'MM' countryName: 'Myanmar' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Yangon' inEU: false Mongolia: countryISO: 'MN' countryName: 'Mongolia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999, 99999' capitalCity: null inEU: false Macau: countryISO: 'MO' countryName: 'Macau' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Macau' inEU: false Saipan: countryISO: 'MP' countryName: 'Saipan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Martinique: countryISO: 'MQ' countryName: 'Martinique' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Mauritania: countryISO: 'MR' countryName: 'Mauritania' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Nouakchott' inEU: false Montserrat: countryISO: 'MS' countryName: 'Montserrat' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Plymouth' inEU: false Malta: countryISO: 'MT' countryName: 'Malta' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Valletta' inEU: true Mauritius: countryISO: 'MU' countryName: 'Mauritius' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Port Louis' inEU: false Maldives: countryISO: 'MV' countryName: 'Maldives' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999, 9999' capitalCity: null inEU: false Malawi: countryISO: 'MW' countryName: 'Malawi' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Lilongwe' inEU: false Mexico: countryISO: 'MX' countryName: 'Mexico' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Malaysia: countryISO: 'MY' countryName: 'Malaysia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Mozambique: countryISO: 'MZ' countryName: 'Mozambique' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Maputo' inEU: false Namibia: countryISO: 'NA' countryName: 'Namibia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Windhoek' inEU: false 'New Caledonia': countryISO: 'NC' countryName: 'New Caledonia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Niger: countryISO: 'NE' countryName: 'Niger' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Niamey' inEU: false Nigeria: countryISO: 'NG' countryName: 'Nigeria' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Abuja' inEU: false Nicaragua: countryISO: 'NI' countryName: 'Nicaragua' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Managua' inEU: false 'Netherlands, The': countryISO: 'NL' countryName: 'Netherlands, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Norway: countryISO: 'NO' countryName: 'Norway' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Nepal: countryISO: 'NP' countryName: 'Nepal' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kathmandu' inEU: false 'Nauru, Republic Of': countryISO: 'NR' countryName: 'Nauru, Republic Of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Yaren District' inEU: false Niue: countryISO: 'NU' countryName: 'Niue' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Alofi' inEU: false 'New Zealand': countryISO: 'NZ' countryName: 'New Zealand' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Oman: countryISO: 'OM' countryName: 'PI:NAME:<NAME>END_PIman' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Muscat' inEU: false Panama: countryISO: 'PA' countryName: 'Panama' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Panama City' inEU: false Peru: countryISO: 'PE' countryName: 'Peru' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Lima' inEU: false Tahiti: countryISO: 'PF' countryName: 'Tahiti' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Papeete' inEU: false 'Papua New Guinea': countryISO: 'PG' countryName: 'Papua New Guinea' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999' capitalCity: null inEU: false 'Philippines, The': countryISO: 'PH' countryName: 'Philippines, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Pakistan: countryISO: 'PK' countryName: 'Pakistan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Poland: countryISO: 'PL' countryName: 'Poland' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99-999' capitalCity: null inEU: true 'Puerto Rico': countryISO: 'PR' countryName: 'Puerto Rico' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Portugal: countryISO: 'PT' countryName: 'Portugal' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999, 9999-999' capitalCity: null inEU: true Palau: countryISO: 'PW' countryName: 'Palau' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Paraguay: countryISO: 'PY' countryName: 'Paraguay' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Asuncion' inEU: false Qatar: countryISO: 'QA' countryName: 'Qatar' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Doha' inEU: false 'Reunion, Island Of': countryISO: 'RE' countryName: 'Reunion, Island Of' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Romania: countryISO: 'RO' countryName: 'Romania' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: true 'Serbia, Republic of': countryISO: 'RS' countryName: 'Serbia, Republic of' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Russian Federation, The': countryISO: 'RU' countryName: 'Russian Federation, The' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false Rwanda: countryISO: 'RW' countryName: 'Rwanda' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kigali' inEU: false 'Saudi Arabia': countryISO: 'SA' countryName: 'Saudi Arabia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Riyadh' inEU: false 'Solomon Islands': countryISO: 'SB' countryName: 'Solomon Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Honiara' inEU: false Seychelles: countryISO: 'SC' countryName: 'Seychelles' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Victoria' inEU: false Sudan: countryISO: 'SD' countryName: 'Sudan' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Khartoum' inEU: false Sweden: countryISO: 'SE' countryName: 'Sweden' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999 99' capitalCity: null inEU: true Singapore: countryISO: 'SG' countryName: 'Singapore' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false 'SAINT HELENA': countryISO: 'SH' countryName: 'SAINT HELENA' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: null inEU: false Slovenia: countryISO: 'SI' countryName: 'Slovenia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: true Slovakia: countryISO: 'SK' countryName: 'Slovakia' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '999 99' capitalCity: null inEU: true 'Sierra Leone': countryISO: 'SL' countryName: 'Sierra Leone' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Freetown' inEU: false 'San Marino': countryISO: 'SM' countryName: 'San Marino' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Senegal: countryISO: 'SN' countryName: 'Senegal' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dakar' inEU: false Somalia: countryISO: 'SO' countryName: 'Somalia' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Mogadishu' inEU: false Suriname: countryISO: 'SR' countryName: 'Suriname' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Paramaribo' inEU: false 'South Sudan': countryISO: 'SS' countryName: 'South Sudan' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Juba' inEU: false 'Sao Tome and Principe': countryISO: 'ST' countryName: 'Sao Tome and Principe' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Sao Tome' inEU: false 'El Salvador': countryISO: 'SV' countryName: 'El Salvador' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'San Salvador' inEU: false Syria: countryISO: 'SY' countryName: 'Syria' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Damascus' inEU: false Swaziland: countryISO: 'SZ' countryName: 'Swaziland' locationFormat: 'City' usesPostalCode: true postalCodeFormat: 'A999' capitalCity: null inEU: false 'Turks and Caicos Islands': countryISO: 'TC' countryName: 'Turks and Caicos Islands' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Cockburn Town' inEU: false Chad: countryISO: 'TD' countryName: 'Chad' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'N Djamena' inEU: false Togo: countryISO: 'TG' countryName: 'Togo' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Lome' inEU: false Thailand: countryISO: 'TH' countryName: 'Thailand' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Tajikistan: countryISO: 'TJ' countryName: 'Tajikistan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false 'East Timor': countryISO: 'TL' countryName: 'East Timor' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dili' inEU: false Tunisia: countryISO: 'TN' countryName: 'Tunisia' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Tonga: countryISO: 'TO' countryName: 'Tonga' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Nuku alofa' inEU: false Turkey: countryISO: 'TR' countryName: 'Turkey' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Trinidad and Tobago': countryISO: 'TT' countryName: 'Trinidad and Tobago' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Port of Spain' inEU: false Tuvalu: countryISO: 'TV' countryName: 'Tuvalu' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Funafuti' inEU: false Taiwan: countryISO: 'TW' countryName: 'Taiwan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999, 99999' capitalCity: null inEU: false Tanzania: countryISO: 'TZ' countryName: 'Tanzania' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Dodoma' inEU: false Ukraine: countryISO: 'UA' countryName: 'Ukraine' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Uganda: countryISO: 'UG' countryName: 'Uganda' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kampala' inEU: false 'United States Of America': countryISO: 'US' countryName: 'United States Of America' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999, 99999-9999' capitalCity: null inEU: false Uruguay: countryISO: 'UY' countryName: 'Uruguay' locationFormat: 'City Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Montevideo' inEU: false Uzbekistan: countryISO: 'UZ' countryName: 'Uzbekistan' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '999999' capitalCity: null inEU: false 'St. Vincent': countryISO: 'VC' countryName: 'St. Vincent' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kingstown' inEU: false Venezuela: countryISO: 'VE' countryName: 'Venezuela' locationFormat: 'Suburb' usesPostalCode: false postalCodeFormat: null capitalCity: 'Caracas' inEU: false 'Virgin Islands (British)': countryISO: 'VG' countryName: 'Virgin Islands (British)' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Road Town' inEU: false 'Virgin Islands (US)': countryISO: 'VI' countryName: 'Virgin Islands (US)' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false Vietnam: countryISO: 'VN' countryName: 'Vietnam' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Hanoi' inEU: false Vanuatu: countryISO: 'VU' countryName: 'Vanuatu' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Port Vila' inEU: false Samoa: countryISO: 'WS' countryName: 'Samoa' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Apia' inEU: false Bonaire: countryISO: 'XB' countryName: 'Bonaire' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Kralendijk' inEU: false Curacao: countryISO: 'XC' countryName: 'Curacao' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Willemstad' inEU: false 'St. Eustatius': countryISO: 'XE' countryName: 'St. Eustatius' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Oranjestad' inEU: false 'St. Maarten': countryISO: 'XM' countryName: 'St. Maarten' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Philipsburg' inEU: false Nevis: countryISO: 'XN' countryName: 'Nevis' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Basseterre' inEU: false 'Somaliland, Rep of (North Somalia)': countryISO: 'XS' countryName: 'Somaliland, Rep of (North Somalia)' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Hargeisa' inEU: false 'St. Barthelemy': countryISO: 'XY' countryName: 'St. Barthelemy' locationFormat: 'City' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'Yemen, Republic of': countryISO: 'YE' countryName: 'Yemen, Republic of' locationFormat: 'City' usesPostalCode: false postalCodeFormat: null capitalCity: 'Sana a' inEU: false Mayotte: countryISO: 'YT' countryName: 'Mayotte' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '99999' capitalCity: null inEU: false 'South Africa': countryISO: 'ZA' countryName: 'South Africa' locationFormat: 'City Postcode' usesPostalCode: true postalCodeFormat: '9999' capitalCity: null inEU: false Zambia: countryISO: 'ZM' countryName: 'Zambia' locationFormat: 'Suburb' usesPostalCode: false postalCodeFormat: null capitalCity: 'Lusaka' inEU: false Zimbabwe: countryISO: 'ZW' countryName: 'Zimbabwe' locationFormat: 'Postcode' usesPostalCode: false postalCodeFormat: null capitalCity: 'Harare' inEU: false
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9993985295295715, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-vm-global-define-property.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") vm = require("vm") code = "Object.defineProperty(this, \"f\", {\n" + " get: function() { return x; },\n" + " set: function(k) { x = k; },\n" + " configurable: true,\n" + " enumerable: true\n" + "});\n" + "g = f;\n" + "f;\n" x = {} o = vm.createContext( console: console x: x ) res = vm.runInContext(code, o, "test") assert res assert.equal typeof res, "object" assert.equal res, x assert.equal o.f, res assert.deepEqual Object.keys(o), [ "console" "x" "g" "f" ]
139375
# 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") vm = require("vm") code = "Object.defineProperty(this, \"f\", {\n" + " get: function() { return x; },\n" + " set: function(k) { x = k; },\n" + " configurable: true,\n" + " enumerable: true\n" + "});\n" + "g = f;\n" + "f;\n" x = {} o = vm.createContext( console: console x: x ) res = vm.runInContext(code, o, "test") assert res assert.equal typeof res, "object" assert.equal res, x assert.equal o.f, res assert.deepEqual Object.keys(o), [ "console" "x" "g" "f" ]
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") vm = require("vm") code = "Object.defineProperty(this, \"f\", {\n" + " get: function() { return x; },\n" + " set: function(k) { x = k; },\n" + " configurable: true,\n" + " enumerable: true\n" + "});\n" + "g = f;\n" + "f;\n" x = {} o = vm.createContext( console: console x: x ) res = vm.runInContext(code, o, "test") assert res assert.equal typeof res, "object" assert.equal res, x assert.equal o.f, res assert.deepEqual Object.keys(o), [ "console" "x" "g" "f" ]
[ { "context": " url = tab.url\n\n li key: \"tab-li-#{index}\", className: tab.class,\n ", "end": 1005, "score": 0.8679496645927429, "start": 1000, "tag": "KEY", "value": "li-#{" }, { "context": " href: url\n key: \"ta...
client/app/components/basic_components.coffee
cozy-labs/emails
58
{ div section h3 h4 ul li a i button span fieldset legend label img form } = React.DOM classer = React.addons.classSet Container = React.createClass render: -> section id: @props.id key: @props.key className: 'panel' , @props.children Title = React.createClass render: -> h3 refs: @props.ref className: 'title' , @props.text SubTitle = React.createClass render: -> h4 refs: @props.ref className: 'subtitle ' + @props.className , @props.text Tabs = React.createClass render: -> ul className: "nav nav-tabs", role: "tablist", for index, tab of @props.tabs if tab.class?.indexOf('active') >= 0 url = null else url = tab.url li key: "tab-li-#{index}", className: tab.class, a href: url key: "tab-#{index}" , tab.text ErrorLine = React.createClass render: -> div className: 'col-sm-5 col-sm-offset-2 control-label', @props.text Form = React.createClass render: -> form id: @props.id className: @props.className method: 'POST' , @props.children FieldSet = React.createClass render: -> fieldset null, legend null, @props.text @props.children FormButton = React.createClass render: -> className = 'btn ' if @props.contrast className += 'btn-cozy-contrast ' else if @props.default className += 'btn-cozy-default ' else className += 'btn-cozy ' if @props.danger className += 'btn-danger ' if @props.class? className += @props.class button className: className onClick: @props.onClick , if @props.spinner span null, Spinner(white: true) else span className: "fa fa-#{@props.icon}" span null, @props.text FormButtons = React.createClass render: -> div null, div className: 'col-sm-offset-4', for formButton, index in @props.buttons formButton.key = index FormButton formButton MenuItem = React.createClass render: -> liOptions = role: 'presentation' liOptions.key = @props.key if @props.key liOptions.className = @props.liClassName if @props.liClassName aOptions = role: 'menuitemu' onClick: @props.onClick aOptions.className = @props.className if @props.className aOptions.href = @props.href if @props.href aOptions.target = @props.href if @props.target li liOptions, a aOptions, @props.children MenuHeader = React.createClass render: -> liOptions = role: 'presentation', className: 'dropdown-header' liOptions.key = @props.key if @props.key li liOptions, @props.children MenuDivider = React.createClass render: -> liOptions = role: 'presentation', className: 'divider' liOptions.key = @props.key if @props.key li liOptions FormDropdown = React.createClass render: -> div key: "account-input-#{@props.name}" className: "form-group account-item-#{@props.name} " , label htmlFor: "#{@props.prefix}-#{@props.name}", className: "col-sm-2 col-sm-offset-2 control-label" , @props.labelText div className: 'col-sm-3', div className: "dropdown", button id: "#{@props.prefix}-#{@props.name}" name: "#{@props.prefix}-#{@props.name}" className: "btn btn-default dropdown-toggle" type: "button" "data-toggle": "dropdown" , @props.defaultText ul className: "dropdown-menu", role: "menu", @props.values.map (method) => li role: "presentation", a 'data-value': method role: "menuitem" onClick: @props.onClick , t "#{@props.methodPrefix} #{method}" # Widget to display contact following these rules: # If a name is provided => Contact Name <address@contact.com> # If no name is provided => address@contact.com AddressLabel = React.createClass render: -> meaninglessKey = 0 if @props.contact.name?.length > 0 and @props.contact.address key = @props.contact.address.replace /\W/g, '' result = span null, span className: 'highlight' @props.contact.name span className: 'contact-address' key: key , i className: 'fa fa-angle-left' @props.contact.address i className: 'fa fa-angle-right' else if @props.contact.name?.length > 0 result = span key: "label-#{meaninglessKey++}", @props.contact.name else result = span null, @props.contact.address return result # Available properties: # - values: {key -> value} # - value: optional key of current value Dropdown = React.createClass displayName: 'Dropdown' getInitialState: -> defaultKey = if @props.value? then @props.value else Object.keys(@props.values)[0] state= label: @props.values[defaultKey] render: -> renderFilter = (key, value) => onChange = => @setState label: value @props.onChange key li role: 'presentation' onClick: onChange key: key, a role: 'menuitem' value div className: 'dropdown', button className: 'dropdown-toggle' type: 'button' 'data-toggle': 'dropdown' "#{@state.label} " span className: 'caret', '' ul className: 'dropdown-menu', role: 'menu', for key, value of @props.values renderFilter key, t "list filter #{key}" # Widget to display a spinner. # If property `white` is set to true, it will use the white version. Spinner = React.createClass displayName: 'Spinner' protoTypes: white: React.PropTypes.bool render: -> suffix = if @props.white then '-white' else '' img src: "images/spinner#{suffix}.svg" alt: 'spinner' className: 'button-spinner' # Module to display a loading progress bar. It takes a current value and a # max value as paremeter. Progress = React.createClass displayName: 'Progress' propTypes: value: React.PropTypes.number.isRequired max: React.PropTypes.number.isRequired render: -> div className: 'progress', div className: classer 'progress-bar': true 'actived': @props.value > 0 style: width: 0 role: 'progressbar' "aria-valuenow": @props.value "aria-valuemin": '0' "aria-valuemax": @props.max module.exports = { AddressLabel Container Dropdown ErrorLine Form FieldSet FormButton FormButtons FormDropdown MenuItem MenuHeader MenuDivider Progress Spinner SubTitle Title Tabs }
118208
{ div section h3 h4 ul li a i button span fieldset legend label img form } = React.DOM classer = React.addons.classSet Container = React.createClass render: -> section id: @props.id key: @props.key className: 'panel' , @props.children Title = React.createClass render: -> h3 refs: @props.ref className: 'title' , @props.text SubTitle = React.createClass render: -> h4 refs: @props.ref className: 'subtitle ' + @props.className , @props.text Tabs = React.createClass render: -> ul className: "nav nav-tabs", role: "tablist", for index, tab of @props.tabs if tab.class?.indexOf('active') >= 0 url = null else url = tab.url li key: "tab-<KEY>index}", className: tab.class, a href: url key: "tab-<KEY>}" , tab.text ErrorLine = React.createClass render: -> div className: 'col-sm-5 col-sm-offset-2 control-label', @props.text Form = React.createClass render: -> form id: @props.id className: @props.className method: 'POST' , @props.children FieldSet = React.createClass render: -> fieldset null, legend null, @props.text @props.children FormButton = React.createClass render: -> className = 'btn ' if @props.contrast className += 'btn-cozy-contrast ' else if @props.default className += 'btn-cozy-default ' else className += 'btn-cozy ' if @props.danger className += 'btn-danger ' if @props.class? className += @props.class button className: className onClick: @props.onClick , if @props.spinner span null, Spinner(white: true) else span className: "fa fa-#{@props.icon}" span null, @props.text FormButtons = React.createClass render: -> div null, div className: 'col-sm-offset-4', for formButton, index in @props.buttons formButton.key = index FormButton formButton MenuItem = React.createClass render: -> liOptions = role: 'presentation' liOptions.key = @props.key if @props.key liOptions.className = @props.liClassName if @props.liClassName aOptions = role: 'menuitemu' onClick: @props.onClick aOptions.className = @props.className if @props.className aOptions.href = @props.href if @props.href aOptions.target = @props.href if @props.target li liOptions, a aOptions, @props.children MenuHeader = React.createClass render: -> liOptions = role: 'presentation', className: 'dropdown-header' liOptions.key = @props.key if @props.key li liOptions, @props.children MenuDivider = React.createClass render: -> liOptions = role: 'presentation', className: 'divider' liOptions.key = @props.key if @props.key li liOptions FormDropdown = React.createClass render: -> div key: "account-input-#{@props.name}" className: "form-group account-item-#{@props.name} " , label htmlFor: "#{@props.prefix}-#{@props.name}", className: "col-sm-2 col-sm-offset-2 control-label" , @props.labelText div className: 'col-sm-3', div className: "dropdown", button id: "#{@props.prefix}-#{@props.name}" name: "#{@props.prefix}-#{@props.name}" className: "btn btn-default dropdown-toggle" type: "button" "data-toggle": "dropdown" , @props.defaultText ul className: "dropdown-menu", role: "menu", @props.values.map (method) => li role: "presentation", a 'data-value': method role: "menuitem" onClick: @props.onClick , t "#{@props.methodPrefix} #{method}" # Widget to display contact following these rules: # If a name is provided => Contact Name <<EMAIL>> # If no name is provided => <EMAIL> AddressLabel = React.createClass render: -> meaninglessKey = 0 if @props.contact.name?.length > 0 and @props.contact.address key = @props.contact.address.replace /\<KEY>/<KEY>, '' result = span null, span className: 'highlight' @props.contact.name span className: 'contact-address' key: key , i className: 'fa fa-angle-left' @props.contact.address i className: 'fa fa-angle-right' else if @props.contact.name?.length > 0 result = span key: "label-#{meaninglessKey++}", @props.contact.name else result = span null, @props.contact.address return result # Available properties: # - values: {key -> value} # - value: optional key of current value Dropdown = React.createClass displayName: 'Dropdown' getInitialState: -> defaultKey = if @props.value? then @props.value else Object.keys(@props.values)[0] state= label: @props.values[defaultKey] render: -> renderFilter = (key, value) => onChange = => @setState label: value @props.onChange key li role: 'presentation' onClick: onChange key: key, a role: 'menuitem' value div className: 'dropdown', button className: 'dropdown-toggle' type: 'button' 'data-toggle': 'dropdown' "#{@state.label} " span className: 'caret', '' ul className: 'dropdown-menu', role: 'menu', for key, value of @props.values renderFilter key, t "list filter #{key}" # Widget to display a spinner. # If property `white` is set to true, it will use the white version. Spinner = React.createClass displayName: 'Spinner' protoTypes: white: React.PropTypes.bool render: -> suffix = if @props.white then '-white' else '' img src: "images/spinner#{suffix}.svg" alt: 'spinner' className: 'button-spinner' # Module to display a loading progress bar. It takes a current value and a # max value as paremeter. Progress = React.createClass displayName: 'Progress' propTypes: value: React.PropTypes.number.isRequired max: React.PropTypes.number.isRequired render: -> div className: 'progress', div className: classer 'progress-bar': true 'actived': @props.value > 0 style: width: 0 role: 'progressbar' "aria-valuenow": @props.value "aria-valuemin": '0' "aria-valuemax": @props.max module.exports = { AddressLabel Container Dropdown ErrorLine Form FieldSet FormButton FormButtons FormDropdown MenuItem MenuHeader MenuDivider Progress Spinner SubTitle Title Tabs }
true
{ div section h3 h4 ul li a i button span fieldset legend label img form } = React.DOM classer = React.addons.classSet Container = React.createClass render: -> section id: @props.id key: @props.key className: 'panel' , @props.children Title = React.createClass render: -> h3 refs: @props.ref className: 'title' , @props.text SubTitle = React.createClass render: -> h4 refs: @props.ref className: 'subtitle ' + @props.className , @props.text Tabs = React.createClass render: -> ul className: "nav nav-tabs", role: "tablist", for index, tab of @props.tabs if tab.class?.indexOf('active') >= 0 url = null else url = tab.url li key: "tab-PI:KEY:<KEY>END_PIindex}", className: tab.class, a href: url key: "tab-PI:KEY:<KEY>END_PI}" , tab.text ErrorLine = React.createClass render: -> div className: 'col-sm-5 col-sm-offset-2 control-label', @props.text Form = React.createClass render: -> form id: @props.id className: @props.className method: 'POST' , @props.children FieldSet = React.createClass render: -> fieldset null, legend null, @props.text @props.children FormButton = React.createClass render: -> className = 'btn ' if @props.contrast className += 'btn-cozy-contrast ' else if @props.default className += 'btn-cozy-default ' else className += 'btn-cozy ' if @props.danger className += 'btn-danger ' if @props.class? className += @props.class button className: className onClick: @props.onClick , if @props.spinner span null, Spinner(white: true) else span className: "fa fa-#{@props.icon}" span null, @props.text FormButtons = React.createClass render: -> div null, div className: 'col-sm-offset-4', for formButton, index in @props.buttons formButton.key = index FormButton formButton MenuItem = React.createClass render: -> liOptions = role: 'presentation' liOptions.key = @props.key if @props.key liOptions.className = @props.liClassName if @props.liClassName aOptions = role: 'menuitemu' onClick: @props.onClick aOptions.className = @props.className if @props.className aOptions.href = @props.href if @props.href aOptions.target = @props.href if @props.target li liOptions, a aOptions, @props.children MenuHeader = React.createClass render: -> liOptions = role: 'presentation', className: 'dropdown-header' liOptions.key = @props.key if @props.key li liOptions, @props.children MenuDivider = React.createClass render: -> liOptions = role: 'presentation', className: 'divider' liOptions.key = @props.key if @props.key li liOptions FormDropdown = React.createClass render: -> div key: "account-input-#{@props.name}" className: "form-group account-item-#{@props.name} " , label htmlFor: "#{@props.prefix}-#{@props.name}", className: "col-sm-2 col-sm-offset-2 control-label" , @props.labelText div className: 'col-sm-3', div className: "dropdown", button id: "#{@props.prefix}-#{@props.name}" name: "#{@props.prefix}-#{@props.name}" className: "btn btn-default dropdown-toggle" type: "button" "data-toggle": "dropdown" , @props.defaultText ul className: "dropdown-menu", role: "menu", @props.values.map (method) => li role: "presentation", a 'data-value': method role: "menuitem" onClick: @props.onClick , t "#{@props.methodPrefix} #{method}" # Widget to display contact following these rules: # If a name is provided => Contact Name <PI:EMAIL:<EMAIL>END_PI> # If no name is provided => PI:EMAIL:<EMAIL>END_PI AddressLabel = React.createClass render: -> meaninglessKey = 0 if @props.contact.name?.length > 0 and @props.contact.address key = @props.contact.address.replace /\PI:KEY:<KEY>END_PI/PI:KEY:<KEY>END_PI, '' result = span null, span className: 'highlight' @props.contact.name span className: 'contact-address' key: key , i className: 'fa fa-angle-left' @props.contact.address i className: 'fa fa-angle-right' else if @props.contact.name?.length > 0 result = span key: "label-#{meaninglessKey++}", @props.contact.name else result = span null, @props.contact.address return result # Available properties: # - values: {key -> value} # - value: optional key of current value Dropdown = React.createClass displayName: 'Dropdown' getInitialState: -> defaultKey = if @props.value? then @props.value else Object.keys(@props.values)[0] state= label: @props.values[defaultKey] render: -> renderFilter = (key, value) => onChange = => @setState label: value @props.onChange key li role: 'presentation' onClick: onChange key: key, a role: 'menuitem' value div className: 'dropdown', button className: 'dropdown-toggle' type: 'button' 'data-toggle': 'dropdown' "#{@state.label} " span className: 'caret', '' ul className: 'dropdown-menu', role: 'menu', for key, value of @props.values renderFilter key, t "list filter #{key}" # Widget to display a spinner. # If property `white` is set to true, it will use the white version. Spinner = React.createClass displayName: 'Spinner' protoTypes: white: React.PropTypes.bool render: -> suffix = if @props.white then '-white' else '' img src: "images/spinner#{suffix}.svg" alt: 'spinner' className: 'button-spinner' # Module to display a loading progress bar. It takes a current value and a # max value as paremeter. Progress = React.createClass displayName: 'Progress' propTypes: value: React.PropTypes.number.isRequired max: React.PropTypes.number.isRequired render: -> div className: 'progress', div className: classer 'progress-bar': true 'actived': @props.value > 0 style: width: 0 role: 'progressbar' "aria-valuenow": @props.value "aria-valuemin": '0' "aria-valuemax": @props.max module.exports = { AddressLabel Container Dropdown ErrorLine Form FieldSet FormButton FormButtons FormDropdown MenuItem MenuHeader MenuDivider Progress Spinner SubTitle Title Tabs }
[ { "context": "--------------\n# Copyright Joe Drago 2018.\n# Distributed under the Boost Softw", "end": 123, "score": 0.9998160600662231, "start": 114, "tag": "NAME", "value": "Joe Drago" } ]
lib/templates/src/coffee/App.coffee
EwoutH/colorist
0
# --------------------------------------------------------------------------- # Copyright Joe Drago 2018. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # --------------------------------------------------------------------------- DOM = require 'react-dom' React = require 'react' tags = require './tags' {el, div} = require './tags' Drawer = require('material-ui/Drawer').default MenuItem = require('material-ui/MenuItem').default PixelsView = require './PixelsView' SummaryView = require './SummaryView' StructArray = require './StructArray' class App extends React.Component constructor: (props) -> super props # Do this one time on startup, for performance @rawPixels = new StructArray(COLORIST_DATA.raw) @highlightInfos = new StructArray(COLORIST_DATA.srgb.info) @state = width: 0 height: 0 navOpen: false view: null @views = summary: SummaryView pixels: PixelsView srgb: PixelsView @navigate(true) window.addEventListener('hashchange', (event) => @navigate() , false) navigate: (fromConstructor = false) -> newHash = decodeURIComponent(window.location.hash.replace(/^#\/?|\/$/g, '')) view = newHash.split('/')[0] viewArg = newHash.substring(view.length+1) if not @views.hasOwnProperty(view) view = 'summary' viewArg = '' @redirect('#summary') if fromConstructor @state.view = view @state.viewArg = viewArg else @setState { view: view, viewArg: viewArg } componentDidMount: -> # Calculate size. TODO: Detect resize and fix containerDom = document.getElementById("appcontainer") console.log "#{containerDom.clientWidth}x#{containerDom.clientHeight}" if (@state.width != containerDom.clientWidth) || (@state.height != containerDom.clientHeight) setTimeout => @setState({ width: containerDom.clientWidth, height: containerDom.clientHeight }) , 0 redirect: (newHash) -> window.location.hash = newHash return toggleNav: -> @setState { navOpen: !@state.navOpen } render: -> if (@state.width == 0) or (@state.height == 0) return [] cie = document.getElementById("cie") elements = [] # Left navigation panel navMenuItems = [ el MenuItem, { key: "menu.title" primaryText: "Available Reports" disabled: true } el MenuItem, { key: "menu.summary" primaryText: "Summary" leftIcon: tags.icon 'event_note' onClick: (e) => e.preventDefault() @redirect('#summary') @setState { navOpen: false } } el MenuItem, { key: "menu.pixels" primaryText: "Pixels" leftIcon: tags.icon 'event_note' onClick: (e) => e.preventDefault() @redirect('#pixels') @setState { navOpen: false } } el MenuItem, { key: "menu.srgb" primaryText: "sRGB Highlight (#{COLORIST_DATA.srgb.highlightLuminance})" leftIcon: tags.icon 'event_note' onClick: (e) => e.preventDefault() @redirect('#srgb') @setState { navOpen: false } } ] elements.push el Drawer, { key: 'leftnav' docked: false open: @state.navOpen disableSwipeToOpen: true onRequestChange: (open) => @setState { navOpen: open } }, navMenuItems # Main view if @state.view != null elements.push el @views[@state.view], { name: @state.view key: @state.view width: @state.width height: @state.height app: this } return elements module.exports = App
195349
# --------------------------------------------------------------------------- # Copyright <NAME> 2018. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # --------------------------------------------------------------------------- DOM = require 'react-dom' React = require 'react' tags = require './tags' {el, div} = require './tags' Drawer = require('material-ui/Drawer').default MenuItem = require('material-ui/MenuItem').default PixelsView = require './PixelsView' SummaryView = require './SummaryView' StructArray = require './StructArray' class App extends React.Component constructor: (props) -> super props # Do this one time on startup, for performance @rawPixels = new StructArray(COLORIST_DATA.raw) @highlightInfos = new StructArray(COLORIST_DATA.srgb.info) @state = width: 0 height: 0 navOpen: false view: null @views = summary: SummaryView pixels: PixelsView srgb: PixelsView @navigate(true) window.addEventListener('hashchange', (event) => @navigate() , false) navigate: (fromConstructor = false) -> newHash = decodeURIComponent(window.location.hash.replace(/^#\/?|\/$/g, '')) view = newHash.split('/')[0] viewArg = newHash.substring(view.length+1) if not @views.hasOwnProperty(view) view = 'summary' viewArg = '' @redirect('#summary') if fromConstructor @state.view = view @state.viewArg = viewArg else @setState { view: view, viewArg: viewArg } componentDidMount: -> # Calculate size. TODO: Detect resize and fix containerDom = document.getElementById("appcontainer") console.log "#{containerDom.clientWidth}x#{containerDom.clientHeight}" if (@state.width != containerDom.clientWidth) || (@state.height != containerDom.clientHeight) setTimeout => @setState({ width: containerDom.clientWidth, height: containerDom.clientHeight }) , 0 redirect: (newHash) -> window.location.hash = newHash return toggleNav: -> @setState { navOpen: !@state.navOpen } render: -> if (@state.width == 0) or (@state.height == 0) return [] cie = document.getElementById("cie") elements = [] # Left navigation panel navMenuItems = [ el MenuItem, { key: "menu.title" primaryText: "Available Reports" disabled: true } el MenuItem, { key: "menu.summary" primaryText: "Summary" leftIcon: tags.icon 'event_note' onClick: (e) => e.preventDefault() @redirect('#summary') @setState { navOpen: false } } el MenuItem, { key: "menu.pixels" primaryText: "Pixels" leftIcon: tags.icon 'event_note' onClick: (e) => e.preventDefault() @redirect('#pixels') @setState { navOpen: false } } el MenuItem, { key: "menu.srgb" primaryText: "sRGB Highlight (#{COLORIST_DATA.srgb.highlightLuminance})" leftIcon: tags.icon 'event_note' onClick: (e) => e.preventDefault() @redirect('#srgb') @setState { navOpen: false } } ] elements.push el Drawer, { key: 'leftnav' docked: false open: @state.navOpen disableSwipeToOpen: true onRequestChange: (open) => @setState { navOpen: open } }, navMenuItems # Main view if @state.view != null elements.push el @views[@state.view], { name: @state.view key: @state.view width: @state.width height: @state.height app: this } return elements module.exports = App
true
# --------------------------------------------------------------------------- # Copyright PI:NAME:<NAME>END_PI 2018. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # --------------------------------------------------------------------------- DOM = require 'react-dom' React = require 'react' tags = require './tags' {el, div} = require './tags' Drawer = require('material-ui/Drawer').default MenuItem = require('material-ui/MenuItem').default PixelsView = require './PixelsView' SummaryView = require './SummaryView' StructArray = require './StructArray' class App extends React.Component constructor: (props) -> super props # Do this one time on startup, for performance @rawPixels = new StructArray(COLORIST_DATA.raw) @highlightInfos = new StructArray(COLORIST_DATA.srgb.info) @state = width: 0 height: 0 navOpen: false view: null @views = summary: SummaryView pixels: PixelsView srgb: PixelsView @navigate(true) window.addEventListener('hashchange', (event) => @navigate() , false) navigate: (fromConstructor = false) -> newHash = decodeURIComponent(window.location.hash.replace(/^#\/?|\/$/g, '')) view = newHash.split('/')[0] viewArg = newHash.substring(view.length+1) if not @views.hasOwnProperty(view) view = 'summary' viewArg = '' @redirect('#summary') if fromConstructor @state.view = view @state.viewArg = viewArg else @setState { view: view, viewArg: viewArg } componentDidMount: -> # Calculate size. TODO: Detect resize and fix containerDom = document.getElementById("appcontainer") console.log "#{containerDom.clientWidth}x#{containerDom.clientHeight}" if (@state.width != containerDom.clientWidth) || (@state.height != containerDom.clientHeight) setTimeout => @setState({ width: containerDom.clientWidth, height: containerDom.clientHeight }) , 0 redirect: (newHash) -> window.location.hash = newHash return toggleNav: -> @setState { navOpen: !@state.navOpen } render: -> if (@state.width == 0) or (@state.height == 0) return [] cie = document.getElementById("cie") elements = [] # Left navigation panel navMenuItems = [ el MenuItem, { key: "menu.title" primaryText: "Available Reports" disabled: true } el MenuItem, { key: "menu.summary" primaryText: "Summary" leftIcon: tags.icon 'event_note' onClick: (e) => e.preventDefault() @redirect('#summary') @setState { navOpen: false } } el MenuItem, { key: "menu.pixels" primaryText: "Pixels" leftIcon: tags.icon 'event_note' onClick: (e) => e.preventDefault() @redirect('#pixels') @setState { navOpen: false } } el MenuItem, { key: "menu.srgb" primaryText: "sRGB Highlight (#{COLORIST_DATA.srgb.highlightLuminance})" leftIcon: tags.icon 'event_note' onClick: (e) => e.preventDefault() @redirect('#srgb') @setState { navOpen: false } } ] elements.push el Drawer, { key: 'leftnav' docked: false open: @state.navOpen disableSwipeToOpen: true onRequestChange: (open) => @setState { navOpen: open } }, navMenuItems # Main view if @state.view != null elements.push el @views[@state.view], { name: @state.view key: @state.view width: @state.width height: @state.height app: this } return elements module.exports = App
[ { "context": "DISQUS_API_KEY = 'qibvGX1OhK1EDIGCsc0QMLJ0sJHSIKVLLyCnwE3RZPKkoQ7Dj0Mm1oUS8mRjLHfq'\nDISQUS_API_URL = 'https://disqus.com/api/3.0/thr", "end": 82, "score": 0.9997516870498657, "start": 18, "tag": "KEY", "value": "qibvGX1OhK1EDIGCsc0QMLJ0sJHSIKVLLyCnwE3RZPKkoQ7Dj0Mm1oUS8mRjLHfq"...
app/assets/javascripts/application/comments.js.coffee
nembrotorg/nembrot-api
4
DISQUS_API_KEY = 'qibvGX1OhK1EDIGCsc0QMLJ0sJHSIKVLLyCnwE3RZPKkoQ7Dj0Mm1oUS8mRjLHfq' DISQUS_API_URL = 'https://disqus.com/api/3.0/threads/set.jsonp' load_disqus_comments_count = () -> page_controller = $('html').data('controller') page_action = $('html').data('action') if (page_controller == 'notes' && page_action == 'show') || page_controller == 'features' $('.page').addClass('deep-link') $.getJSON DISQUS_API_URL + "?api_key=" + DISQUS_API_KEY + "&forum=" + window.Nembrot.DISQUS_SHORT_NAME + "&thread=" + encodeURIComponent(location.href), (data) -> count = _normalize_count(data.response.first) $('#tools a[href$="#comments"]').text(count) else $('.page').removeClass('deep-link') $('#tools a[href$="#comments"]').text('') load_comments_count = () -> page_controller = $('html').data('controller') page_action = $('html').data('action') if (page_controller == 'notes' && page_action == 'show') || page_controller == 'features' $('.page').addClass('deep-link') count = RegExp(/\d+/).exec($('#comments h2').text()) if count == null then count = '' $('#tools a[href$="#comments"]').text(count) else $('.page').removeClass('deep-link') $('#tools a[href$="#comments"]').text('') window.Nembrot.load_comments_count = load_comments_count # Document hooks ****************************************************************************************************** $ -> $(document).on 'submit', '#main section:not(#comments) form', (event) -> $.pjax.submit event, '[data-pjax-container]' # if $('#disqus_thread').length > 0 then load_disqus_comments_count(page_controller, page_action) # Check Settings first if $('#comments').length > 0 then load_comments_count() # if $('#disqus_thread').length > 0 # DISQUS.reset # reload: true # config: -> # @page.title = $('h1').text() # @language = $('html').attr('lang') # return $(document).on 'pjax:success', '#main', (data) -> # if $('#disqus_thread').length > 0 then load_disqus_comments_count(page_controller, page_action) # Check Settings first if $('#comments').length > 0 then load_comments_count()
207663
DISQUS_API_KEY = '<KEY>' DISQUS_API_URL = 'https://disqus.com/api/3.0/threads/set.jsonp' load_disqus_comments_count = () -> page_controller = $('html').data('controller') page_action = $('html').data('action') if (page_controller == 'notes' && page_action == 'show') || page_controller == 'features' $('.page').addClass('deep-link') $.getJSON DISQUS_API_URL + "?api_key=" + DISQUS_API_KEY + "&forum=" + window.Nembrot.DISQUS_SHORT_NAME + "&thread=" + encodeURIComponent(location.href), (data) -> count = _normalize_count(data.response.first) $('#tools a[href$="#comments"]').text(count) else $('.page').removeClass('deep-link') $('#tools a[href$="#comments"]').text('') load_comments_count = () -> page_controller = $('html').data('controller') page_action = $('html').data('action') if (page_controller == 'notes' && page_action == 'show') || page_controller == 'features' $('.page').addClass('deep-link') count = RegExp(/\d+/).exec($('#comments h2').text()) if count == null then count = '' $('#tools a[href$="#comments"]').text(count) else $('.page').removeClass('deep-link') $('#tools a[href$="#comments"]').text('') window.Nembrot.load_comments_count = load_comments_count # Document hooks ****************************************************************************************************** $ -> $(document).on 'submit', '#main section:not(#comments) form', (event) -> $.pjax.submit event, '[data-pjax-container]' # if $('#disqus_thread').length > 0 then load_disqus_comments_count(page_controller, page_action) # Check Settings first if $('#comments').length > 0 then load_comments_count() # if $('#disqus_thread').length > 0 # DISQUS.reset # reload: true # config: -> # @page.title = $('h1').text() # @language = $('html').attr('lang') # return $(document).on 'pjax:success', '#main', (data) -> # if $('#disqus_thread').length > 0 then load_disqus_comments_count(page_controller, page_action) # Check Settings first if $('#comments').length > 0 then load_comments_count()
true
DISQUS_API_KEY = 'PI:KEY:<KEY>END_PI' DISQUS_API_URL = 'https://disqus.com/api/3.0/threads/set.jsonp' load_disqus_comments_count = () -> page_controller = $('html').data('controller') page_action = $('html').data('action') if (page_controller == 'notes' && page_action == 'show') || page_controller == 'features' $('.page').addClass('deep-link') $.getJSON DISQUS_API_URL + "?api_key=" + DISQUS_API_KEY + "&forum=" + window.Nembrot.DISQUS_SHORT_NAME + "&thread=" + encodeURIComponent(location.href), (data) -> count = _normalize_count(data.response.first) $('#tools a[href$="#comments"]').text(count) else $('.page').removeClass('deep-link') $('#tools a[href$="#comments"]').text('') load_comments_count = () -> page_controller = $('html').data('controller') page_action = $('html').data('action') if (page_controller == 'notes' && page_action == 'show') || page_controller == 'features' $('.page').addClass('deep-link') count = RegExp(/\d+/).exec($('#comments h2').text()) if count == null then count = '' $('#tools a[href$="#comments"]').text(count) else $('.page').removeClass('deep-link') $('#tools a[href$="#comments"]').text('') window.Nembrot.load_comments_count = load_comments_count # Document hooks ****************************************************************************************************** $ -> $(document).on 'submit', '#main section:not(#comments) form', (event) -> $.pjax.submit event, '[data-pjax-container]' # if $('#disqus_thread').length > 0 then load_disqus_comments_count(page_controller, page_action) # Check Settings first if $('#comments').length > 0 then load_comments_count() # if $('#disqus_thread').length > 0 # DISQUS.reset # reload: true # config: -> # @page.title = $('h1').text() # @language = $('html').attr('lang') # return $(document).on 'pjax:success', '#main', (data) -> # if $('#disqus_thread').length > 0 then load_disqus_comments_count(page_controller, page_action) # Check Settings first if $('#comments').length > 0 then load_comments_count()
[ { "context": " id: 'id'\n pass: 'pass'\n\n registry:\n ", "end": 373, "score": 0.9993909597396851, "start": 369, "tag": "PASSWORD", "value": "pass" } ]
modules/http/lib/sessions/Sessions.coffee
nero-networks/floyd
0
events = require 'events' module.exports = ## ## ## class SessionsManager extends floyd.auth.AuthContext configure: (config)-> super new floyd.Config data: cookie: name: 'FSID' login: id: 'id' pass: 'pass' registry: type: 'http.sessions.Registry' interval: 60 timeout: 3600 sessions: type: 'http.sessions.Session' , config ## ## ## boot: (done)-> @_registry = new (floyd.tools.objects.resolve @data.registry.type) @data.registry, @ super done ## ## ## start: (done)-> super done exclude = @data.find 'no-session-routes', [] ## use the next HttpContext (idealy our parent) to connect req handler @delegate '_addMiddleware', (req, res, next)=> #console.log 'sessions init' if @data.disabled @logger.warning 'DEPRECATED: use data.cookie = false' return next() if @data.disabled || @data.cookie is false for expr in exclude return next() if req.url.match expr #console.log 'sessions getSID' @_getSID req, (err, SID)=> return next(err) if err #console.log 'sessions', SID @_load SID, (err, sess)=> #console.log 'sessions', sess, err return next(err) if err #console.log 'session', sess.public req.session = res.session = sess.public floyd.tools.objects.intercept res, 'end', (args..., end)=> end.apply res, args req.session = res.session = null ## next() ## ## ## _getSID: (req, fn)-> #console.log 'search cookie', @data.cookie.name, req.url, req.headers.cookie if SID = req.cookies.get @data.cookie.name fn null, SID else #console.log 'create SID' @_registry.createSID (err, SID)=> #console.log 'create cookie', SID req.cookies.set @data.cookie.name, SID fn null, SID ## ## ## login: (token, user, pass, _fn)-> fn = (err, user)=> if err setTimeout ()=> _fn err , 2500 else _fn null, user sid = token.substr 40 ## TODO - validate token sess = @_registry.get(sid) return fn(new floyd.error.Unauthorized 'login') if !sess || !user || !pass @_loadUser user, (err, data)=> return fn(err || new floyd.error.Unauthorized 'login') if err || !data if data.active is false || !floyd.tools.crypto.password.verify pass, data[@data.login.pass] @logger.warning 'access denied for %s@%s', user, sid fn new floyd.error.Unauthorized 'login' else data.lastlogin = +new Date() @_checkPasswordHash user, pass, data, (err, data)=> return fn(err) if err @parent.children.users.set (data.id||user), data, (err)=> data = floyd.tools.objects.clone data, login: user delete data[@data.login.pass] sess.public.user = data ## fn null, data ## ## ## _loadUser: (id, fn)-> if @data.login.id is 'id' @parent.children.users.get id, fn else query = {} query[@data.login.id] = id @parent.children.users.find query, limit: 1 , null, (err, items)=> fn err, items?[0] ## ## ## _checkPasswordHash: (user, pass, data, fn)-> cfg = floyd.tools.objects.extend floyd.config.crypto.password, @data.password parts = data[@data.login.pass].split '-' if parts.length is 1 \ ## check for old-style password hash or cfg.hasher isnt parts[1] \ ## check for new hash config or cfg.keySize isnt (parseInt parts[2]) \ or cfg.iterations isnt (parseInt parts[3]) data[@data.login.pass] = floyd.tools.crypto.password.create pass @logger.warning 'replacing password hash', data[@data.login.pass] ## fn null, data ## ## ## logout: (token, fn)-> sid = token.substr 40 ## TODO - validate token #console.log 'logout %s@%s', user, sid if (sess = @_registry.get(sid)) delete sess.public.user fn() ## ## ## authorize: (token, fn)-> if token && (sess = @_registry?.get (sid = token.substr 40)) #console.log 'found session', sess, sess.public.user?.login ## initialize destroy hook on the fly sess.destroyHook = ()=> fn new Error 'session destroyed' sess.on 'destroy', sess.destroyHook ## authorize loggedin session if user = sess.public.user?.login @_loadUser user, (err, data)=> return fn(err) if err data = floyd.tools.objects.clone data, login: user delete data[@data.login.pass] fn null, sess.public.user = data ## authorize anonymous session else fn() else super token, fn ## unauthorize: (token)-> if token && (sess = @_registry?.get (sid = token.substr 40)) && typeof sess.destroyHook is 'function' sess.off 'destroy', sess.destroyHook ## ## ## authenticate: (identity, fn)-> @logger.finer 'session authenticate identity %s', identity.id super identity, (err)=> return fn() if !err ## successfully authenticated identity.token (err, token)=> if err || !token @logger.warning 'session authenticate NO TOKEN', identity.id return fn(err || new Error 'session authenticate NO TOKEN') sid = token.substr 40 @logger.fine 'session authenticate session %s', sid @_load sid, (err, sess)=> return fn(err) if err @logger.finer 'session authenticate hash %s', token.substr 0, 39 if token is sess.token @logger.fine 'session authenticate SUCCESS', identity.id fn() else @logger.debug 'session authenticate FAILURE', identity.id fn new Error 'session authenticate FAILURE' ## ## ## _load: (sid, fn)-> #console.log 'load session', sid ## search and create if !(sess = @_registry.get sid) @_registry.add sess = new (floyd.tools.objects.resolve @data.registry.sessions.type) sid, @data.registry.sessions sess.touch() ## deliver fn null, sess ## ## ## createSID: (fn)-> @logger.warning 'pubic createSID is deprecated and will be removed in future' @_registry.createSID fn
3816
events = require 'events' module.exports = ## ## ## class SessionsManager extends floyd.auth.AuthContext configure: (config)-> super new floyd.Config data: cookie: name: 'FSID' login: id: 'id' pass: '<PASSWORD>' registry: type: 'http.sessions.Registry' interval: 60 timeout: 3600 sessions: type: 'http.sessions.Session' , config ## ## ## boot: (done)-> @_registry = new (floyd.tools.objects.resolve @data.registry.type) @data.registry, @ super done ## ## ## start: (done)-> super done exclude = @data.find 'no-session-routes', [] ## use the next HttpContext (idealy our parent) to connect req handler @delegate '_addMiddleware', (req, res, next)=> #console.log 'sessions init' if @data.disabled @logger.warning 'DEPRECATED: use data.cookie = false' return next() if @data.disabled || @data.cookie is false for expr in exclude return next() if req.url.match expr #console.log 'sessions getSID' @_getSID req, (err, SID)=> return next(err) if err #console.log 'sessions', SID @_load SID, (err, sess)=> #console.log 'sessions', sess, err return next(err) if err #console.log 'session', sess.public req.session = res.session = sess.public floyd.tools.objects.intercept res, 'end', (args..., end)=> end.apply res, args req.session = res.session = null ## next() ## ## ## _getSID: (req, fn)-> #console.log 'search cookie', @data.cookie.name, req.url, req.headers.cookie if SID = req.cookies.get @data.cookie.name fn null, SID else #console.log 'create SID' @_registry.createSID (err, SID)=> #console.log 'create cookie', SID req.cookies.set @data.cookie.name, SID fn null, SID ## ## ## login: (token, user, pass, _fn)-> fn = (err, user)=> if err setTimeout ()=> _fn err , 2500 else _fn null, user sid = token.substr 40 ## TODO - validate token sess = @_registry.get(sid) return fn(new floyd.error.Unauthorized 'login') if !sess || !user || !pass @_loadUser user, (err, data)=> return fn(err || new floyd.error.Unauthorized 'login') if err || !data if data.active is false || !floyd.tools.crypto.password.verify pass, data[@data.login.pass] @logger.warning 'access denied for %s@%s', user, sid fn new floyd.error.Unauthorized 'login' else data.lastlogin = +new Date() @_checkPasswordHash user, pass, data, (err, data)=> return fn(err) if err @parent.children.users.set (data.id||user), data, (err)=> data = floyd.tools.objects.clone data, login: user delete data[@data.login.pass] sess.public.user = data ## fn null, data ## ## ## _loadUser: (id, fn)-> if @data.login.id is 'id' @parent.children.users.get id, fn else query = {} query[@data.login.id] = id @parent.children.users.find query, limit: 1 , null, (err, items)=> fn err, items?[0] ## ## ## _checkPasswordHash: (user, pass, data, fn)-> cfg = floyd.tools.objects.extend floyd.config.crypto.password, @data.password parts = data[@data.login.pass].split '-' if parts.length is 1 \ ## check for old-style password hash or cfg.hasher isnt parts[1] \ ## check for new hash config or cfg.keySize isnt (parseInt parts[2]) \ or cfg.iterations isnt (parseInt parts[3]) data[@data.login.pass] = floyd.tools.crypto.password.create pass @logger.warning 'replacing password hash', data[@data.login.pass] ## fn null, data ## ## ## logout: (token, fn)-> sid = token.substr 40 ## TODO - validate token #console.log 'logout %s@%s', user, sid if (sess = @_registry.get(sid)) delete sess.public.user fn() ## ## ## authorize: (token, fn)-> if token && (sess = @_registry?.get (sid = token.substr 40)) #console.log 'found session', sess, sess.public.user?.login ## initialize destroy hook on the fly sess.destroyHook = ()=> fn new Error 'session destroyed' sess.on 'destroy', sess.destroyHook ## authorize loggedin session if user = sess.public.user?.login @_loadUser user, (err, data)=> return fn(err) if err data = floyd.tools.objects.clone data, login: user delete data[@data.login.pass] fn null, sess.public.user = data ## authorize anonymous session else fn() else super token, fn ## unauthorize: (token)-> if token && (sess = @_registry?.get (sid = token.substr 40)) && typeof sess.destroyHook is 'function' sess.off 'destroy', sess.destroyHook ## ## ## authenticate: (identity, fn)-> @logger.finer 'session authenticate identity %s', identity.id super identity, (err)=> return fn() if !err ## successfully authenticated identity.token (err, token)=> if err || !token @logger.warning 'session authenticate NO TOKEN', identity.id return fn(err || new Error 'session authenticate NO TOKEN') sid = token.substr 40 @logger.fine 'session authenticate session %s', sid @_load sid, (err, sess)=> return fn(err) if err @logger.finer 'session authenticate hash %s', token.substr 0, 39 if token is sess.token @logger.fine 'session authenticate SUCCESS', identity.id fn() else @logger.debug 'session authenticate FAILURE', identity.id fn new Error 'session authenticate FAILURE' ## ## ## _load: (sid, fn)-> #console.log 'load session', sid ## search and create if !(sess = @_registry.get sid) @_registry.add sess = new (floyd.tools.objects.resolve @data.registry.sessions.type) sid, @data.registry.sessions sess.touch() ## deliver fn null, sess ## ## ## createSID: (fn)-> @logger.warning 'pubic createSID is deprecated and will be removed in future' @_registry.createSID fn
true
events = require 'events' module.exports = ## ## ## class SessionsManager extends floyd.auth.AuthContext configure: (config)-> super new floyd.Config data: cookie: name: 'FSID' login: id: 'id' pass: 'PI:PASSWORD:<PASSWORD>END_PI' registry: type: 'http.sessions.Registry' interval: 60 timeout: 3600 sessions: type: 'http.sessions.Session' , config ## ## ## boot: (done)-> @_registry = new (floyd.tools.objects.resolve @data.registry.type) @data.registry, @ super done ## ## ## start: (done)-> super done exclude = @data.find 'no-session-routes', [] ## use the next HttpContext (idealy our parent) to connect req handler @delegate '_addMiddleware', (req, res, next)=> #console.log 'sessions init' if @data.disabled @logger.warning 'DEPRECATED: use data.cookie = false' return next() if @data.disabled || @data.cookie is false for expr in exclude return next() if req.url.match expr #console.log 'sessions getSID' @_getSID req, (err, SID)=> return next(err) if err #console.log 'sessions', SID @_load SID, (err, sess)=> #console.log 'sessions', sess, err return next(err) if err #console.log 'session', sess.public req.session = res.session = sess.public floyd.tools.objects.intercept res, 'end', (args..., end)=> end.apply res, args req.session = res.session = null ## next() ## ## ## _getSID: (req, fn)-> #console.log 'search cookie', @data.cookie.name, req.url, req.headers.cookie if SID = req.cookies.get @data.cookie.name fn null, SID else #console.log 'create SID' @_registry.createSID (err, SID)=> #console.log 'create cookie', SID req.cookies.set @data.cookie.name, SID fn null, SID ## ## ## login: (token, user, pass, _fn)-> fn = (err, user)=> if err setTimeout ()=> _fn err , 2500 else _fn null, user sid = token.substr 40 ## TODO - validate token sess = @_registry.get(sid) return fn(new floyd.error.Unauthorized 'login') if !sess || !user || !pass @_loadUser user, (err, data)=> return fn(err || new floyd.error.Unauthorized 'login') if err || !data if data.active is false || !floyd.tools.crypto.password.verify pass, data[@data.login.pass] @logger.warning 'access denied for %s@%s', user, sid fn new floyd.error.Unauthorized 'login' else data.lastlogin = +new Date() @_checkPasswordHash user, pass, data, (err, data)=> return fn(err) if err @parent.children.users.set (data.id||user), data, (err)=> data = floyd.tools.objects.clone data, login: user delete data[@data.login.pass] sess.public.user = data ## fn null, data ## ## ## _loadUser: (id, fn)-> if @data.login.id is 'id' @parent.children.users.get id, fn else query = {} query[@data.login.id] = id @parent.children.users.find query, limit: 1 , null, (err, items)=> fn err, items?[0] ## ## ## _checkPasswordHash: (user, pass, data, fn)-> cfg = floyd.tools.objects.extend floyd.config.crypto.password, @data.password parts = data[@data.login.pass].split '-' if parts.length is 1 \ ## check for old-style password hash or cfg.hasher isnt parts[1] \ ## check for new hash config or cfg.keySize isnt (parseInt parts[2]) \ or cfg.iterations isnt (parseInt parts[3]) data[@data.login.pass] = floyd.tools.crypto.password.create pass @logger.warning 'replacing password hash', data[@data.login.pass] ## fn null, data ## ## ## logout: (token, fn)-> sid = token.substr 40 ## TODO - validate token #console.log 'logout %s@%s', user, sid if (sess = @_registry.get(sid)) delete sess.public.user fn() ## ## ## authorize: (token, fn)-> if token && (sess = @_registry?.get (sid = token.substr 40)) #console.log 'found session', sess, sess.public.user?.login ## initialize destroy hook on the fly sess.destroyHook = ()=> fn new Error 'session destroyed' sess.on 'destroy', sess.destroyHook ## authorize loggedin session if user = sess.public.user?.login @_loadUser user, (err, data)=> return fn(err) if err data = floyd.tools.objects.clone data, login: user delete data[@data.login.pass] fn null, sess.public.user = data ## authorize anonymous session else fn() else super token, fn ## unauthorize: (token)-> if token && (sess = @_registry?.get (sid = token.substr 40)) && typeof sess.destroyHook is 'function' sess.off 'destroy', sess.destroyHook ## ## ## authenticate: (identity, fn)-> @logger.finer 'session authenticate identity %s', identity.id super identity, (err)=> return fn() if !err ## successfully authenticated identity.token (err, token)=> if err || !token @logger.warning 'session authenticate NO TOKEN', identity.id return fn(err || new Error 'session authenticate NO TOKEN') sid = token.substr 40 @logger.fine 'session authenticate session %s', sid @_load sid, (err, sess)=> return fn(err) if err @logger.finer 'session authenticate hash %s', token.substr 0, 39 if token is sess.token @logger.fine 'session authenticate SUCCESS', identity.id fn() else @logger.debug 'session authenticate FAILURE', identity.id fn new Error 'session authenticate FAILURE' ## ## ## _load: (sid, fn)-> #console.log 'load session', sid ## search and create if !(sess = @_registry.get sid) @_registry.add sess = new (floyd.tools.objects.resolve @data.registry.sessions.type) sid, @data.registry.sessions sess.touch() ## deliver fn null, sess ## ## ## createSID: (fn)-> @logger.warning 'pubic createSID is deprecated and will be removed in future' @_registry.createSID fn
[ { "context": " Prelude.wait 5, -> name\n objects = [makeObject('doug'), makeObject('rover'), makeObject('spot')]\n Pre", "end": 909, "score": 0.7845911979675293, "start": 905, "tag": "NAME", "value": "doug" }, { "context": "name\n objects = [makeObject('doug'), makeObject('rover')...
tests/unit/utils/prelude-test.coffee
foxnewsnetwork/table-grid-2d
2
`import Prelude from 'table-grid-2d/utils/prelude'` `import { module, test } from 'qunit'` module 'Prelude' test 'it loads', (assert) -> assert.ok Prelude, assert.ok Prelude.zip assert.ok Prelude.promiseFilterBy assert.ok Prelude.promiseLift assert.ok Prelude.asyncMapBy assert.ok Prelude.asyncMap assert.ok Prelude.reduceBuild assert.ok Prelude.lll test 'zip normal', (assert) -> actual = Prelude.zip [1,2,3], ['a','b','c'] expected = Ember.A [ [1, 'a'], [2, 'b'], [3, 'c'] ] assert.deepEqual actual, expected test 'zip uneven', (assert) -> actual = Prelude.zip [1,2,3], ['a','b','c','d'] expected = Ember.A [ [1, 'a'], [2, 'b'], [3, 'c'], [undefined, 'd'] ] assert.deepEqual actual, expected test 'promiseFilterBy', (assert) -> makeObject = (name) -> Ember.Object.create name: Prelude.wait 5, -> name objects = [makeObject('doug'), makeObject('rover'), makeObject('spot')] Prelude.promiseFilterBy objects, "name", "rover" .then (objects) -> assert.ok objects, "filter should return an array" assert.equal objects.length, 1, "the array should have correct length" assert.ok objects[0], "the array should have contents" objects[0].get("name").then (name) -> assert.equal name, "rover"
210072
`import Prelude from 'table-grid-2d/utils/prelude'` `import { module, test } from 'qunit'` module 'Prelude' test 'it loads', (assert) -> assert.ok Prelude, assert.ok Prelude.zip assert.ok Prelude.promiseFilterBy assert.ok Prelude.promiseLift assert.ok Prelude.asyncMapBy assert.ok Prelude.asyncMap assert.ok Prelude.reduceBuild assert.ok Prelude.lll test 'zip normal', (assert) -> actual = Prelude.zip [1,2,3], ['a','b','c'] expected = Ember.A [ [1, 'a'], [2, 'b'], [3, 'c'] ] assert.deepEqual actual, expected test 'zip uneven', (assert) -> actual = Prelude.zip [1,2,3], ['a','b','c','d'] expected = Ember.A [ [1, 'a'], [2, 'b'], [3, 'c'], [undefined, 'd'] ] assert.deepEqual actual, expected test 'promiseFilterBy', (assert) -> makeObject = (name) -> Ember.Object.create name: Prelude.wait 5, -> name objects = [makeObject('<NAME>'), makeObject('<NAME>'), makeObject('spot')] Prelude.promiseFilterBy objects, "name", "<NAME>" .then (objects) -> assert.ok objects, "filter should return an array" assert.equal objects.length, 1, "the array should have correct length" assert.ok objects[0], "the array should have contents" objects[0].get("name").then (name) -> assert.equal name, "<NAME>"
true
`import Prelude from 'table-grid-2d/utils/prelude'` `import { module, test } from 'qunit'` module 'Prelude' test 'it loads', (assert) -> assert.ok Prelude, assert.ok Prelude.zip assert.ok Prelude.promiseFilterBy assert.ok Prelude.promiseLift assert.ok Prelude.asyncMapBy assert.ok Prelude.asyncMap assert.ok Prelude.reduceBuild assert.ok Prelude.lll test 'zip normal', (assert) -> actual = Prelude.zip [1,2,3], ['a','b','c'] expected = Ember.A [ [1, 'a'], [2, 'b'], [3, 'c'] ] assert.deepEqual actual, expected test 'zip uneven', (assert) -> actual = Prelude.zip [1,2,3], ['a','b','c','d'] expected = Ember.A [ [1, 'a'], [2, 'b'], [3, 'c'], [undefined, 'd'] ] assert.deepEqual actual, expected test 'promiseFilterBy', (assert) -> makeObject = (name) -> Ember.Object.create name: Prelude.wait 5, -> name objects = [makeObject('PI:NAME:<NAME>END_PI'), makeObject('PI:NAME:<NAME>END_PI'), makeObject('spot')] Prelude.promiseFilterBy objects, "name", "PI:NAME:<NAME>END_PI" .then (objects) -> assert.ok objects, "filter should return an array" assert.equal objects.length, 1, "the array should have correct length" assert.ok objects[0], "the array should have contents" objects[0].get("name").then (name) -> assert.equal name, "PI:NAME:<NAME>END_PI"
[ { "context": "ew Klass\n\n klass.should.have.property 'name', 'mittens'\n\n it 'should use overridden constructor.', ->\n ", "end": 920, "score": 0.9146714210510254, "start": 913, "tag": "NAME", "value": "mittens" } ]
spec/specs/helpers/inherits.coffee
rstone770/inheritor
0
require('chai').should() fixture = require "#{process.cwd()}/spec/fixtures/helpers/klass" inherits = require "#{process.cwd()}/src/helpers/inherits" describe 'helpers/inherits', -> bare = null withStatics = null withPrototype = null beforeEach () -> bare = fixture 'bare' withStatics = fixture 'static' withPrototype = fixture 'prototype' it 'should always return a constructor.', -> inherits(bare).should.be.a.function inherits(bare, {}).should.be.a.function inherits(bare, {}, {}).should.be.a.function it 'should be instance of base.', -> Klass = inherits withPrototype, method: () -> klass = new Klass klass.should.be.instanceOf withPrototype it 'should use the parent constructor if one is not overridden.', -> Klass = inherits fixture 'constructor' klass = new Klass klass.should.have.property 'name', 'mittens' it 'should use overridden constructor.', -> Klass = inherits bare, constructor: (@age = 30) -> klass = new Klass klass.should.have.property 'age', 30 it 'should copy everything from parent prototype.', -> Klass = inherits withPrototype klass = new Klass klass.should.have.property 'baseMethod', withPrototype::baseMethod klass.should.have.property 'baseProperty', withPrototype::baseProperty it 'should extend from provided prototype.', -> Klass = inherits withPrototype, anotherMethod: () -> baseProperty: 'overridden' klass = new Klass klass.should.have.property 'baseMethod', withPrototype::baseMethod klass.should.have.property 'anotherMethod', Klass::anotherMethod klass.should.have.property 'baseProperty', Klass::baseProperty it 'should copy static properties from parent.', -> Klass = inherits withStatics Klass.should.have.property 'staticMethod', withStatics.staticMethod Klass.should.have.property 'staticProperty', withStatics.staticProperty it 'should extend statics from provided statics.', -> Klass = inherits withStatics, {}, anotherMethod: () -> staticProperty: 'overridden' Klass.should.have.property 'staticMethod', withStatics.staticMethod Klass.should.have.property 'anotherMethod', Klass.anotherMethod Klass.should.have.property 'staticProperty', Klass.staticProperty it 'should expose parent prototype as @__super.', -> Klass = inherits withPrototype Klass.should.have.property '__super', withPrototype::
81292
require('chai').should() fixture = require "#{process.cwd()}/spec/fixtures/helpers/klass" inherits = require "#{process.cwd()}/src/helpers/inherits" describe 'helpers/inherits', -> bare = null withStatics = null withPrototype = null beforeEach () -> bare = fixture 'bare' withStatics = fixture 'static' withPrototype = fixture 'prototype' it 'should always return a constructor.', -> inherits(bare).should.be.a.function inherits(bare, {}).should.be.a.function inherits(bare, {}, {}).should.be.a.function it 'should be instance of base.', -> Klass = inherits withPrototype, method: () -> klass = new Klass klass.should.be.instanceOf withPrototype it 'should use the parent constructor if one is not overridden.', -> Klass = inherits fixture 'constructor' klass = new Klass klass.should.have.property 'name', '<NAME>' it 'should use overridden constructor.', -> Klass = inherits bare, constructor: (@age = 30) -> klass = new Klass klass.should.have.property 'age', 30 it 'should copy everything from parent prototype.', -> Klass = inherits withPrototype klass = new Klass klass.should.have.property 'baseMethod', withPrototype::baseMethod klass.should.have.property 'baseProperty', withPrototype::baseProperty it 'should extend from provided prototype.', -> Klass = inherits withPrototype, anotherMethod: () -> baseProperty: 'overridden' klass = new Klass klass.should.have.property 'baseMethod', withPrototype::baseMethod klass.should.have.property 'anotherMethod', Klass::anotherMethod klass.should.have.property 'baseProperty', Klass::baseProperty it 'should copy static properties from parent.', -> Klass = inherits withStatics Klass.should.have.property 'staticMethod', withStatics.staticMethod Klass.should.have.property 'staticProperty', withStatics.staticProperty it 'should extend statics from provided statics.', -> Klass = inherits withStatics, {}, anotherMethod: () -> staticProperty: 'overridden' Klass.should.have.property 'staticMethod', withStatics.staticMethod Klass.should.have.property 'anotherMethod', Klass.anotherMethod Klass.should.have.property 'staticProperty', Klass.staticProperty it 'should expose parent prototype as @__super.', -> Klass = inherits withPrototype Klass.should.have.property '__super', withPrototype::
true
require('chai').should() fixture = require "#{process.cwd()}/spec/fixtures/helpers/klass" inherits = require "#{process.cwd()}/src/helpers/inherits" describe 'helpers/inherits', -> bare = null withStatics = null withPrototype = null beforeEach () -> bare = fixture 'bare' withStatics = fixture 'static' withPrototype = fixture 'prototype' it 'should always return a constructor.', -> inherits(bare).should.be.a.function inherits(bare, {}).should.be.a.function inherits(bare, {}, {}).should.be.a.function it 'should be instance of base.', -> Klass = inherits withPrototype, method: () -> klass = new Klass klass.should.be.instanceOf withPrototype it 'should use the parent constructor if one is not overridden.', -> Klass = inherits fixture 'constructor' klass = new Klass klass.should.have.property 'name', 'PI:NAME:<NAME>END_PI' it 'should use overridden constructor.', -> Klass = inherits bare, constructor: (@age = 30) -> klass = new Klass klass.should.have.property 'age', 30 it 'should copy everything from parent prototype.', -> Klass = inherits withPrototype klass = new Klass klass.should.have.property 'baseMethod', withPrototype::baseMethod klass.should.have.property 'baseProperty', withPrototype::baseProperty it 'should extend from provided prototype.', -> Klass = inherits withPrototype, anotherMethod: () -> baseProperty: 'overridden' klass = new Klass klass.should.have.property 'baseMethod', withPrototype::baseMethod klass.should.have.property 'anotherMethod', Klass::anotherMethod klass.should.have.property 'baseProperty', Klass::baseProperty it 'should copy static properties from parent.', -> Klass = inherits withStatics Klass.should.have.property 'staticMethod', withStatics.staticMethod Klass.should.have.property 'staticProperty', withStatics.staticProperty it 'should extend statics from provided statics.', -> Klass = inherits withStatics, {}, anotherMethod: () -> staticProperty: 'overridden' Klass.should.have.property 'staticMethod', withStatics.staticMethod Klass.should.have.property 'anotherMethod', Klass.anotherMethod Klass.should.have.property 'staticProperty', Klass.staticProperty it 'should expose parent prototype as @__super.', -> Klass = inherits withPrototype Klass.should.have.property '__super', withPrototype::
[ { "context": "tch.\n \"\"\", {utf8: true})\n\n bot.reply(\"My name is Aiden\", \"Nice to meet you, aiden.\")\n bot.reply(\"My nam", "end": 1649, "score": 0.9978874325752258, "start": 1644, "tag": "NAME", "value": "Aiden" }, { "context": "Nice to meet you, aiden.\")\n bot.reply(\"...
test/test-unicode.coffee
rundexter/rivescript-js
1
TestCase = require("./test-base") ################################################################################ # Unicode Tests ################################################################################ exports.test_unicode = (test) -> bot = new TestCase(test, """ ! sub who's = who is + äh - What's the matter? + ブラッキー - エーフィ // Make sure %Previous continues working in UTF-8 mode. + knock knock - Who's there? + * % who is there - <sentence> who? + * % * who - Haha! <sentence>! // And with UTF-8. + tëll më ä pöëm - Thërë öncë wäs ä män nämëd Tïm + more % thërë öncë wäs ä män nämëd tïm - Whö nëvër qüïtë lëärnëd höw tö swïm + more % whö nëvër qüïtë lëärnëd höw tö swïm - Hë fëll öff ä döck, änd sänk lïkë ä röck + more % hë fëll öff ä döck änd sänk lïkë ä röck - Änd thät wäs thë ënd öf hïm. """, {"utf8": true}) bot.reply("äh", "What's the matter?") bot.reply("ブラッキー", "エーフィ") bot.reply("knock knock", "Who's there?") bot.reply("Orange", "Orange who?") bot.reply("banana", "Haha! Banana!") bot.reply("tëll më ä pöëm", "Thërë öncë wäs ä män nämëd Tïm") bot.reply("more", "Whö nëvër qüïtë lëärnëd höw tö swïm") bot.reply("more", "Hë fëll öff ä döck, änd sänk lïkë ä röck") bot.reply("more", "Änd thät wäs thë ënd öf hïm.") test.done() exports.test_wildcards = (test) -> bot = new TestCase(test, """ + my name is _ - Nice to meet you, <star>. + i am # years old - A lot of people are <star> years old. + * - No match. """, {utf8: true}) bot.reply("My name is Aiden", "Nice to meet you, aiden.") bot.reply("My name is Bảo", "Nice to meet you, bảo.") bot.reply("My name is 5", "No match.") bot.reply("I am five years old", "No match.") bot.reply("I am 5 years old", "A lot of people are 5 years old.") test.done() exports.test_punctuation = (test) -> bot = new TestCase(test, """ + hello bot - Hello human! """, {"utf8": true}) bot.reply("Hello bot", "Hello human!") bot.reply("Hello, bot!", "Hello human!") bot.reply("Hello: Bot", "Hello human!") bot.reply("Hello... bot?", "Hello human!") bot.rs.unicodePunctuation = new RegExp(/xxx/g) bot.reply("Hello bot", "Hello human!") bot.reply("Hello, bot!", "ERR: No Reply Matched") test.done() exports.test_alternatives_and_optionals = (test) -> bot = new TestCase(test, """ + [*] to your [*] - Wild. + [*] 아침 [*] - UTF8 Wild. """, {"utf8": true}) bot.reply("foo to your bar", "Wild.") bot.reply("foo to your", "Wild.") bot.reply("to your bar", "Wild.") bot.reply("to your", "Wild.") bot.reply("아침", "UTF8 Wild.") bot.reply("아침 선생님.", "UTF8 Wild.") bot.reply("좋은 아침", "UTF8 Wild.") test.done()
120980
TestCase = require("./test-base") ################################################################################ # Unicode Tests ################################################################################ exports.test_unicode = (test) -> bot = new TestCase(test, """ ! sub who's = who is + äh - What's the matter? + ブラッキー - エーフィ // Make sure %Previous continues working in UTF-8 mode. + knock knock - Who's there? + * % who is there - <sentence> who? + * % * who - Haha! <sentence>! // And with UTF-8. + tëll më ä pöëm - Thërë öncë wäs ä män nämëd Tïm + more % thërë öncë wäs ä män nämëd tïm - Whö nëvër qüïtë lëärnëd höw tö swïm + more % whö nëvër qüïtë lëärnëd höw tö swïm - Hë fëll öff ä döck, änd sänk lïkë ä röck + more % hë fëll öff ä döck änd sänk lïkë ä röck - Änd thät wäs thë ënd öf hïm. """, {"utf8": true}) bot.reply("äh", "What's the matter?") bot.reply("ブラッキー", "エーフィ") bot.reply("knock knock", "Who's there?") bot.reply("Orange", "Orange who?") bot.reply("banana", "Haha! Banana!") bot.reply("tëll më ä pöëm", "Thërë öncë wäs ä män nämëd Tïm") bot.reply("more", "Whö nëvër qüïtë lëärnëd höw tö swïm") bot.reply("more", "Hë fëll öff ä döck, änd sänk lïkë ä röck") bot.reply("more", "Änd thät wäs thë ënd öf hïm.") test.done() exports.test_wildcards = (test) -> bot = new TestCase(test, """ + my name is _ - Nice to meet you, <star>. + i am # years old - A lot of people are <star> years old. + * - No match. """, {utf8: true}) bot.reply("My name is <NAME>", "Nice to meet you, aiden.") bot.reply("My name is <NAME>", "Nice to meet you, bảo.") bot.reply("My name is 5", "No match.") bot.reply("I am five years old", "No match.") bot.reply("I am 5 years old", "A lot of people are 5 years old.") test.done() exports.test_punctuation = (test) -> bot = new TestCase(test, """ + hello bot - Hello human! """, {"utf8": true}) bot.reply("Hello bot", "Hello human!") bot.reply("Hello, bot!", "Hello human!") bot.reply("Hello: Bot", "Hello human!") bot.reply("Hello... bot?", "Hello human!") bot.rs.unicodePunctuation = new RegExp(/xxx/g) bot.reply("Hello bot", "Hello human!") bot.reply("Hello, bot!", "ERR: No Reply Matched") test.done() exports.test_alternatives_and_optionals = (test) -> bot = new TestCase(test, """ + [*] to your [*] - Wild. + [*] 아침 [*] - UTF8 Wild. """, {"utf8": true}) bot.reply("foo to your bar", "Wild.") bot.reply("foo to your", "Wild.") bot.reply("to your bar", "Wild.") bot.reply("to your", "Wild.") bot.reply("아침", "UTF8 Wild.") bot.reply("아침 선생님.", "UTF8 Wild.") bot.reply("좋은 아침", "UTF8 Wild.") test.done()
true
TestCase = require("./test-base") ################################################################################ # Unicode Tests ################################################################################ exports.test_unicode = (test) -> bot = new TestCase(test, """ ! sub who's = who is + äh - What's the matter? + ブラッキー - エーフィ // Make sure %Previous continues working in UTF-8 mode. + knock knock - Who's there? + * % who is there - <sentence> who? + * % * who - Haha! <sentence>! // And with UTF-8. + tëll më ä pöëm - Thërë öncë wäs ä män nämëd Tïm + more % thërë öncë wäs ä män nämëd tïm - Whö nëvër qüïtë lëärnëd höw tö swïm + more % whö nëvër qüïtë lëärnëd höw tö swïm - Hë fëll öff ä döck, änd sänk lïkë ä röck + more % hë fëll öff ä döck änd sänk lïkë ä röck - Änd thät wäs thë ënd öf hïm. """, {"utf8": true}) bot.reply("äh", "What's the matter?") bot.reply("ブラッキー", "エーフィ") bot.reply("knock knock", "Who's there?") bot.reply("Orange", "Orange who?") bot.reply("banana", "Haha! Banana!") bot.reply("tëll më ä pöëm", "Thërë öncë wäs ä män nämëd Tïm") bot.reply("more", "Whö nëvër qüïtë lëärnëd höw tö swïm") bot.reply("more", "Hë fëll öff ä döck, änd sänk lïkë ä röck") bot.reply("more", "Änd thät wäs thë ënd öf hïm.") test.done() exports.test_wildcards = (test) -> bot = new TestCase(test, """ + my name is _ - Nice to meet you, <star>. + i am # years old - A lot of people are <star> years old. + * - No match. """, {utf8: true}) bot.reply("My name is PI:NAME:<NAME>END_PI", "Nice to meet you, aiden.") bot.reply("My name is PI:NAME:<NAME>END_PI", "Nice to meet you, bảo.") bot.reply("My name is 5", "No match.") bot.reply("I am five years old", "No match.") bot.reply("I am 5 years old", "A lot of people are 5 years old.") test.done() exports.test_punctuation = (test) -> bot = new TestCase(test, """ + hello bot - Hello human! """, {"utf8": true}) bot.reply("Hello bot", "Hello human!") bot.reply("Hello, bot!", "Hello human!") bot.reply("Hello: Bot", "Hello human!") bot.reply("Hello... bot?", "Hello human!") bot.rs.unicodePunctuation = new RegExp(/xxx/g) bot.reply("Hello bot", "Hello human!") bot.reply("Hello, bot!", "ERR: No Reply Matched") test.done() exports.test_alternatives_and_optionals = (test) -> bot = new TestCase(test, """ + [*] to your [*] - Wild. + [*] 아침 [*] - UTF8 Wild. """, {"utf8": true}) bot.reply("foo to your bar", "Wild.") bot.reply("foo to your", "Wild.") bot.reply("to your bar", "Wild.") bot.reply("to your", "Wild.") bot.reply("아침", "UTF8 Wild.") bot.reply("아침 선생님.", "UTF8 Wild.") bot.reply("좋은 아침", "UTF8 Wild.") test.done()
[ { "context": "{pluginName}\"\n\n unless plugin\n key = \"suraido#{if sliders > 1 then '-' + ++index else ''}\"\n ", "end": 6090, "score": 0.9986075758934021, "start": 6081, "tag": "KEY", "value": "suraido#{" }, { "context": "plugin\n key = \"suraido#{if slider...
coffee/suraido.coffee
IcaliaLabs/furatto
133
(($, window, document) -> "use strict" #set the plugin name pluginName = 'suraido' defaults = speed: 500 delay: 3000 pause: false loop: false enableKeys: true enableDots: true enableArrows: true prev: '«' next: '»' fluid: true starting: false completed: false easing: 'swing' autoplay: false paginationClass: 'pagination' paginationItemClass: 'dot' arrowsClass: 'arrows' arrowClass: 'arrow' class Furatto.Suraido constructor: (@el, options) -> #jquery element wrapper @$el = $(@el) #merges options @options = $.extend {}, defaults, options #slider items wrapper @itemsWrapper = @$el.find('>ul') #max slider size @maxSize = width: @$el.outerWidth() | 0 height: @$el.outerHeight() | 0 #items definition weakSelf = @ @items = $(@itemsWrapper).find('>li').each (index) -> $this = $(@) width = $this.outerWidth() height = $this.outerHeight() weakSelf.maxSize.width = width if width > weakSelf.maxSize.width weakSelf.maxSize.height = height if height > weakSelf.maxSize.height #items on the wrapper @itemsLength = @items.length #current item position @currentItemIndex = 0 #fix for alpha on captions @items.find('.caption').css(width: "#{100 / @itemsLength}%") #set the main element @_setsMainElement() #Set relative widths @itemsWrapper.css( position: "relative" left: 0 width: "#{@itemsLength * 100}%" ) #sets the styling for each slider item @_setsItems() #autoslide @_enablesAutoPlay() if @options.autoplay #keypresses binding @_enableBindKeys() if @options.enableKeys @options.enableDots and @_createPagination() @options.enableArrows and @_createArrows() #fluid behavior for responsive layouts @_enablesFluidBehavior() if @options.fluid #chrome fix if window.chrome @items.css 'background-size', '100% 100%' if $.event.special['swipe'] or $.Event 'swipe' @$el.on 'swipeleft swiperight swipeLeft swipeRight', (e) => if e.type.toLowerCase() is 'swipeleft' then @next() else @prev() _setsItems: => @items.css float: 'left' width: "#{100 / @itemsLength}%" _setsMainElement: => @$el.css width: @maxSize.width height: @items.first().outerHeight() overflow: 'hidden' _enablesAutoPlay: => setTimeout(=> if @options.delay | 0 @play() if @options.pause @$el.on 'mouseover, mouseout', (event) => @stop() event.type is 'mouseout' && @play() , @options.autoPlayDelay | 0) _enablesFluidBehavior: => $(window).resize(=> @resize and clearTimeout(@resize) @resize = setTimeout(=> style = height: @items.eq(@currentItemIndex).outerHeight() + 30 width = @$el.outerWidth() @itemsWrapper.css style style['width'] = "#{Math.min(Math.round((width / @$el.parent().width()) * 100), 100)}%" @$el.css style , 50) ).resize() _enableBindKeys: => $(document).on 'keydown', (event) => switch event.which when 37 then @prev() when 39 then @next() when 27 || 32 then @stop() _createPagination: => html = "<ol class='#{@options.paginationClass}'>" $.each @items, (index) => html += "<li class='#{if index == @currentItemIndex then @options.paginationItemClass + ' active' else @options.paginationItemClass}'> #{++index}</li>" html += "</ol>" @_bindPagination(@options.paginationClass, @options.paginationItemClass, html) _createArrows: => html = "<div class=\"" html = html + @options.arrowsClass + "\">" + html + @options.arrowClass + " prev\">" + @options.prev + "</div>" + html + @options.arrowClass + " next\">" + @options.next + "</div></div>" @_bindPagination(@options.arrowsClass, @options.arrowClass, html) _bindPagination: (className, itemClassName, html) -> weakSelf = @ @$el.addClass("has-#{className}").append(html).find(".#{itemClassName}").click -> $this = $(@) if $this.hasClass(weakSelf.options.paginationItemClass) weakSelf.stop().to($this.index()) else if $this.hasClass('prev') then weakSelf.prev() else weakSelf.next() to: (index, callback) => if @t @stop() @play() target = @items.eq(index) $.isFunction(@options.starting) and !callback and @options.starting @$el, @items.eq(@currentItemIndex) if not (target.length || index < 0) and @options.loop is false return if index < 0 index = @items.length - 1 speed = if callback then 5 else @options.speed | 0 easing = @options.easing obj = height: target.outerHeight() + 30 if not @itemsWrapper.queue('fx').length @$el.find(".#{@options.paginationItemClass}").eq(index).addClass('active').siblings().removeClass('active') @$el.animate(obj, speed, easing) and @itemsWrapper.animate($.extend( left: "-#{index}00%", obj), speed, easing, (data) => @currentItemIndex = index $.isFunction(@options.complete) and !callback and @options.complete(@el, target) ) play: => @t = setInterval( => @to(@currentItemIndex + 1) , @options.delay | 0) stop: => @t = clearInterval(@t) @ next: => if @currentItemIndex == (@itemsLength - 1) @stop().to(0) else @stop().to(@currentItemIndex + 1) prev: => @stop().to(@currentItemIndex - 1) $.fn[pluginName] = (options) -> sliders = this.length [_, args...] = arguments @each (index) -> me = $(@) plugin = $.data @, "plugin_#{pluginName}" unless plugin key = "suraido#{if sliders > 1 then '-' + ++index else ''}" instance = new Furatto.Suraido(@, options) me.data(key, instance).data('key', key) else if plugin[_]? and $.type(plugin[_]) == 'function' plugin[_].apply plugin, args Furatto.Suraido.version = "1.0.0" $(document).ready -> $('[data-suraido]').each -> $(@).suraido() ) $, window, document
111577
(($, window, document) -> "use strict" #set the plugin name pluginName = 'suraido' defaults = speed: 500 delay: 3000 pause: false loop: false enableKeys: true enableDots: true enableArrows: true prev: '«' next: '»' fluid: true starting: false completed: false easing: 'swing' autoplay: false paginationClass: 'pagination' paginationItemClass: 'dot' arrowsClass: 'arrows' arrowClass: 'arrow' class Furatto.Suraido constructor: (@el, options) -> #jquery element wrapper @$el = $(@el) #merges options @options = $.extend {}, defaults, options #slider items wrapper @itemsWrapper = @$el.find('>ul') #max slider size @maxSize = width: @$el.outerWidth() | 0 height: @$el.outerHeight() | 0 #items definition weakSelf = @ @items = $(@itemsWrapper).find('>li').each (index) -> $this = $(@) width = $this.outerWidth() height = $this.outerHeight() weakSelf.maxSize.width = width if width > weakSelf.maxSize.width weakSelf.maxSize.height = height if height > weakSelf.maxSize.height #items on the wrapper @itemsLength = @items.length #current item position @currentItemIndex = 0 #fix for alpha on captions @items.find('.caption').css(width: "#{100 / @itemsLength}%") #set the main element @_setsMainElement() #Set relative widths @itemsWrapper.css( position: "relative" left: 0 width: "#{@itemsLength * 100}%" ) #sets the styling for each slider item @_setsItems() #autoslide @_enablesAutoPlay() if @options.autoplay #keypresses binding @_enableBindKeys() if @options.enableKeys @options.enableDots and @_createPagination() @options.enableArrows and @_createArrows() #fluid behavior for responsive layouts @_enablesFluidBehavior() if @options.fluid #chrome fix if window.chrome @items.css 'background-size', '100% 100%' if $.event.special['swipe'] or $.Event 'swipe' @$el.on 'swipeleft swiperight swipeLeft swipeRight', (e) => if e.type.toLowerCase() is 'swipeleft' then @next() else @prev() _setsItems: => @items.css float: 'left' width: "#{100 / @itemsLength}%" _setsMainElement: => @$el.css width: @maxSize.width height: @items.first().outerHeight() overflow: 'hidden' _enablesAutoPlay: => setTimeout(=> if @options.delay | 0 @play() if @options.pause @$el.on 'mouseover, mouseout', (event) => @stop() event.type is 'mouseout' && @play() , @options.autoPlayDelay | 0) _enablesFluidBehavior: => $(window).resize(=> @resize and clearTimeout(@resize) @resize = setTimeout(=> style = height: @items.eq(@currentItemIndex).outerHeight() + 30 width = @$el.outerWidth() @itemsWrapper.css style style['width'] = "#{Math.min(Math.round((width / @$el.parent().width()) * 100), 100)}%" @$el.css style , 50) ).resize() _enableBindKeys: => $(document).on 'keydown', (event) => switch event.which when 37 then @prev() when 39 then @next() when 27 || 32 then @stop() _createPagination: => html = "<ol class='#{@options.paginationClass}'>" $.each @items, (index) => html += "<li class='#{if index == @currentItemIndex then @options.paginationItemClass + ' active' else @options.paginationItemClass}'> #{++index}</li>" html += "</ol>" @_bindPagination(@options.paginationClass, @options.paginationItemClass, html) _createArrows: => html = "<div class=\"" html = html + @options.arrowsClass + "\">" + html + @options.arrowClass + " prev\">" + @options.prev + "</div>" + html + @options.arrowClass + " next\">" + @options.next + "</div></div>" @_bindPagination(@options.arrowsClass, @options.arrowClass, html) _bindPagination: (className, itemClassName, html) -> weakSelf = @ @$el.addClass("has-#{className}").append(html).find(".#{itemClassName}").click -> $this = $(@) if $this.hasClass(weakSelf.options.paginationItemClass) weakSelf.stop().to($this.index()) else if $this.hasClass('prev') then weakSelf.prev() else weakSelf.next() to: (index, callback) => if @t @stop() @play() target = @items.eq(index) $.isFunction(@options.starting) and !callback and @options.starting @$el, @items.eq(@currentItemIndex) if not (target.length || index < 0) and @options.loop is false return if index < 0 index = @items.length - 1 speed = if callback then 5 else @options.speed | 0 easing = @options.easing obj = height: target.outerHeight() + 30 if not @itemsWrapper.queue('fx').length @$el.find(".#{@options.paginationItemClass}").eq(index).addClass('active').siblings().removeClass('active') @$el.animate(obj, speed, easing) and @itemsWrapper.animate($.extend( left: "-#{index}00%", obj), speed, easing, (data) => @currentItemIndex = index $.isFunction(@options.complete) and !callback and @options.complete(@el, target) ) play: => @t = setInterval( => @to(@currentItemIndex + 1) , @options.delay | 0) stop: => @t = clearInterval(@t) @ next: => if @currentItemIndex == (@itemsLength - 1) @stop().to(0) else @stop().to(@currentItemIndex + 1) prev: => @stop().to(@currentItemIndex - 1) $.fn[pluginName] = (options) -> sliders = this.length [_, args...] = arguments @each (index) -> me = $(@) plugin = $.data @, "plugin_#{pluginName}" unless plugin key = "<KEY>if sliders > 1 then <KEY> + ++index else ''<KEY>}" instance = new Furatto.Suraido(@, options) me.data(key, instance).data('key', key) else if plugin[_]? and $.type(plugin[_]) == 'function' plugin[_].apply plugin, args Furatto.Suraido.version = "1.0.0" $(document).ready -> $('[data-suraido]').each -> $(@).suraido() ) $, window, document
true
(($, window, document) -> "use strict" #set the plugin name pluginName = 'suraido' defaults = speed: 500 delay: 3000 pause: false loop: false enableKeys: true enableDots: true enableArrows: true prev: '«' next: '»' fluid: true starting: false completed: false easing: 'swing' autoplay: false paginationClass: 'pagination' paginationItemClass: 'dot' arrowsClass: 'arrows' arrowClass: 'arrow' class Furatto.Suraido constructor: (@el, options) -> #jquery element wrapper @$el = $(@el) #merges options @options = $.extend {}, defaults, options #slider items wrapper @itemsWrapper = @$el.find('>ul') #max slider size @maxSize = width: @$el.outerWidth() | 0 height: @$el.outerHeight() | 0 #items definition weakSelf = @ @items = $(@itemsWrapper).find('>li').each (index) -> $this = $(@) width = $this.outerWidth() height = $this.outerHeight() weakSelf.maxSize.width = width if width > weakSelf.maxSize.width weakSelf.maxSize.height = height if height > weakSelf.maxSize.height #items on the wrapper @itemsLength = @items.length #current item position @currentItemIndex = 0 #fix for alpha on captions @items.find('.caption').css(width: "#{100 / @itemsLength}%") #set the main element @_setsMainElement() #Set relative widths @itemsWrapper.css( position: "relative" left: 0 width: "#{@itemsLength * 100}%" ) #sets the styling for each slider item @_setsItems() #autoslide @_enablesAutoPlay() if @options.autoplay #keypresses binding @_enableBindKeys() if @options.enableKeys @options.enableDots and @_createPagination() @options.enableArrows and @_createArrows() #fluid behavior for responsive layouts @_enablesFluidBehavior() if @options.fluid #chrome fix if window.chrome @items.css 'background-size', '100% 100%' if $.event.special['swipe'] or $.Event 'swipe' @$el.on 'swipeleft swiperight swipeLeft swipeRight', (e) => if e.type.toLowerCase() is 'swipeleft' then @next() else @prev() _setsItems: => @items.css float: 'left' width: "#{100 / @itemsLength}%" _setsMainElement: => @$el.css width: @maxSize.width height: @items.first().outerHeight() overflow: 'hidden' _enablesAutoPlay: => setTimeout(=> if @options.delay | 0 @play() if @options.pause @$el.on 'mouseover, mouseout', (event) => @stop() event.type is 'mouseout' && @play() , @options.autoPlayDelay | 0) _enablesFluidBehavior: => $(window).resize(=> @resize and clearTimeout(@resize) @resize = setTimeout(=> style = height: @items.eq(@currentItemIndex).outerHeight() + 30 width = @$el.outerWidth() @itemsWrapper.css style style['width'] = "#{Math.min(Math.round((width / @$el.parent().width()) * 100), 100)}%" @$el.css style , 50) ).resize() _enableBindKeys: => $(document).on 'keydown', (event) => switch event.which when 37 then @prev() when 39 then @next() when 27 || 32 then @stop() _createPagination: => html = "<ol class='#{@options.paginationClass}'>" $.each @items, (index) => html += "<li class='#{if index == @currentItemIndex then @options.paginationItemClass + ' active' else @options.paginationItemClass}'> #{++index}</li>" html += "</ol>" @_bindPagination(@options.paginationClass, @options.paginationItemClass, html) _createArrows: => html = "<div class=\"" html = html + @options.arrowsClass + "\">" + html + @options.arrowClass + " prev\">" + @options.prev + "</div>" + html + @options.arrowClass + " next\">" + @options.next + "</div></div>" @_bindPagination(@options.arrowsClass, @options.arrowClass, html) _bindPagination: (className, itemClassName, html) -> weakSelf = @ @$el.addClass("has-#{className}").append(html).find(".#{itemClassName}").click -> $this = $(@) if $this.hasClass(weakSelf.options.paginationItemClass) weakSelf.stop().to($this.index()) else if $this.hasClass('prev') then weakSelf.prev() else weakSelf.next() to: (index, callback) => if @t @stop() @play() target = @items.eq(index) $.isFunction(@options.starting) and !callback and @options.starting @$el, @items.eq(@currentItemIndex) if not (target.length || index < 0) and @options.loop is false return if index < 0 index = @items.length - 1 speed = if callback then 5 else @options.speed | 0 easing = @options.easing obj = height: target.outerHeight() + 30 if not @itemsWrapper.queue('fx').length @$el.find(".#{@options.paginationItemClass}").eq(index).addClass('active').siblings().removeClass('active') @$el.animate(obj, speed, easing) and @itemsWrapper.animate($.extend( left: "-#{index}00%", obj), speed, easing, (data) => @currentItemIndex = index $.isFunction(@options.complete) and !callback and @options.complete(@el, target) ) play: => @t = setInterval( => @to(@currentItemIndex + 1) , @options.delay | 0) stop: => @t = clearInterval(@t) @ next: => if @currentItemIndex == (@itemsLength - 1) @stop().to(0) else @stop().to(@currentItemIndex + 1) prev: => @stop().to(@currentItemIndex - 1) $.fn[pluginName] = (options) -> sliders = this.length [_, args...] = arguments @each (index) -> me = $(@) plugin = $.data @, "plugin_#{pluginName}" unless plugin key = "PI:KEY:<KEY>END_PIif sliders > 1 then PI:KEY:<KEY>END_PI + ++index else ''PI:KEY:<KEY>END_PI}" instance = new Furatto.Suraido(@, options) me.data(key, instance).data('key', key) else if plugin[_]? and $.type(plugin[_]) == 'function' plugin[_].apply plugin, args Furatto.Suraido.version = "1.0.0" $(document).ready -> $('[data-suraido]').each -> $(@).suraido() ) $, window, document
[ { "context": "ole.error err if err\n\n personalToken = 'pt' + do require 'hat'\n\n bindingKey ", "end": 12074, "score": 0.7466939687728882, "start": 12072, "tag": "KEY", "value": "pt" }, { "context": "o require 'hat'\n\n bindingKey = \"clie...
workers/auth/lib/auth/authworker.coffee
ezgikaysi/koding
1
# coffeelint: disable=cyclomatic_complexity { EventEmitter } = require 'microemitter' module.exports = class AuthWorker extends EventEmitter AuthedClient = require './authedclient' AUTH_EXCHANGE_OPTIONS = type : 'fanout' autoDelete : yes REROUTING_EXCHANGE_OPTIONS = USERS_PRESENCE_CONTROL_EXCHANGE_OPTIONS = type : 'fanout' autoDelete : yes NOTIFICATION_EXCHANGE_OPTIONS = type : 'topic' autoDelete : yes constructor: (@bongo, options = {}) -> # instance options { @servicesPresenceExchange, @reroutingExchange @notificationExchange, @usersPresenceControlExchange @presenceTimeoutAmount, @authExchange, @authAllExchange } = options # initialize defaults: @servicesPresenceExchange ?= 'services-presence' @usersPresenceControlExchange ?= 'users-presence-control' @reroutingExchange ?= 'routing-control' @notificationExchange ?= 'notification' @authExchange ?= 'auth' @authAllExchange ?= 'authAll' @presenceTimeoutAmount ?= 1000 * 60 * 2 # 2 min # instance state @services = {} @clients = bySocketId : {} byExchange : {} byRoutingKey : {} @usersBySocketId = {} @counts = {} @waitingAuthWhos = {} bound: require 'koding-bound' authenticate: (messageData, routingKey, socketId, callback) -> { clientId, channel, event } = messageData @requireSession clientId, routingKey, socketId, callback requireSession: (clientId, routingKey, socketId, callback) -> { JSession } = @bongo.models JSession.fetchSession clientId, (err, { session }) => if err? then console.error err if err? or not session? then @rejectClient routingKey else @addUserSocket session.username, socketId if session.username? tokenHasChanged = session.clientId isnt clientId @updateSessionToken session.clientId, routingKey if tokenHasChanged callback session addUserSocket: (username, socketId) -> @usersBySocketId[socketId] = username @fetchUserPresenceControlExchange (exchange) -> exchange.publish 'auth.join', { username, socketId } removeUserSocket: (socketId) -> username = @usersBySocketId[socketId] return unless username delete @usersBySocketId[username] @fetchUserPresenceControlExchange (exchange) -> exchange.publish 'auth.leave', { username, socketId } updateSessionToken: (clientId, routingKey) -> @bongo.respondToClient routingKey, method : 'updateSessionToken' arguments : [clientId] callbacks : {} getNextServiceInfo: (serviceType) -> count = @counts[serviceType] ?= 0 servicesOfType = @services[serviceType] return unless servicesOfType?.length serviceInfo = servicesOfType[count % servicesOfType.length] @counts[serviceType] += 1 return serviceInfo removeService: ({ serviceGenericName, serviceUniqueName }) -> servicesOfType = @services[serviceGenericName] [index] = (i for s, i in servicesOfType \ when s.serviceUniqueName is serviceUniqueName) servicesOfType.splice index, 1 clientsByExchange = @clients.byExchange[serviceUniqueName] clientsByExchange?.forEach @bound 'cycleClient' cycleClient: (client) -> { routingKey } = client @bongo.respondToClient routingKey, method : 'cycleChannel' arguments : [] callbacks : {} removeClient: (rest...) -> if rest.length is 1 [client] = rest return @removeClient client.socketId, client.exchange, client.routingKey [socketId, exchange, routingKey] = rest delete @clients.bySocketId[socketId] delete @clients.byExchange[exchange] delete @clients.byRoutingKey[routingKey] addClient: (socketId, exchange, routingKey, sendOk = yes) -> if sendOk @bongo.respondToClient routingKey, method : 'auth.authOk' arguments : [] callbacks : {} clientsBySocketId = @clients.bySocketId[socketId] ?= [] clientsByExchange = @clients.byExchange[exchange] ?= [] clientsByRoutingKey = @clients.byRoutingKey[routingKey] ?= [] client = new AuthedClient { routingKey, socketId, exchange } clientsBySocketId.push client clientsByRoutingKey.push client clientsByExchange.push client rejectClient:(routingKey, message) -> # console.log 'rejecting', routingKey return console.trace() unless routingKey? @bongo.respondToClient routingKey, method : 'error' arguments : [{ message: message ? 'Access denied' }] callbacks : {} setSecretNames:(routingKey, publishingName, subscribingName) -> setSecretNamesEvent = "#{routingKey}.setSecretNames" message = JSON.stringify { publishingName, subscribingName } @bongo.respondToClient setSecretNamesEvent, message publishToService: (exchangeName, routingKey, payload, callback) -> { connection } = @bongo.mq connection.exchange exchangeName, AUTH_EXCHANGE_OPTIONS, (exchange) -> exchange.publish routingKey, payload exchange.close() # don't leak a channel callback? null getWaitingAuthWhoKey = (o) -> "#{o.username}!#{o.correlationName}!#{o.serviceGenericName}" makeExchangeFetcher = (exchangeName, exchangeOptions) -> exKey = "#{exchangeName}_" (callback) -> if @[exKey] then return process.nextTick => callback @[exKey] @bongo.mq.connection.exchange( @[exchangeName] exchangeOptions (exchange) => callback @[exKey] = exchange ).on 'error', console.error.bind console fetchReroutingExchange: makeExchangeFetcher( 'reroutingExchange', REROUTING_EXCHANGE_OPTIONS ) fetchNotificationExchange: makeExchangeFetcher( 'notificationExchange', NOTIFICATION_EXCHANGE_OPTIONS ) fetchUserPresenceControlExchange: makeExchangeFetcher( 'usersPresenceControlExchange', USERS_PRESENCE_CONTROL_EXCHANGE_OPTIONS ) addBinding:(bindingExchange, bindingKey, publishingExchange, routingKey, suffix = '') -> suffix = ".#{suffix}" if suffix.length @fetchReroutingExchange (exchange) -> exchange.publish 'auth.join', { bindingExchange bindingKey publishingExchange routingKey suffix } notify:(routingKey, event, contents) -> @fetchNotificationExchange (exchange) -> exchange.publish routingKey, { event, contents } respondServiceUnavailable: (routingKey, serviceGenericName) -> @bongo.respondToClient routingKey, method : 'error' arguments : [{ message : "Service unavailable! #{routingKey}" code :503 serviceGenericName }] callbacks : {} generateClient = (group, account) -> { context: { group: group.slug }, connection: { delegate: account } } join: do -> ensureGroupPermission = ({ group, account }, callback) -> { JGroup } = @bongo.models checkGroupPermission.call this, group, account, (err, hasPermission) -> if err then callback err else if hasPermission JGroup.fetchSecretChannelName group.slug, callback else callback { message: 'Access denied!', code: 403 } ensureSocialapiChannelPermission = ({ group, account, options }, callback) -> { SocialChannel } = @bongo.models checkGroupPermission.call this, group, account, (err, hasPermission) -> if err then callback err else if hasPermission client = generateClient group, account reqOptions = type: options.apiChannelType name: options.apiChannelName SocialChannel.checkChannelParticipation client, reqOptions, (err, res) -> if err console.warn """ tries to open an unattended channel: user: #{account.profile.nickname} channelname: #{reqOptions.name} channeltype: #{reqOptions.type} """ return callback err SocialChannel.fetchSecretChannelName options, callback else callback { message: 'Access denied!', code: 403 } checkGroupPermission = (group, account, callback) -> { JPermissionSet } = @bongo.models client = generateClient group, account JPermissionSet.checkPermission client, 'read group activity', group, null, callback joinGroupHelper = (messageData, routingKey, socketId) -> { JAccount, JGroup } = @bongo.models fail = (err) => console.error err if err @rejectClient routingKey @authenticate messageData, routingKey, socketId, (session) => unless session then fail() fetchAccountAndGroup.call this, session.username, messageData.group, (err, data) => return fail err if err { account, group } = data ensureGroupPermission.call this, { group, account }, (err, secretChannelName) => if err or not secretChannelName @rejectClient routingKey else handleSecretnameAndRoutingKey.call this, routingKey, secretChannelName handleSecretnameAndRoutingKey = (routingKey, secretChannelName) -> @addBinding 'broadcast', secretChannelName, 'broker', routingKey @setSecretNames routingKey, secretChannelName fetchAccountAndGroup = (username, groupSlug, callback) -> { JAccount, JGroup } = @bongo.models JAccount.one { 'profile.nickname': username }, (err, account) -> return callback err if err return callback { message: 'Account not found' } if not account JGroup.one { slug: groupSlug }, (err, group) -> return callback err if err return callback { message: 'Group not found' } if not group return callback null, { account, group } joinSocialApiHelper = (messageData, routingKey, socketId) -> { JAccount, JGroup, SocialChannel } = @bongo.models fail = (err) => console.error err if err @rejectClient routingKey @authenticate messageData, routingKey, socketId, (session) => return fail() unless session fetchAccountAndGroup.call this, session.username, messageData.group, (err, data) => return fail err if err { account, group } = data options = groupSlug : group.slug apiChannelType : messageData.channelType apiChannelName : messageData.channelName ensureSocialapiChannelPermission.call this, { group, account, options } , (err, secretChannelName) => return fail err if err unless secretChannelName return fail { message: 'secretChannelName not set' } handleSecretnameAndRoutingKey.call this, routingKey, secretChannelName joinNotificationHelper = (messageData, routingKey, socketId) -> fail = (err) => console.error err if err @rejectClient routingKey @authenticate messageData, routingKey, socketId, (session) => unless session then fail() else if session?.username @addClient socketId, @reroutingExchange, routingKey, no bindingKey = session.username @addBinding 'notification', bindingKey, 'broker', routingKey else @rejectClient routingKey joinChatHelper = (messageData, routingKey, socketId) -> { name } = messageData { JName } = @bongo.models fail = => @rejectClient routingKey @authenticate messageData, routingKey, socketId, (session) => return fail() unless session?.username? JName.fetchSecretName name, (err, secretChannelName) => return console.error err if err personalToken = 'pt' + do require 'hat' bindingKey = "client.#{personalToken}" consumerRoutingKey = "chat.#{secretChannelName}" { username } = session @addBinding 'chat', bindingKey, 'chat-hose', consumerRoutingKey, username @notify username, 'chatOpen', { publicName : name routingKey : personalToken bindingKey : consumerRoutingKey } joinClient = (messageData, socketId) -> { routingKey, brokerExchange, serviceType, wrapperRoutingKeyPrefix } = messageData switch serviceType when 'bongo' then # ignore when 'group' unless ///^group\.#{messageData.group}\.///.test routingKey return @rejectClient routingKey joinGroupHelper.call this, messageData, routingKey, socketId when 'socialapi' unless ///^socialapi\.///.test routingKey return @rejectClient routingKey joinSocialApiHelper.call this, messageData, routingKey, socketId when 'chat' joinChatHelper.call this, messageData, routingKey, socketId when 'notification' unless ///^notification\.///.test routingKey return @rejectClient routingKey joinNotificationHelper.call this, messageData, routingKey, socketId when 'secret' @addClient socketId, 'routing-control', wrapperRoutingKeyPrefix, no else @rejectClient routingKey unless /^oid./.test routingKey # TODO: we're not really handling the oid channels at all (I guess we don't need to) C.T. cleanUpClient: (client) -> @removeClient client @bongo.mq.connection.exchange client.exchange, AUTH_EXCHANGE_OPTIONS, (exchange) -> exchange.publish 'auth.leave', { routingKey: client.routingKey } exchange.close() # don't leak a channel! cleanUpAfterDisconnect: (socketId) -> @removeUserSocket socketId clientServices = @clients.bySocketId[socketId] clientServices?.forEach @bound 'cleanUpClient' connect: -> { bongo } = this bongo.on 'connected', => { connection } = bongo.mq # FIXME: this is a hack to hold the chat exchange open for the meantime connection.exchange 'chat', NOTIFICATION_EXCHANGE_OPTIONS, (chatExchange) -> # *chirp chirp chirp chirp* connection.exchange @authAllExchange, AUTH_EXCHANGE_OPTIONS, (authAllExchange) => connection.queue '', { exclusive:yes }, (authAllQueue) => authAllQueue.bind authAllExchange, '' authAllQueue.on 'queueBindOk', => authAllQueue.subscribe (message, headers, deliveryInfo) => { routingKey } = deliveryInfo messageStr = "#{message.data}" switch routingKey when 'broker.clientConnected' then # ignore when 'broker.clientDisconnected' @cleanUpAfterDisconnect messageStr connection.exchange @authExchange, AUTH_EXCHANGE_OPTIONS, (authExchange) => connection.queue @authExchange, (authQueue) => authQueue.bind authExchange, '' authQueue.on 'queueBindOk', => authQueue.subscribe (message, headers, deliveryInfo) => { routingKey, correlationId } = deliveryInfo socketId = correlationId messageStr = "#{message.data}" messageData = (try JSON.parse messageStr) or message switch routingKey when "client.#{@authExchange}" @join messageData, socketId else @rejectClient routingKey
147956
# coffeelint: disable=cyclomatic_complexity { EventEmitter } = require 'microemitter' module.exports = class AuthWorker extends EventEmitter AuthedClient = require './authedclient' AUTH_EXCHANGE_OPTIONS = type : 'fanout' autoDelete : yes REROUTING_EXCHANGE_OPTIONS = USERS_PRESENCE_CONTROL_EXCHANGE_OPTIONS = type : 'fanout' autoDelete : yes NOTIFICATION_EXCHANGE_OPTIONS = type : 'topic' autoDelete : yes constructor: (@bongo, options = {}) -> # instance options { @servicesPresenceExchange, @reroutingExchange @notificationExchange, @usersPresenceControlExchange @presenceTimeoutAmount, @authExchange, @authAllExchange } = options # initialize defaults: @servicesPresenceExchange ?= 'services-presence' @usersPresenceControlExchange ?= 'users-presence-control' @reroutingExchange ?= 'routing-control' @notificationExchange ?= 'notification' @authExchange ?= 'auth' @authAllExchange ?= 'authAll' @presenceTimeoutAmount ?= 1000 * 60 * 2 # 2 min # instance state @services = {} @clients = bySocketId : {} byExchange : {} byRoutingKey : {} @usersBySocketId = {} @counts = {} @waitingAuthWhos = {} bound: require 'koding-bound' authenticate: (messageData, routingKey, socketId, callback) -> { clientId, channel, event } = messageData @requireSession clientId, routingKey, socketId, callback requireSession: (clientId, routingKey, socketId, callback) -> { JSession } = @bongo.models JSession.fetchSession clientId, (err, { session }) => if err? then console.error err if err? or not session? then @rejectClient routingKey else @addUserSocket session.username, socketId if session.username? tokenHasChanged = session.clientId isnt clientId @updateSessionToken session.clientId, routingKey if tokenHasChanged callback session addUserSocket: (username, socketId) -> @usersBySocketId[socketId] = username @fetchUserPresenceControlExchange (exchange) -> exchange.publish 'auth.join', { username, socketId } removeUserSocket: (socketId) -> username = @usersBySocketId[socketId] return unless username delete @usersBySocketId[username] @fetchUserPresenceControlExchange (exchange) -> exchange.publish 'auth.leave', { username, socketId } updateSessionToken: (clientId, routingKey) -> @bongo.respondToClient routingKey, method : 'updateSessionToken' arguments : [clientId] callbacks : {} getNextServiceInfo: (serviceType) -> count = @counts[serviceType] ?= 0 servicesOfType = @services[serviceType] return unless servicesOfType?.length serviceInfo = servicesOfType[count % servicesOfType.length] @counts[serviceType] += 1 return serviceInfo removeService: ({ serviceGenericName, serviceUniqueName }) -> servicesOfType = @services[serviceGenericName] [index] = (i for s, i in servicesOfType \ when s.serviceUniqueName is serviceUniqueName) servicesOfType.splice index, 1 clientsByExchange = @clients.byExchange[serviceUniqueName] clientsByExchange?.forEach @bound 'cycleClient' cycleClient: (client) -> { routingKey } = client @bongo.respondToClient routingKey, method : 'cycleChannel' arguments : [] callbacks : {} removeClient: (rest...) -> if rest.length is 1 [client] = rest return @removeClient client.socketId, client.exchange, client.routingKey [socketId, exchange, routingKey] = rest delete @clients.bySocketId[socketId] delete @clients.byExchange[exchange] delete @clients.byRoutingKey[routingKey] addClient: (socketId, exchange, routingKey, sendOk = yes) -> if sendOk @bongo.respondToClient routingKey, method : 'auth.authOk' arguments : [] callbacks : {} clientsBySocketId = @clients.bySocketId[socketId] ?= [] clientsByExchange = @clients.byExchange[exchange] ?= [] clientsByRoutingKey = @clients.byRoutingKey[routingKey] ?= [] client = new AuthedClient { routingKey, socketId, exchange } clientsBySocketId.push client clientsByRoutingKey.push client clientsByExchange.push client rejectClient:(routingKey, message) -> # console.log 'rejecting', routingKey return console.trace() unless routingKey? @bongo.respondToClient routingKey, method : 'error' arguments : [{ message: message ? 'Access denied' }] callbacks : {} setSecretNames:(routingKey, publishingName, subscribingName) -> setSecretNamesEvent = "#{routingKey}.setSecretNames" message = JSON.stringify { publishingName, subscribingName } @bongo.respondToClient setSecretNamesEvent, message publishToService: (exchangeName, routingKey, payload, callback) -> { connection } = @bongo.mq connection.exchange exchangeName, AUTH_EXCHANGE_OPTIONS, (exchange) -> exchange.publish routingKey, payload exchange.close() # don't leak a channel callback? null getWaitingAuthWhoKey = (o) -> "#{o.username}!#{o.correlationName}!#{o.serviceGenericName}" makeExchangeFetcher = (exchangeName, exchangeOptions) -> exKey = "#{exchangeName}_" (callback) -> if @[exKey] then return process.nextTick => callback @[exKey] @bongo.mq.connection.exchange( @[exchangeName] exchangeOptions (exchange) => callback @[exKey] = exchange ).on 'error', console.error.bind console fetchReroutingExchange: makeExchangeFetcher( 'reroutingExchange', REROUTING_EXCHANGE_OPTIONS ) fetchNotificationExchange: makeExchangeFetcher( 'notificationExchange', NOTIFICATION_EXCHANGE_OPTIONS ) fetchUserPresenceControlExchange: makeExchangeFetcher( 'usersPresenceControlExchange', USERS_PRESENCE_CONTROL_EXCHANGE_OPTIONS ) addBinding:(bindingExchange, bindingKey, publishingExchange, routingKey, suffix = '') -> suffix = ".#{suffix}" if suffix.length @fetchReroutingExchange (exchange) -> exchange.publish 'auth.join', { bindingExchange bindingKey publishingExchange routingKey suffix } notify:(routingKey, event, contents) -> @fetchNotificationExchange (exchange) -> exchange.publish routingKey, { event, contents } respondServiceUnavailable: (routingKey, serviceGenericName) -> @bongo.respondToClient routingKey, method : 'error' arguments : [{ message : "Service unavailable! #{routingKey}" code :503 serviceGenericName }] callbacks : {} generateClient = (group, account) -> { context: { group: group.slug }, connection: { delegate: account } } join: do -> ensureGroupPermission = ({ group, account }, callback) -> { JGroup } = @bongo.models checkGroupPermission.call this, group, account, (err, hasPermission) -> if err then callback err else if hasPermission JGroup.fetchSecretChannelName group.slug, callback else callback { message: 'Access denied!', code: 403 } ensureSocialapiChannelPermission = ({ group, account, options }, callback) -> { SocialChannel } = @bongo.models checkGroupPermission.call this, group, account, (err, hasPermission) -> if err then callback err else if hasPermission client = generateClient group, account reqOptions = type: options.apiChannelType name: options.apiChannelName SocialChannel.checkChannelParticipation client, reqOptions, (err, res) -> if err console.warn """ tries to open an unattended channel: user: #{account.profile.nickname} channelname: #{reqOptions.name} channeltype: #{reqOptions.type} """ return callback err SocialChannel.fetchSecretChannelName options, callback else callback { message: 'Access denied!', code: 403 } checkGroupPermission = (group, account, callback) -> { JPermissionSet } = @bongo.models client = generateClient group, account JPermissionSet.checkPermission client, 'read group activity', group, null, callback joinGroupHelper = (messageData, routingKey, socketId) -> { JAccount, JGroup } = @bongo.models fail = (err) => console.error err if err @rejectClient routingKey @authenticate messageData, routingKey, socketId, (session) => unless session then fail() fetchAccountAndGroup.call this, session.username, messageData.group, (err, data) => return fail err if err { account, group } = data ensureGroupPermission.call this, { group, account }, (err, secretChannelName) => if err or not secretChannelName @rejectClient routingKey else handleSecretnameAndRoutingKey.call this, routingKey, secretChannelName handleSecretnameAndRoutingKey = (routingKey, secretChannelName) -> @addBinding 'broadcast', secretChannelName, 'broker', routingKey @setSecretNames routingKey, secretChannelName fetchAccountAndGroup = (username, groupSlug, callback) -> { JAccount, JGroup } = @bongo.models JAccount.one { 'profile.nickname': username }, (err, account) -> return callback err if err return callback { message: 'Account not found' } if not account JGroup.one { slug: groupSlug }, (err, group) -> return callback err if err return callback { message: 'Group not found' } if not group return callback null, { account, group } joinSocialApiHelper = (messageData, routingKey, socketId) -> { JAccount, JGroup, SocialChannel } = @bongo.models fail = (err) => console.error err if err @rejectClient routingKey @authenticate messageData, routingKey, socketId, (session) => return fail() unless session fetchAccountAndGroup.call this, session.username, messageData.group, (err, data) => return fail err if err { account, group } = data options = groupSlug : group.slug apiChannelType : messageData.channelType apiChannelName : messageData.channelName ensureSocialapiChannelPermission.call this, { group, account, options } , (err, secretChannelName) => return fail err if err unless secretChannelName return fail { message: 'secretChannelName not set' } handleSecretnameAndRoutingKey.call this, routingKey, secretChannelName joinNotificationHelper = (messageData, routingKey, socketId) -> fail = (err) => console.error err if err @rejectClient routingKey @authenticate messageData, routingKey, socketId, (session) => unless session then fail() else if session?.username @addClient socketId, @reroutingExchange, routingKey, no bindingKey = session.username @addBinding 'notification', bindingKey, 'broker', routingKey else @rejectClient routingKey joinChatHelper = (messageData, routingKey, socketId) -> { name } = messageData { JName } = @bongo.models fail = => @rejectClient routingKey @authenticate messageData, routingKey, socketId, (session) => return fail() unless session?.username? JName.fetchSecretName name, (err, secretChannelName) => return console.error err if err personalToken = '<KEY>' + do require 'hat' bindingKey = "<KEY>}" consumerRoutingKey = "chat<KEY>.#{secretChannelName}" { username } = session @addBinding 'chat', bindingKey, 'chat-hose', consumerRoutingKey, username @notify username, 'chatOpen', { publicName : name routingKey : personalToken bindingKey : consumerRoutingKey } joinClient = (messageData, socketId) -> { routingKey, brokerExchange, serviceType, wrapperRoutingKeyPrefix } = messageData switch serviceType when 'bongo' then # ignore when 'group' unless ///^group\.#{messageData.group}\.///.test routingKey return @rejectClient routingKey joinGroupHelper.call this, messageData, routingKey, socketId when 'socialapi' unless ///^socialapi\.///.test routingKey return @rejectClient routingKey joinSocialApiHelper.call this, messageData, routingKey, socketId when 'chat' joinChatHelper.call this, messageData, routingKey, socketId when 'notification' unless ///^notification\.///.test routingKey return @rejectClient routingKey joinNotificationHelper.call this, messageData, routingKey, socketId when 'secret' @addClient socketId, 'routing-control', wrapperRoutingKeyPrefix, no else @rejectClient routingKey unless /^oid./.test routingKey # TODO: we're not really handling the oid channels at all (I guess we don't need to) C.T. cleanUpClient: (client) -> @removeClient client @bongo.mq.connection.exchange client.exchange, AUTH_EXCHANGE_OPTIONS, (exchange) -> exchange.publish 'auth.leave', { routingKey: client.routingKey } exchange.close() # don't leak a channel! cleanUpAfterDisconnect: (socketId) -> @removeUserSocket socketId clientServices = @clients.bySocketId[socketId] clientServices?.forEach @bound 'cleanUpClient' connect: -> { bongo } = this bongo.on 'connected', => { connection } = bongo.mq # FIXME: this is a hack to hold the chat exchange open for the meantime connection.exchange 'chat', NOTIFICATION_EXCHANGE_OPTIONS, (chatExchange) -> # *chirp chirp chirp chirp* connection.exchange @authAllExchange, AUTH_EXCHANGE_OPTIONS, (authAllExchange) => connection.queue '', { exclusive:yes }, (authAllQueue) => authAllQueue.bind authAllExchange, '' authAllQueue.on 'queueBindOk', => authAllQueue.subscribe (message, headers, deliveryInfo) => { routingKey } = deliveryInfo messageStr = "#{message.data}" switch routingKey when 'broker.clientConnected' then # ignore when 'broker.clientDisconnected' @cleanUpAfterDisconnect messageStr connection.exchange @authExchange, AUTH_EXCHANGE_OPTIONS, (authExchange) => connection.queue @authExchange, (authQueue) => authQueue.bind authExchange, '' authQueue.on 'queueBindOk', => authQueue.subscribe (message, headers, deliveryInfo) => { routingKey, correlationId } = deliveryInfo socketId = correlationId messageStr = "#{message.data}" messageData = (try JSON.parse messageStr) or message switch routingKey when "client.#{@authExchange}" @join messageData, socketId else @rejectClient routingKey
true
# coffeelint: disable=cyclomatic_complexity { EventEmitter } = require 'microemitter' module.exports = class AuthWorker extends EventEmitter AuthedClient = require './authedclient' AUTH_EXCHANGE_OPTIONS = type : 'fanout' autoDelete : yes REROUTING_EXCHANGE_OPTIONS = USERS_PRESENCE_CONTROL_EXCHANGE_OPTIONS = type : 'fanout' autoDelete : yes NOTIFICATION_EXCHANGE_OPTIONS = type : 'topic' autoDelete : yes constructor: (@bongo, options = {}) -> # instance options { @servicesPresenceExchange, @reroutingExchange @notificationExchange, @usersPresenceControlExchange @presenceTimeoutAmount, @authExchange, @authAllExchange } = options # initialize defaults: @servicesPresenceExchange ?= 'services-presence' @usersPresenceControlExchange ?= 'users-presence-control' @reroutingExchange ?= 'routing-control' @notificationExchange ?= 'notification' @authExchange ?= 'auth' @authAllExchange ?= 'authAll' @presenceTimeoutAmount ?= 1000 * 60 * 2 # 2 min # instance state @services = {} @clients = bySocketId : {} byExchange : {} byRoutingKey : {} @usersBySocketId = {} @counts = {} @waitingAuthWhos = {} bound: require 'koding-bound' authenticate: (messageData, routingKey, socketId, callback) -> { clientId, channel, event } = messageData @requireSession clientId, routingKey, socketId, callback requireSession: (clientId, routingKey, socketId, callback) -> { JSession } = @bongo.models JSession.fetchSession clientId, (err, { session }) => if err? then console.error err if err? or not session? then @rejectClient routingKey else @addUserSocket session.username, socketId if session.username? tokenHasChanged = session.clientId isnt clientId @updateSessionToken session.clientId, routingKey if tokenHasChanged callback session addUserSocket: (username, socketId) -> @usersBySocketId[socketId] = username @fetchUserPresenceControlExchange (exchange) -> exchange.publish 'auth.join', { username, socketId } removeUserSocket: (socketId) -> username = @usersBySocketId[socketId] return unless username delete @usersBySocketId[username] @fetchUserPresenceControlExchange (exchange) -> exchange.publish 'auth.leave', { username, socketId } updateSessionToken: (clientId, routingKey) -> @bongo.respondToClient routingKey, method : 'updateSessionToken' arguments : [clientId] callbacks : {} getNextServiceInfo: (serviceType) -> count = @counts[serviceType] ?= 0 servicesOfType = @services[serviceType] return unless servicesOfType?.length serviceInfo = servicesOfType[count % servicesOfType.length] @counts[serviceType] += 1 return serviceInfo removeService: ({ serviceGenericName, serviceUniqueName }) -> servicesOfType = @services[serviceGenericName] [index] = (i for s, i in servicesOfType \ when s.serviceUniqueName is serviceUniqueName) servicesOfType.splice index, 1 clientsByExchange = @clients.byExchange[serviceUniqueName] clientsByExchange?.forEach @bound 'cycleClient' cycleClient: (client) -> { routingKey } = client @bongo.respondToClient routingKey, method : 'cycleChannel' arguments : [] callbacks : {} removeClient: (rest...) -> if rest.length is 1 [client] = rest return @removeClient client.socketId, client.exchange, client.routingKey [socketId, exchange, routingKey] = rest delete @clients.bySocketId[socketId] delete @clients.byExchange[exchange] delete @clients.byRoutingKey[routingKey] addClient: (socketId, exchange, routingKey, sendOk = yes) -> if sendOk @bongo.respondToClient routingKey, method : 'auth.authOk' arguments : [] callbacks : {} clientsBySocketId = @clients.bySocketId[socketId] ?= [] clientsByExchange = @clients.byExchange[exchange] ?= [] clientsByRoutingKey = @clients.byRoutingKey[routingKey] ?= [] client = new AuthedClient { routingKey, socketId, exchange } clientsBySocketId.push client clientsByRoutingKey.push client clientsByExchange.push client rejectClient:(routingKey, message) -> # console.log 'rejecting', routingKey return console.trace() unless routingKey? @bongo.respondToClient routingKey, method : 'error' arguments : [{ message: message ? 'Access denied' }] callbacks : {} setSecretNames:(routingKey, publishingName, subscribingName) -> setSecretNamesEvent = "#{routingKey}.setSecretNames" message = JSON.stringify { publishingName, subscribingName } @bongo.respondToClient setSecretNamesEvent, message publishToService: (exchangeName, routingKey, payload, callback) -> { connection } = @bongo.mq connection.exchange exchangeName, AUTH_EXCHANGE_OPTIONS, (exchange) -> exchange.publish routingKey, payload exchange.close() # don't leak a channel callback? null getWaitingAuthWhoKey = (o) -> "#{o.username}!#{o.correlationName}!#{o.serviceGenericName}" makeExchangeFetcher = (exchangeName, exchangeOptions) -> exKey = "#{exchangeName}_" (callback) -> if @[exKey] then return process.nextTick => callback @[exKey] @bongo.mq.connection.exchange( @[exchangeName] exchangeOptions (exchange) => callback @[exKey] = exchange ).on 'error', console.error.bind console fetchReroutingExchange: makeExchangeFetcher( 'reroutingExchange', REROUTING_EXCHANGE_OPTIONS ) fetchNotificationExchange: makeExchangeFetcher( 'notificationExchange', NOTIFICATION_EXCHANGE_OPTIONS ) fetchUserPresenceControlExchange: makeExchangeFetcher( 'usersPresenceControlExchange', USERS_PRESENCE_CONTROL_EXCHANGE_OPTIONS ) addBinding:(bindingExchange, bindingKey, publishingExchange, routingKey, suffix = '') -> suffix = ".#{suffix}" if suffix.length @fetchReroutingExchange (exchange) -> exchange.publish 'auth.join', { bindingExchange bindingKey publishingExchange routingKey suffix } notify:(routingKey, event, contents) -> @fetchNotificationExchange (exchange) -> exchange.publish routingKey, { event, contents } respondServiceUnavailable: (routingKey, serviceGenericName) -> @bongo.respondToClient routingKey, method : 'error' arguments : [{ message : "Service unavailable! #{routingKey}" code :503 serviceGenericName }] callbacks : {} generateClient = (group, account) -> { context: { group: group.slug }, connection: { delegate: account } } join: do -> ensureGroupPermission = ({ group, account }, callback) -> { JGroup } = @bongo.models checkGroupPermission.call this, group, account, (err, hasPermission) -> if err then callback err else if hasPermission JGroup.fetchSecretChannelName group.slug, callback else callback { message: 'Access denied!', code: 403 } ensureSocialapiChannelPermission = ({ group, account, options }, callback) -> { SocialChannel } = @bongo.models checkGroupPermission.call this, group, account, (err, hasPermission) -> if err then callback err else if hasPermission client = generateClient group, account reqOptions = type: options.apiChannelType name: options.apiChannelName SocialChannel.checkChannelParticipation client, reqOptions, (err, res) -> if err console.warn """ tries to open an unattended channel: user: #{account.profile.nickname} channelname: #{reqOptions.name} channeltype: #{reqOptions.type} """ return callback err SocialChannel.fetchSecretChannelName options, callback else callback { message: 'Access denied!', code: 403 } checkGroupPermission = (group, account, callback) -> { JPermissionSet } = @bongo.models client = generateClient group, account JPermissionSet.checkPermission client, 'read group activity', group, null, callback joinGroupHelper = (messageData, routingKey, socketId) -> { JAccount, JGroup } = @bongo.models fail = (err) => console.error err if err @rejectClient routingKey @authenticate messageData, routingKey, socketId, (session) => unless session then fail() fetchAccountAndGroup.call this, session.username, messageData.group, (err, data) => return fail err if err { account, group } = data ensureGroupPermission.call this, { group, account }, (err, secretChannelName) => if err or not secretChannelName @rejectClient routingKey else handleSecretnameAndRoutingKey.call this, routingKey, secretChannelName handleSecretnameAndRoutingKey = (routingKey, secretChannelName) -> @addBinding 'broadcast', secretChannelName, 'broker', routingKey @setSecretNames routingKey, secretChannelName fetchAccountAndGroup = (username, groupSlug, callback) -> { JAccount, JGroup } = @bongo.models JAccount.one { 'profile.nickname': username }, (err, account) -> return callback err if err return callback { message: 'Account not found' } if not account JGroup.one { slug: groupSlug }, (err, group) -> return callback err if err return callback { message: 'Group not found' } if not group return callback null, { account, group } joinSocialApiHelper = (messageData, routingKey, socketId) -> { JAccount, JGroup, SocialChannel } = @bongo.models fail = (err) => console.error err if err @rejectClient routingKey @authenticate messageData, routingKey, socketId, (session) => return fail() unless session fetchAccountAndGroup.call this, session.username, messageData.group, (err, data) => return fail err if err { account, group } = data options = groupSlug : group.slug apiChannelType : messageData.channelType apiChannelName : messageData.channelName ensureSocialapiChannelPermission.call this, { group, account, options } , (err, secretChannelName) => return fail err if err unless secretChannelName return fail { message: 'secretChannelName not set' } handleSecretnameAndRoutingKey.call this, routingKey, secretChannelName joinNotificationHelper = (messageData, routingKey, socketId) -> fail = (err) => console.error err if err @rejectClient routingKey @authenticate messageData, routingKey, socketId, (session) => unless session then fail() else if session?.username @addClient socketId, @reroutingExchange, routingKey, no bindingKey = session.username @addBinding 'notification', bindingKey, 'broker', routingKey else @rejectClient routingKey joinChatHelper = (messageData, routingKey, socketId) -> { name } = messageData { JName } = @bongo.models fail = => @rejectClient routingKey @authenticate messageData, routingKey, socketId, (session) => return fail() unless session?.username? JName.fetchSecretName name, (err, secretChannelName) => return console.error err if err personalToken = 'PI:KEY:<KEY>END_PI' + do require 'hat' bindingKey = "PI:KEY:<KEY>END_PI}" consumerRoutingKey = "chatPI:KEY:<KEY>END_PI.#{secretChannelName}" { username } = session @addBinding 'chat', bindingKey, 'chat-hose', consumerRoutingKey, username @notify username, 'chatOpen', { publicName : name routingKey : personalToken bindingKey : consumerRoutingKey } joinClient = (messageData, socketId) -> { routingKey, brokerExchange, serviceType, wrapperRoutingKeyPrefix } = messageData switch serviceType when 'bongo' then # ignore when 'group' unless ///^group\.#{messageData.group}\.///.test routingKey return @rejectClient routingKey joinGroupHelper.call this, messageData, routingKey, socketId when 'socialapi' unless ///^socialapi\.///.test routingKey return @rejectClient routingKey joinSocialApiHelper.call this, messageData, routingKey, socketId when 'chat' joinChatHelper.call this, messageData, routingKey, socketId when 'notification' unless ///^notification\.///.test routingKey return @rejectClient routingKey joinNotificationHelper.call this, messageData, routingKey, socketId when 'secret' @addClient socketId, 'routing-control', wrapperRoutingKeyPrefix, no else @rejectClient routingKey unless /^oid./.test routingKey # TODO: we're not really handling the oid channels at all (I guess we don't need to) C.T. cleanUpClient: (client) -> @removeClient client @bongo.mq.connection.exchange client.exchange, AUTH_EXCHANGE_OPTIONS, (exchange) -> exchange.publish 'auth.leave', { routingKey: client.routingKey } exchange.close() # don't leak a channel! cleanUpAfterDisconnect: (socketId) -> @removeUserSocket socketId clientServices = @clients.bySocketId[socketId] clientServices?.forEach @bound 'cleanUpClient' connect: -> { bongo } = this bongo.on 'connected', => { connection } = bongo.mq # FIXME: this is a hack to hold the chat exchange open for the meantime connection.exchange 'chat', NOTIFICATION_EXCHANGE_OPTIONS, (chatExchange) -> # *chirp chirp chirp chirp* connection.exchange @authAllExchange, AUTH_EXCHANGE_OPTIONS, (authAllExchange) => connection.queue '', { exclusive:yes }, (authAllQueue) => authAllQueue.bind authAllExchange, '' authAllQueue.on 'queueBindOk', => authAllQueue.subscribe (message, headers, deliveryInfo) => { routingKey } = deliveryInfo messageStr = "#{message.data}" switch routingKey when 'broker.clientConnected' then # ignore when 'broker.clientDisconnected' @cleanUpAfterDisconnect messageStr connection.exchange @authExchange, AUTH_EXCHANGE_OPTIONS, (authExchange) => connection.queue @authExchange, (authQueue) => authQueue.bind authExchange, '' authQueue.on 'queueBindOk', => authQueue.subscribe (message, headers, deliveryInfo) => { routingKey, correlationId } = deliveryInfo socketId = correlationId messageStr = "#{message.data}" messageData = (try JSON.parse messageStr) or message switch routingKey when "client.#{@authExchange}" @join messageData, socketId else @rejectClient routingKey
[ { "context": " -> getPlayer(\"location\").x +=1 )\n\n if key == 115 && getPlayer(\"location\").y < getMap(\"mapSize\").y ", "end": 1755, "score": 0.7195940017700195, "start": 1753, "tag": "KEY", "value": "15" }, { "context": "-> getPlayer(\"location\").y -=1 )\n\n if key == 100...
pixel-colision/script.coffee
FelixLuciano/arquivo
0
$ -> obstacles = [ "5 3" ] getMap = ( info ) -> if info return $("#warzone").data( info ) else return $("#warzone") $.each obstacles, ( i ) -> createObstacle = ( x, y ) -> return "<div class='obstacle' style='margin-left: #{x}px;margin-top: #{y}px;'></div>" getObstaclePos = obstacles[i].split(" ") getMap() .prepend createObstacle( Number( getObstaclePos[0] ) * 50, Number( getObstaclePos[1] ) * 50 ) $ ".obstacle:nth-child(1)" .data "location", { x: Number( getObstaclePos[0] ) y: Number( getObstaclePos[1] ) } getPlayer = ( info ) -> if info return $("#player").data( info ) else return $("#player") locationUpdate = -> getPlayer() .css { marginLeft: getPlayer("location").x * 50 marginTop: getPlayer("location").y * 50 } createMap = ( width, height ) -> getMap() .css { width: width * 50 height: height * 50 } .data "mapSize", { x: width, y: height } getPlayer() .data "location", { x: 0, y: 0 } createMap( 11, 7 ) $( document ).keypress ( e ) -> key = e.which getIfObstacle = ( action )-> $("*.obstacle").each -> if getPlayer("location").y == $( this ).data("location").y && getPlayer("location").x == $( this ).data("location").x action() locationUpdate() return false if key == 119 && getPlayer("location").y > 0 getPlayer("location").y -=1 locationUpdate() getIfObstacle( -> getPlayer("location").y +=1 ) if key == 97 && getPlayer("location").x > 0 getPlayer("location").x -=1 locationUpdate() getIfObstacle( -> getPlayer("location").x +=1 ) if key == 115 && getPlayer("location").y < getMap("mapSize").y - 1 getPlayer("location").y +=1 locationUpdate() getIfObstacle( -> getPlayer("location").y -=1 ) if key == 100 && getPlayer("location").x < getMap("mapSize").x - 1 getPlayer("location").x +=1 locationUpdate() getIfObstacle( -> getPlayer("location").x -=1 )
155795
$ -> obstacles = [ "5 3" ] getMap = ( info ) -> if info return $("#warzone").data( info ) else return $("#warzone") $.each obstacles, ( i ) -> createObstacle = ( x, y ) -> return "<div class='obstacle' style='margin-left: #{x}px;margin-top: #{y}px;'></div>" getObstaclePos = obstacles[i].split(" ") getMap() .prepend createObstacle( Number( getObstaclePos[0] ) * 50, Number( getObstaclePos[1] ) * 50 ) $ ".obstacle:nth-child(1)" .data "location", { x: Number( getObstaclePos[0] ) y: Number( getObstaclePos[1] ) } getPlayer = ( info ) -> if info return $("#player").data( info ) else return $("#player") locationUpdate = -> getPlayer() .css { marginLeft: getPlayer("location").x * 50 marginTop: getPlayer("location").y * 50 } createMap = ( width, height ) -> getMap() .css { width: width * 50 height: height * 50 } .data "mapSize", { x: width, y: height } getPlayer() .data "location", { x: 0, y: 0 } createMap( 11, 7 ) $( document ).keypress ( e ) -> key = e.which getIfObstacle = ( action )-> $("*.obstacle").each -> if getPlayer("location").y == $( this ).data("location").y && getPlayer("location").x == $( this ).data("location").x action() locationUpdate() return false if key == 119 && getPlayer("location").y > 0 getPlayer("location").y -=1 locationUpdate() getIfObstacle( -> getPlayer("location").y +=1 ) if key == 97 && getPlayer("location").x > 0 getPlayer("location").x -=1 locationUpdate() getIfObstacle( -> getPlayer("location").x +=1 ) if key == 1<KEY> && getPlayer("location").y < getMap("mapSize").y - 1 getPlayer("location").y +=1 locationUpdate() getIfObstacle( -> getPlayer("location").y -=1 ) if key == 10<KEY> && getPlayer("location").x < getMap("mapSize").x - 1 getPlayer("location").x +=1 locationUpdate() getIfObstacle( -> getPlayer("location").x -=1 )
true
$ -> obstacles = [ "5 3" ] getMap = ( info ) -> if info return $("#warzone").data( info ) else return $("#warzone") $.each obstacles, ( i ) -> createObstacle = ( x, y ) -> return "<div class='obstacle' style='margin-left: #{x}px;margin-top: #{y}px;'></div>" getObstaclePos = obstacles[i].split(" ") getMap() .prepend createObstacle( Number( getObstaclePos[0] ) * 50, Number( getObstaclePos[1] ) * 50 ) $ ".obstacle:nth-child(1)" .data "location", { x: Number( getObstaclePos[0] ) y: Number( getObstaclePos[1] ) } getPlayer = ( info ) -> if info return $("#player").data( info ) else return $("#player") locationUpdate = -> getPlayer() .css { marginLeft: getPlayer("location").x * 50 marginTop: getPlayer("location").y * 50 } createMap = ( width, height ) -> getMap() .css { width: width * 50 height: height * 50 } .data "mapSize", { x: width, y: height } getPlayer() .data "location", { x: 0, y: 0 } createMap( 11, 7 ) $( document ).keypress ( e ) -> key = e.which getIfObstacle = ( action )-> $("*.obstacle").each -> if getPlayer("location").y == $( this ).data("location").y && getPlayer("location").x == $( this ).data("location").x action() locationUpdate() return false if key == 119 && getPlayer("location").y > 0 getPlayer("location").y -=1 locationUpdate() getIfObstacle( -> getPlayer("location").y +=1 ) if key == 97 && getPlayer("location").x > 0 getPlayer("location").x -=1 locationUpdate() getIfObstacle( -> getPlayer("location").x +=1 ) if key == 1PI:KEY:<KEY>END_PI && getPlayer("location").y < getMap("mapSize").y - 1 getPlayer("location").y +=1 locationUpdate() getIfObstacle( -> getPlayer("location").y -=1 ) if key == 10PI:KEY:<KEY>END_PI && getPlayer("location").x < getMap("mapSize").x - 1 getPlayer("location").x +=1 locationUpdate() getIfObstacle( -> getPlayer("location").x -=1 )
[ { "context": "names.\n#\n# Dotted notation: Key row (0) containing firstName, lastName, address.street, \n# address.city, addre", "end": 367, "score": 0.992647647857666, "start": 358, "tag": "NAME", "value": "firstName" }, { "context": "Dotted notation: Key row (0) containing firstNa...
src/excel-as-json.coffee
alexander-e-andrews/excel-as-json
0
# Create a list of json objects; 1 object per excel sheet row # # Assume: Excel spreadsheet is a rectangle of data, where the first row is # object keys and remaining rows are object values and the desired json # is a list of objects. Alternatively, data may be column oriented with # col 0 containing key names. # # Dotted notation: Key row (0) containing firstName, lastName, address.street, # address.city, address.state, address.zip would produce, per row, a doc with # first and last names and an embedded doc named address, with the address. # # Arrays: may be indexed (phones[0].number) or flat (aliases[]). Indexed # arrays imply a list of objects. Flat arrays imply a semicolon delimited list. # # USE: # From a shell # coffee src/excel-as-json.coffee # fs = require 'fs' path = require 'path' excel = require 'excel' BOOLTEXT = ['true', 'false'] BOOLVALS = {'true': true, 'false': false} isArray = (obj) -> Object.prototype.toString.call(obj) is '[object Array]' # Extract key name and array index from names[1] or names[] # return [keyIsList, keyName, index] # for names[1] return [true, keyName, index] # for names[] return [true, keyName, undefined] # for names return [false, keyName, undefined] parseKeyName = (key) -> index = key.match(/\[(\d+)\]$/) switch when index then [true, key.split('[')[0], Number(index[1])] when key[-2..] is '[]' then [true, key[...-2], undefined] else [false, key, undefined] # Convert a list of values to a list of more native forms convertValueList = (list, options) -> (convertValue(item, options) for item in list) # Convert values to native types # Note: all values from the excel module are text convertValue = (value, options) -> # isFinite returns true for empty or blank strings, check for those first if value.length == 0 || !/\S/.test(value) value else if isFinite(value) if options.convertTextToNumber Number(value) else value else testVal = value.toLowerCase() if testVal in BOOLTEXT BOOLVALS[testVal] else value # Assign a value to a dotted property key - set values on sub-objects assign = (obj, key, value, options) -> # On first call, a key is a string. Recursed calls, a key is an array key = key.split '.' unless typeof key is 'object' # Array element accessors look like phones[0].type or aliases[] [keyIsList, keyName, index] = parseKeyName key.shift() if key.length if keyIsList # if our object is already an array, ensure an object exists for this index if isArray obj[keyName] unless obj[keyName][index] obj[keyName].push({}) for i in [obj[keyName].length..index] # else set this value to an array large enough to contain this index else obj[keyName] = ({} for i in [0..index]) assign obj[keyName][index], key, value, options else obj[keyName] ?= {} assign obj[keyName], key, value, options else if keyIsList and index? console.error "WARNING: Unexpected key path terminal containing an indexed list for <#{keyName}>" console.error "WARNING: Indexed arrays indicate a list of objects and should not be the last element in a key path" console.error "WARNING: The last element of a key path should be a key name or flat array. E.g. alias, aliases[]" if (keyIsList and not index?) if value != '' obj[keyName] = convertValueList(value.split(';'), options) else if !options.omitEmptyFields obj[keyName] = [] else if !(options.omitEmptyFields && value == '') obj[keyName] = convertValue(value, options) # Transpose a 2D array transpose = (matrix) -> (t[i] for t in matrix) for i in [0...matrix[0].length] # Convert 2D array to nested objects. If row oriented data, row 0 is dotted key names. # Column oriented data is transposed convert = (data, options) -> data = transpose data if options.isColOriented keys = data[0] rows = data[1..] result = [] for row in rows item = {} assign(item, keys[index], value, options) for value, index in row result.push item return result # Write JSON encoded data to file # call back is callback(err) write = (data, dst, callback) -> # Create the target directory if it does not exist dir = path.dirname(dst) fs.mkdirSync dir if !fs.existsSync(dir) fs.writeFile dst, JSON.stringify(data, null, 2), (err) -> if err then callback "Error writing file #{dst}: #{err}" else callback undefined # src: xlsx file that we will read sheet 0 of # dst: file path to write json to. If null, simply return the result # options: see below # callback(err, data): callback for completion notification # # options: # sheet: string; 1: numeric, 1-based index of target sheet # isColOriented: boolean: false; are objects stored in excel columns; key names in col A # omitEmptyFields: boolean: false: do not include keys with empty values in json output. empty values are stored as '' # TODO: this is probably better named omitKeysWithEmptyValues # convertTextToNumber boolean: true; if text looks like a number, convert it to a number # # convertExcel(src, dst) <br/> # will write a row oriented xlsx sheet 1 to `dst` as JSON with no notification # convertExcel(src, dst, {isColOriented: true}) <br/> # will write a col oriented xlsx sheet 1 to file with no notification # convertExcel(src, dst, {isColOriented: true}, callback) <br/> # will write a col oriented xlsx to file and notify with errors and parsed data # convertExcel(src, null, null, callback) <br/> # will parse a row oriented xslx using default options and return errors and the parsed data in the callback # _DEFAULT_OPTIONS = sheet: '1' isColOriented: false omitEmptyFields: false convertTextToNumber: true # Ensure options sane, provide defaults as appropriate _validateOptions = (options) -> if !options options = _DEFAULT_OPTIONS else if !options.hasOwnProperty('sheet') options.sheet = '1' else # ensure sheet is a text representation of a number if !isNaN(parseFloat(options.sheet)) && isFinite(options.sheet) if options.sheet < 1 options.sheet = '1' else # could be 3 or '3'; force to be '3' options.sheet = '' + options.sheet else # something bizarre like true, [Function: isNaN], etc options.sheet = '1' if !options.hasOwnProperty('isColOriented') options.isColOriented = false if !options.hasOwnProperty('omitEmptyFields') options.omitEmptyFields = false if !options.hasOwnProperty('convertTextToNumber') options.convertTextToNumber = true options processWorksheet = (data, dst, options=_DEFAULT_OPTIONS, callback=undefined) -> options = _validateOptions(options) # provide a callback if the user did not if !callback then callback = (err, data) -> result = convert data, options if dst write result, dst, (err) -> if err then callback err else callback undefined, result else callback undefined, result processFile = (src, dst, options=_DEFAULT_OPTIONS, callback=undefined) -> options = _validateOptions(options) # provide a callback if the user did not if !callback then callback = (err, data) -> # NOTE: 'excel' does not properly bubble file not found and prints # an ugly error we can't trap, so look for this common error first if not fs.existsSync src callback "Cannot find src file #{src}" else excel src, options.sheet, (err, data) -> if err callback "Error reading #{src}: #{err}" else result = convert data, options if dst write result, dst, (err) -> if err then callback err else callback undefined, result else callback undefined, result # This is the single expected module entry point exports.processFile = processFile # Unsupported use # Exposing remaining functionality for unexpected use cases, testing, etc. exports.assign = assign exports.convert = convert exports.convertValue = convertValue exports.parseKeyName = parseKeyName exports._validateOptions = _validateOptions exports.transpose = transpose
87259
# Create a list of json objects; 1 object per excel sheet row # # Assume: Excel spreadsheet is a rectangle of data, where the first row is # object keys and remaining rows are object values and the desired json # is a list of objects. Alternatively, data may be column oriented with # col 0 containing key names. # # Dotted notation: Key row (0) containing <NAME>, <NAME>, address.street, # address.city, address.state, address.zip would produce, per row, a doc with # first and last names and an embedded doc named address, with the address. # # Arrays: may be indexed (phones[0].number) or flat (aliases[]). Indexed # arrays imply a list of objects. Flat arrays imply a semicolon delimited list. # # USE: # From a shell # coffee src/excel-as-json.coffee # fs = require 'fs' path = require 'path' excel = require 'excel' BOOLTEXT = ['true', 'false'] BOOLVALS = {'true': true, 'false': false} isArray = (obj) -> Object.prototype.toString.call(obj) is '[object Array]' # Extract key name and array index from names[1] or names[] # return [keyIsList, keyName, index] # for names[1] return [true, keyName, index] # for names[] return [true, keyName, undefined] # for names return [false, keyName, undefined] parseKeyName = (key) -> index = key.match(/\[(\d+)\]$/) switch when index then [true, key.split('[')[0], Number(index[1])] when key[-2..] is '[]' then [true, key[...-2], undefined] else [false, key, undefined] # Convert a list of values to a list of more native forms convertValueList = (list, options) -> (convertValue(item, options) for item in list) # Convert values to native types # Note: all values from the excel module are text convertValue = (value, options) -> # isFinite returns true for empty or blank strings, check for those first if value.length == 0 || !/\S/.test(value) value else if isFinite(value) if options.convertTextToNumber Number(value) else value else testVal = value.toLowerCase() if testVal in BOOLTEXT BOOLVALS[testVal] else value # Assign a value to a dotted property key - set values on sub-objects assign = (obj, key, value, options) -> # On first call, a key is a string. Recursed calls, a key is an array key = key.split '.' unless typeof key is 'object' # Array element accessors look like phones[0].type or aliases[] [keyIsList, keyName, index] = parseKeyName key.shift() if key.length if keyIsList # if our object is already an array, ensure an object exists for this index if isArray obj[keyName] unless obj[keyName][index] obj[keyName].push({}) for i in [obj[keyName].length..index] # else set this value to an array large enough to contain this index else obj[keyName] = ({} for i in [0..index]) assign obj[keyName][index], key, value, options else obj[keyName] ?= {} assign obj[keyName], key, value, options else if keyIsList and index? console.error "WARNING: Unexpected key path terminal containing an indexed list for <#{keyName}>" console.error "WARNING: Indexed arrays indicate a list of objects and should not be the last element in a key path" console.error "WARNING: The last element of a key path should be a key name or flat array. E.g. alias, aliases[]" if (keyIsList and not index?) if value != '' obj[keyName] = convertValueList(value.split(';'), options) else if !options.omitEmptyFields obj[keyName] = [] else if !(options.omitEmptyFields && value == '') obj[keyName] = convertValue(value, options) # Transpose a 2D array transpose = (matrix) -> (t[i] for t in matrix) for i in [0...matrix[0].length] # Convert 2D array to nested objects. If row oriented data, row 0 is dotted key names. # Column oriented data is transposed convert = (data, options) -> data = transpose data if options.isColOriented keys = data[0] rows = data[1..] result = [] for row in rows item = {} assign(item, keys[index], value, options) for value, index in row result.push item return result # Write JSON encoded data to file # call back is callback(err) write = (data, dst, callback) -> # Create the target directory if it does not exist dir = path.dirname(dst) fs.mkdirSync dir if !fs.existsSync(dir) fs.writeFile dst, JSON.stringify(data, null, 2), (err) -> if err then callback "Error writing file #{dst}: #{err}" else callback undefined # src: xlsx file that we will read sheet 0 of # dst: file path to write json to. If null, simply return the result # options: see below # callback(err, data): callback for completion notification # # options: # sheet: string; 1: numeric, 1-based index of target sheet # isColOriented: boolean: false; are objects stored in excel columns; key names in col A # omitEmptyFields: boolean: false: do not include keys with empty values in json output. empty values are stored as '' # TODO: this is probably better named omitKeysWithEmptyValues # convertTextToNumber boolean: true; if text looks like a number, convert it to a number # # convertExcel(src, dst) <br/> # will write a row oriented xlsx sheet 1 to `dst` as JSON with no notification # convertExcel(src, dst, {isColOriented: true}) <br/> # will write a col oriented xlsx sheet 1 to file with no notification # convertExcel(src, dst, {isColOriented: true}, callback) <br/> # will write a col oriented xlsx to file and notify with errors and parsed data # convertExcel(src, null, null, callback) <br/> # will parse a row oriented xslx using default options and return errors and the parsed data in the callback # _DEFAULT_OPTIONS = sheet: '1' isColOriented: false omitEmptyFields: false convertTextToNumber: true # Ensure options sane, provide defaults as appropriate _validateOptions = (options) -> if !options options = _DEFAULT_OPTIONS else if !options.hasOwnProperty('sheet') options.sheet = '1' else # ensure sheet is a text representation of a number if !isNaN(parseFloat(options.sheet)) && isFinite(options.sheet) if options.sheet < 1 options.sheet = '1' else # could be 3 or '3'; force to be '3' options.sheet = '' + options.sheet else # something bizarre like true, [Function: isNaN], etc options.sheet = '1' if !options.hasOwnProperty('isColOriented') options.isColOriented = false if !options.hasOwnProperty('omitEmptyFields') options.omitEmptyFields = false if !options.hasOwnProperty('convertTextToNumber') options.convertTextToNumber = true options processWorksheet = (data, dst, options=_DEFAULT_OPTIONS, callback=undefined) -> options = _validateOptions(options) # provide a callback if the user did not if !callback then callback = (err, data) -> result = convert data, options if dst write result, dst, (err) -> if err then callback err else callback undefined, result else callback undefined, result processFile = (src, dst, options=_DEFAULT_OPTIONS, callback=undefined) -> options = _validateOptions(options) # provide a callback if the user did not if !callback then callback = (err, data) -> # NOTE: 'excel' does not properly bubble file not found and prints # an ugly error we can't trap, so look for this common error first if not fs.existsSync src callback "Cannot find src file #{src}" else excel src, options.sheet, (err, data) -> if err callback "Error reading #{src}: #{err}" else result = convert data, options if dst write result, dst, (err) -> if err then callback err else callback undefined, result else callback undefined, result # This is the single expected module entry point exports.processFile = processFile # Unsupported use # Exposing remaining functionality for unexpected use cases, testing, etc. exports.assign = assign exports.convert = convert exports.convertValue = convertValue exports.parseKeyName = parseKeyName exports._validateOptions = _validateOptions exports.transpose = transpose
true
# Create a list of json objects; 1 object per excel sheet row # # Assume: Excel spreadsheet is a rectangle of data, where the first row is # object keys and remaining rows are object values and the desired json # is a list of objects. Alternatively, data may be column oriented with # col 0 containing key names. # # Dotted notation: Key row (0) containing PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, address.street, # address.city, address.state, address.zip would produce, per row, a doc with # first and last names and an embedded doc named address, with the address. # # Arrays: may be indexed (phones[0].number) or flat (aliases[]). Indexed # arrays imply a list of objects. Flat arrays imply a semicolon delimited list. # # USE: # From a shell # coffee src/excel-as-json.coffee # fs = require 'fs' path = require 'path' excel = require 'excel' BOOLTEXT = ['true', 'false'] BOOLVALS = {'true': true, 'false': false} isArray = (obj) -> Object.prototype.toString.call(obj) is '[object Array]' # Extract key name and array index from names[1] or names[] # return [keyIsList, keyName, index] # for names[1] return [true, keyName, index] # for names[] return [true, keyName, undefined] # for names return [false, keyName, undefined] parseKeyName = (key) -> index = key.match(/\[(\d+)\]$/) switch when index then [true, key.split('[')[0], Number(index[1])] when key[-2..] is '[]' then [true, key[...-2], undefined] else [false, key, undefined] # Convert a list of values to a list of more native forms convertValueList = (list, options) -> (convertValue(item, options) for item in list) # Convert values to native types # Note: all values from the excel module are text convertValue = (value, options) -> # isFinite returns true for empty or blank strings, check for those first if value.length == 0 || !/\S/.test(value) value else if isFinite(value) if options.convertTextToNumber Number(value) else value else testVal = value.toLowerCase() if testVal in BOOLTEXT BOOLVALS[testVal] else value # Assign a value to a dotted property key - set values on sub-objects assign = (obj, key, value, options) -> # On first call, a key is a string. Recursed calls, a key is an array key = key.split '.' unless typeof key is 'object' # Array element accessors look like phones[0].type or aliases[] [keyIsList, keyName, index] = parseKeyName key.shift() if key.length if keyIsList # if our object is already an array, ensure an object exists for this index if isArray obj[keyName] unless obj[keyName][index] obj[keyName].push({}) for i in [obj[keyName].length..index] # else set this value to an array large enough to contain this index else obj[keyName] = ({} for i in [0..index]) assign obj[keyName][index], key, value, options else obj[keyName] ?= {} assign obj[keyName], key, value, options else if keyIsList and index? console.error "WARNING: Unexpected key path terminal containing an indexed list for <#{keyName}>" console.error "WARNING: Indexed arrays indicate a list of objects and should not be the last element in a key path" console.error "WARNING: The last element of a key path should be a key name or flat array. E.g. alias, aliases[]" if (keyIsList and not index?) if value != '' obj[keyName] = convertValueList(value.split(';'), options) else if !options.omitEmptyFields obj[keyName] = [] else if !(options.omitEmptyFields && value == '') obj[keyName] = convertValue(value, options) # Transpose a 2D array transpose = (matrix) -> (t[i] for t in matrix) for i in [0...matrix[0].length] # Convert 2D array to nested objects. If row oriented data, row 0 is dotted key names. # Column oriented data is transposed convert = (data, options) -> data = transpose data if options.isColOriented keys = data[0] rows = data[1..] result = [] for row in rows item = {} assign(item, keys[index], value, options) for value, index in row result.push item return result # Write JSON encoded data to file # call back is callback(err) write = (data, dst, callback) -> # Create the target directory if it does not exist dir = path.dirname(dst) fs.mkdirSync dir if !fs.existsSync(dir) fs.writeFile dst, JSON.stringify(data, null, 2), (err) -> if err then callback "Error writing file #{dst}: #{err}" else callback undefined # src: xlsx file that we will read sheet 0 of # dst: file path to write json to. If null, simply return the result # options: see below # callback(err, data): callback for completion notification # # options: # sheet: string; 1: numeric, 1-based index of target sheet # isColOriented: boolean: false; are objects stored in excel columns; key names in col A # omitEmptyFields: boolean: false: do not include keys with empty values in json output. empty values are stored as '' # TODO: this is probably better named omitKeysWithEmptyValues # convertTextToNumber boolean: true; if text looks like a number, convert it to a number # # convertExcel(src, dst) <br/> # will write a row oriented xlsx sheet 1 to `dst` as JSON with no notification # convertExcel(src, dst, {isColOriented: true}) <br/> # will write a col oriented xlsx sheet 1 to file with no notification # convertExcel(src, dst, {isColOriented: true}, callback) <br/> # will write a col oriented xlsx to file and notify with errors and parsed data # convertExcel(src, null, null, callback) <br/> # will parse a row oriented xslx using default options and return errors and the parsed data in the callback # _DEFAULT_OPTIONS = sheet: '1' isColOriented: false omitEmptyFields: false convertTextToNumber: true # Ensure options sane, provide defaults as appropriate _validateOptions = (options) -> if !options options = _DEFAULT_OPTIONS else if !options.hasOwnProperty('sheet') options.sheet = '1' else # ensure sheet is a text representation of a number if !isNaN(parseFloat(options.sheet)) && isFinite(options.sheet) if options.sheet < 1 options.sheet = '1' else # could be 3 or '3'; force to be '3' options.sheet = '' + options.sheet else # something bizarre like true, [Function: isNaN], etc options.sheet = '1' if !options.hasOwnProperty('isColOriented') options.isColOriented = false if !options.hasOwnProperty('omitEmptyFields') options.omitEmptyFields = false if !options.hasOwnProperty('convertTextToNumber') options.convertTextToNumber = true options processWorksheet = (data, dst, options=_DEFAULT_OPTIONS, callback=undefined) -> options = _validateOptions(options) # provide a callback if the user did not if !callback then callback = (err, data) -> result = convert data, options if dst write result, dst, (err) -> if err then callback err else callback undefined, result else callback undefined, result processFile = (src, dst, options=_DEFAULT_OPTIONS, callback=undefined) -> options = _validateOptions(options) # provide a callback if the user did not if !callback then callback = (err, data) -> # NOTE: 'excel' does not properly bubble file not found and prints # an ugly error we can't trap, so look for this common error first if not fs.existsSync src callback "Cannot find src file #{src}" else excel src, options.sheet, (err, data) -> if err callback "Error reading #{src}: #{err}" else result = convert data, options if dst write result, dst, (err) -> if err then callback err else callback undefined, result else callback undefined, result # This is the single expected module entry point exports.processFile = processFile # Unsupported use # Exposing remaining functionality for unexpected use cases, testing, etc. exports.assign = assign exports.convert = convert exports.convertValue = convertValue exports.parseKeyName = parseKeyName exports._validateOptions = _validateOptions exports.transpose = transpose
[ { "context": "obj?\n @username = if obj.hasOwnProperty('username') then obj.username else null\n @email ", "end": 292, "score": 0.9913027286529541, "start": 284, "tag": "USERNAME", "value": "username" }, { "context": "obj?\n @username = if obj.hasOwnPrope...
client/app/factory/userFactory.coffee
chriscx/Fluid
0
angular.module('Users').factory 'User', ($http, $location, $window, AuthenticationService) -> class User # # Constructor: if is not set by the server, it will be overwritten on save # constructor: (obj) -> if obj? @username = if obj.hasOwnProperty('username') then obj.username else null @email = if obj.hasOwnProperty('email') then obj.email else null @password = if obj.hasOwnProperty('password') then obj.password else null @firstname = if obj.hasOwnProperty('firstname') then obj.firstname else null @lastname = if obj.hasOwnProperty('lastname') then obj.lastname else null set: (obj) -> if obj? @username = if obj.hasOwnProperty('username') then obj.username else null @email = if obj.hasOwnProperty('email') then obj.email else null @password = if obj.hasOwnProperty('password') then obj.password else null @firstname = if obj.hasOwnProperty('firstname') then obj.firstname else null @lastname = if obj.hasOwnProperty('lastname') then obj.lastname else null getInfo: -> username: @username email: @email firstname: @firstname lastname: @lastname get: (attribute) -> if @.hasOwnProperty(attribute) and attribute != 'password' then @[attribute] else null
188453
angular.module('Users').factory 'User', ($http, $location, $window, AuthenticationService) -> class User # # Constructor: if is not set by the server, it will be overwritten on save # constructor: (obj) -> if obj? @username = if obj.hasOwnProperty('username') then obj.username else null @email = if obj.hasOwnProperty('email') then obj.email else null @password = if obj.hasOwnProperty('password') then obj.password else null @firstname = if obj.hasOwnProperty('firstname') then obj.firstname else null @lastname = if obj.hasOwnProperty('lastname') then obj.lastname else null set: (obj) -> if obj? @username = if obj.hasOwnProperty('username') then obj.username else null @email = if obj.hasOwnProperty('email') then obj.email else null @password = if obj.hasOwnProperty('<PASSWORD>') then <PASSWORD> else <PASSWORD> @firstname = if obj.hasOwnProperty('firstname') then obj.firstname else null @lastname = if obj.hasOwnProperty('lastname') then obj.lastname else null getInfo: -> username: @username email: @email firstname: @firstname lastname: @lastname get: (attribute) -> if @.hasOwnProperty(attribute) and attribute != 'password' then @[attribute] else null
true
angular.module('Users').factory 'User', ($http, $location, $window, AuthenticationService) -> class User # # Constructor: if is not set by the server, it will be overwritten on save # constructor: (obj) -> if obj? @username = if obj.hasOwnProperty('username') then obj.username else null @email = if obj.hasOwnProperty('email') then obj.email else null @password = if obj.hasOwnProperty('password') then obj.password else null @firstname = if obj.hasOwnProperty('firstname') then obj.firstname else null @lastname = if obj.hasOwnProperty('lastname') then obj.lastname else null set: (obj) -> if obj? @username = if obj.hasOwnProperty('username') then obj.username else null @email = if obj.hasOwnProperty('email') then obj.email else null @password = if obj.hasOwnProperty('PI:PASSWORD:<PASSWORD>END_PI') then PI:PASSWORD:<PASSWORD>END_PI else PI:PASSWORD:<PASSWORD>END_PI @firstname = if obj.hasOwnProperty('firstname') then obj.firstname else null @lastname = if obj.hasOwnProperty('lastname') then obj.lastname else null getInfo: -> username: @username email: @email firstname: @firstname lastname: @lastname get: (attribute) -> if @.hasOwnProperty(attribute) and attribute != 'password' then @[attribute] else null
[ { "context": "Edition Core Set': [\n {\n name: 'X-Wing'\n type: 'ship'\n count: 1\n ", "end": 849, "score": 0.9997711181640625, "start": 843, "tag": "NAME", "value": "X-Wing" }, { "context": " count: 1\n }\n {\n name:...
coffeescripts/manifest.coffee
whaleberg/xwing
0
exportObj = exports ? this String::startsWith ?= (t) -> @indexOf t == 0 sortWithoutQuotes = (a, b, type = '') -> a_name = displayName(a,type).replace /[^a-z0-9]/ig, '' b_name = displayName(b,type).replace /[^a-z0-9]/ig, '' if a_name < b_name -1 else if a_name > b_name 1 else 0 displayName = (name, type) -> obj = undefined if type == 'ship' obj = exportObj.ships[name] else if type == 'upgrade' obj = exportObj.upgrades[name] else if type == 'pilot' obj = exportObj.pilots[name] else return name if obj and obj.display_name return obj.display_name return name exportObj.manifestBySettings = 'collectioncheck': true exportObj.manifestByExpansion = 'Second Edition Core Set': [ { name: 'X-Wing' type: 'ship' count: 1 } { name: 'TIE Fighter' type: 'ship' count: 2 } { name: 'Luke Skywalker' type: 'pilot' count: 1 } { name: 'Jek Porkins' type: 'pilot' count: 1 } { name: 'Red Squadron Veteran' type: 'pilot' count: 1 } { name: 'Blue Squadron Escort' type: 'pilot' count: 1 } { name: 'Iden Versio' type: 'pilot' count: 1 } { name: 'Valen Rudor' type: 'pilot' count: 1 } { name: 'Black Squadron Ace' type: 'pilot' count: 2 } { name: '"Night Beast"' type: 'pilot' count: 1 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 2 } { name: 'Academy Pilot' type: 'pilot' count: 2 } { name: 'Elusive' type: 'upgrade' count: 1 } { name: 'Outmaneuver' type: 'upgrade' count: 1 } { name: 'Predator' type: 'upgrade' count: 1 } { name: 'Heightened Perception' type: 'upgrade' count: 2 } { name: 'Instinctive Aim' type: 'upgrade' count: 1 } { name: 'Sense' type: 'upgrade' count: 2 } { name: 'Supernatural Reflexes' type: 'upgrade' count: 2 } { name: 'Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 1 } { name: 'R2-D2' type: 'upgrade' count: 1 } { name: 'R3 Astromech' type: 'upgrade' count: 1 } { name: 'R5 Astromech' type: 'upgrade' count: 1 } { name: 'R5-D8' type: 'upgrade' count: 1 } { name: 'Servomotor S-Foils' type: 'upgrade' count: 1 } { name: 'Afterburners' type: 'upgrade' count: 1 } { name: 'Hull Upgrade' type: 'upgrade' count: 1 } { name: 'Shield Upgrade' type: 'upgrade' count: 1 } ] "Saw's Renegades Expansion Pack" : [ { name: 'U-Wing' type: 'ship' count: 1 } { name: 'X-Wing' type: 'ship' count: 1 } { name: 'Saw Gerrera' type: 'pilot' count: 1 } { name: 'Magva Yarro' type: 'pilot' count: 1 } { name: 'Benthic Two Tubes' type: 'pilot' count: 1 } { name: 'Partisan Renegade' type: 'pilot' count: 1 } { name: 'Kullbee Sperado' type: 'pilot' count: 1 } { name: 'Leevan Tenza' type: 'pilot' count: 1 } { name: 'Edrio Two Tubes' type: 'pilot' count: 1 } { name: 'Cavern Angels Zealot' type: 'pilot' count: 3 } { name: 'R3 Astromech' type: 'upgrade' count: 1 } { name: 'R4 Astromech' type: 'upgrade' count: 1 } { name: 'Saw Gerrera' type: 'upgrade' count: 1 } { name: 'Magva Yarro' type: 'upgrade' count: 1 } { name: 'Pivot Wing' type: 'upgrade' count: 1 } { name: 'Servomotor S-Foils' type: 'upgrade' count: 1 } { name: "Deadman's Switch" type: 'upgrade' count: 2 } { name: 'Advanced Sensors' type: 'upgrade' count: 1 } { name: 'Trick Shot' type: 'upgrade' count: 2 } { name: 'Proton Torpedoes' type: 'upgrade' count: 1 } ] 'TIE Reaper Expansion Pack' : [ { name: 'TIE Reaper' type: 'ship' count: 1 } { name: 'Major Vermeil' type: 'pilot' count: 1 } { name: 'Captain Feroph' type: 'pilot' count: 1 } { name: '"Vizier"' type: 'pilot' count: 1 } { name: 'Scarif Base Pilot' type: 'pilot' count: 1 } { name: 'Director Krennic' type: 'upgrade' count: 1 } { name: 'Death Troopers' type: 'upgrade' count: 1 } { name: 'ISB Slicer' type: 'upgrade' count: 2 } { name: 'Tactical Officer' type: 'upgrade' count: 2 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: 'Juke' type: 'upgrade' count: 2 } ] 'Rebel Alliance Conversion Kit': [ { name: 'Thane Kyrell' type: 'pilot' count: 1 } { name: 'Norra Wexley (Y-Wing)' type: 'pilot' count: 1 } { name: 'Evaan Verlaine' type: 'pilot' count: 1 } { name: 'Biggs Darklighter' type: 'pilot' count: 1 } { name: 'Garven Dreis (X-Wing)' type: 'pilot' count: 1 } { name: 'Wedge Antilles' type: 'pilot' count: 1 } { name: 'Blue Squadron Escort' type: 'pilot' count: 2 } { name: 'Red Squadron Veteran' type: 'pilot' count: 2 } { name: '"Dutch" Vander' type: 'pilot' count: 1 } { name: 'Horton Salm' type: 'pilot' count: 1 } { name: 'Gold Squadron Veteran' type: 'pilot' count: 2 } { name: 'Gray Squadron Bomber' type: 'pilot' count: 2 } { name: 'Arvel Crynyd' type: 'pilot' count: 1 } { name: 'Jake Farrell' type: 'pilot' count: 1 } { name: 'Green Squadron Pilot' type: 'pilot' count: 2 } { name: 'Phoenix Squadron Pilot' type: 'pilot' count: 2 } { name: 'Braylen Stramm' type: 'pilot' count: 1 } { name: 'Ten Numb' type: 'pilot' count: 1 } { name: 'Blue Squadron Pilot' type: 'pilot' count: 2 } { name: 'Blade Squadron Veteran' type: 'pilot' count: 2 } { name: 'Airen Cracken' type: 'pilot' count: 1 } { name: 'Lieutenant Blount' type: 'pilot' count: 1 } { name: 'Bandit Squadron Pilot' type: 'pilot' count: 3 } { name: 'Tala Squadron Pilot' type: 'pilot' count: 3 } { name: 'Lowhhrick' type: 'pilot' count: 1 } { name: 'Wullffwarro' type: 'pilot' count: 1 } { name: 'Kashyyyk Defender' type: 'pilot' count: 2 } { name: 'Ezra Bridger' type: 'pilot' count: 1 } { name: 'Hera Syndulla' type: 'pilot' count: 1 } { name: 'Sabine Wren' type: 'pilot' count: 1 } { name: '"Zeb" Orrelios' type: 'pilot' count: 1 } { name: 'AP-5' type: 'pilot' count: 1 } { name: 'Ezra Bridger (Sheathipede)' type: 'pilot' count: 1 } { name: 'Fenn Rau (Sheathipede)' type: 'pilot' count: 1 } { name: '"Zeb" Orrelios (Sheathipede)' type: 'pilot' count: 1 } { name: 'Jan Ors' type: 'pilot' count: 1 } { name: 'Kyle Katarn' type: 'pilot' count: 1 } { name: 'Roark Garnet' type: 'pilot' count: 1 } { name: 'Rebel Scout' type: 'pilot' count: 2 } { name: 'Captain Rex' type: 'pilot' count: 1 } { name: 'Ezra Bridger (TIE Fighter)' type: 'pilot' count: 1 } { name: 'Sabine Wren (TIE Fighter)' type: 'pilot' count: 1 } { name: '"Zeb" Orrelios (TIE Fighter)' type: 'pilot' count: 1 } { name: 'Corran Horn' type: 'pilot' count: 1 } { name: 'Gavin Darklighter' type: 'pilot' count: 1 } { name: 'Knave Squadron Escort' type: 'pilot' count: 2 } { name: 'Rogue Squadron Escort' type: 'pilot' count: 2 } { name: 'Bodhi Rook' type: 'pilot' count: 1 } { name: 'Cassian Andor' type: 'pilot' count: 1 } { name: 'Heff Tobber' type: 'pilot' count: 1 } { name: 'Blue Squadron Scout' type: 'pilot' count: 2 } { name: 'Esege Tuketu' type: 'pilot' count: 1 } { name: 'Miranda Doni' type: 'pilot' count: 1 } { name: 'Warden Squadron Pilot' type: 'pilot' count: 2 } { name: 'Garven Dreis' type: 'pilot' count: 1 } { name: 'Ibtisam' type: 'pilot' count: 1 } { name: 'Norra Wexley' type: 'pilot' count: 1 } { name: 'Shara Bey' type: 'pilot' count: 1 } { name: 'Chewbacca' type: 'pilot' count: 1 } { name: 'Han Solo' type: 'pilot' count: 1 } { name: 'Lando Calrissian' type: 'pilot' count: 1 } { name: 'Outer Rim Smuggler' type: 'pilot' count: 1 } { name: '"Chopper"' type: 'pilot' count: 1 } { name: 'Hera Syndulla (VCX-100)' type: 'pilot' count: 1 } { name: 'Kanan Jarrus' type: 'pilot' count: 1 } { name: 'Lothal Rebel' type: 'pilot' count: 1 } { name: 'Dash Rendar' type: 'pilot' count: 1 } { name: '"Leebo"' type: 'pilot' count: 1 } { name: 'Wild Space Fringer' type: 'pilot' count: 1 } { name: 'Crack Shot' type: 'upgrade' count: 2 } { name: 'Daredevil' type: 'upgrade' count: 2 } { name: 'Debris Gambit' type: 'upgrade' count: 2 } { name: 'Elusive' type: 'upgrade' count: 2 } { name: 'Expert Handling' type: 'upgrade' count: 2 } { name: 'Intimidation' type: 'upgrade' count: 2 } { name: 'Juke' type: 'upgrade' count: 2 } { name: 'Lone Wolf' type: 'upgrade' count: 1 } { name: 'Marksmanship' type: 'upgrade' count: 2 } { name: 'Outmaneuver' type: 'upgrade' count: 2 } { name: 'Predator' type: 'upgrade' count: 2 } { name: 'Saturation Salvo' type: 'upgrade' count: 2 } { name: 'Selfless' type: 'upgrade' count: 3 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: 'Trick Shot' type: 'upgrade' count: 2 } { name: 'Advanced Sensors' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'Cloaking Device' type: 'upgrade' count: 1 } { name: 'Contraband Cybernetics' type: 'upgrade' count: 2 } { name: "Deadman's Switch" type: 'upgrade' count: 2 } { name: 'Feedback Array' type: 'upgrade' count: 2 } { name: 'Inertial Dampeners' type: 'upgrade' count: 2 } { name: 'Rigged Cargo Chute' type: 'upgrade' count: 2 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 2 } { name: 'Ion Cannon' type: 'upgrade' count: 2 } { name: 'Jamming Beam' type: 'upgrade' count: 2 } { name: 'Tractor Beam' type: 'upgrade' count: 2 } { name: 'Dorsal Turret' type: 'upgrade' count: 2 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 2 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 2 } { name: 'Ion Torpedoes' type: 'upgrade' count: 2 } { name: 'Proton Torpedoes' type: 'upgrade' count: 2 } { name: 'Baze Malbus' type: 'upgrade' count: 1 } { name: 'C-3PO' type: 'upgrade' count: 1 } { name: 'Cassian Andor' type: 'upgrade' count: 1 } { name: 'Chewbacca' type: 'upgrade' count: 1 } { name: '"Chopper" (Crew)' type: 'upgrade' count: 1 } { name: 'Freelance Slicer' type: 'upgrade' count: 2 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 2 } { name: 'Hera Syndulla' type: 'upgrade' count: 1 } { name: 'Informant' type: 'upgrade' count: 1 } { name: 'Jyn Erso' type: 'upgrade' count: 1 } { name: 'Kanan Jarrus' type: 'upgrade' count: 1 } { name: 'Lando Calrissian' type: 'upgrade' count: 1 } { name: 'Leia Organa' type: 'upgrade' count: 1 } { name: 'Nien Nunb' type: 'upgrade' count: 1 } { name: 'Novice Technician' type: 'upgrade' count: 2 } { name: 'Perceptive Copilot' type: 'upgrade' count: 2 } { name: 'R2-D2 (Crew)' type: 'upgrade' count: 1 } { name: 'Sabine Wren' type: 'upgrade' count: 1 } { name: 'Seasoned Navigator' type: 'upgrade' count: 1 } { name: 'Tactical Officer' type: 'upgrade' count: 1 } { name: '"Zeb" Orrelios' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Concussion Missiles' type: 'upgrade' count: 2 } { name: 'Homing Missiles' type: 'upgrade' count: 2 } { name: 'Ion Missiles' type: 'upgrade' count: 2 } { name: 'Proton Rockets' type: 'upgrade' count: 2 } { name: 'Bomblet Generator' type: 'upgrade' count: 1 } { name: 'Conner Nets' type: 'upgrade' count: 2 } { name: 'Proton Bombs' type: 'upgrade' count: 2 } { name: 'Proximity Mines' type: 'upgrade' count: 2 } { name: 'Seismic Charges' type: 'upgrade' count: 2 } { name: 'Ghost' type: 'upgrade' count: 1 } { name: 'Millennium Falcon' type: 'upgrade' count: 1 } { name: 'Moldy Crow' type: 'upgrade' count: 1 } { name: 'Outrider' type: 'upgrade' count: 1 } { name: 'Phantom' type: 'upgrade' count: 1 } { name: 'Pivot Wing' type: 'upgrade' count: 2 } { name: 'Servomotor S-Foils' type: 'upgrade' count: 2 } { name: 'Bistan' type: 'upgrade' count: 1 } { name: 'Ezra Bridger' type: 'upgrade' count: 1 } { name: 'Han Solo' type: 'upgrade' count: 1 } { name: 'Hotshot Gunner' type: 'upgrade' count: 2 } { name: 'Luke Skywalker' type: 'upgrade' count: 1 } { name: 'Skilled Bombardier' type: 'upgrade' count: 2 } { name: 'Veteran Tail Gunner' type: 'upgrade' count: 2 } { name: 'Veteran Turret Gunner' type: 'upgrade' count: 2 } { name: '"Chopper" (Astromech)' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 2 } { name: 'R3 Astromech' type: 'upgrade' count: 2 } { name: 'R4 Astromech' type: 'upgrade' count: 2 } { name: 'R5 Astromech' type: 'upgrade' count: 2 } { name: 'Ablative Plating' type: 'upgrade' count: 2 } { name: 'Advanced SLAM' type: 'upgrade' count: 2 } { name: 'Electronic Baffle' type: 'upgrade' count: 2 } { name: 'Engine Upgrade' type: 'upgrade' count: 2 } { name: 'Hull Upgrade' type: 'upgrade' count: 2 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Tactical Scrambler' type: 'upgrade' count: 2 } ] 'Galactic Empire Conversion Kit': [ { name: 'Ved Foslo' type: 'pilot' count: 1 } { name: 'Del Meeko' type: 'pilot' count: 1 } { name: 'Gideon Hask' type: 'pilot' count: 1 } { name: 'Seyn Marana' type: 'pilot' count: 1 } { name: '"Howlrunner"' type: 'pilot' count: 1 } { name: '"Mauler" Mithel' type: 'pilot' count: 1 } { name: '"Scourge" Skutu' type: 'pilot' count: 1 } { name: '"Wampa"' type: 'pilot' count: 1 } { name: 'Black Squadron Ace' type: 'pilot' count: 4 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 4 } { name: 'Academy Pilot' type: 'pilot' count: 4 } { name: 'Darth Vader' type: 'pilot' count: 1 } { name: 'Maarek Stele' type: 'pilot' count: 1 } { name: 'Zertik Strom' type: 'pilot' count: 1 } { name: 'Storm Squadron Ace' type: 'pilot' count: 2 } { name: 'Tempest Squadron Pilot' type: 'pilot' count: 2 } { name: 'Grand Inquisitor' type: 'pilot' count: 1 } { name: 'Seventh Sister' type: 'pilot' count: 1 } { name: 'Baron of the Empire' type: 'pilot' count: 3 } { name: 'Inquisitor' type: 'pilot' count: 3 } { name: 'Soontir Fel' type: 'pilot' count: 1 } { name: 'Turr Phennir' type: 'pilot' count: 1 } { name: 'Alpha Squadron Pilot' type: 'pilot' count: 2 } { name: 'Saber Squadron Ace' type: 'pilot' count: 2 } { name: 'Tomax Bren' type: 'pilot' count: 1 } { name: 'Captain Jonus' type: 'pilot' count: 1 } { name: 'Major Rhymer' type: 'pilot' count: 1 } { name: '"Deathfire"' type: 'pilot' count: 1 } { name: 'Gamma Squadron Ace' type: 'pilot' count: 3 } { name: 'Scimitar Squadron Pilot' type: 'pilot' count: 3 } { name: '"Duchess"' type: 'pilot' count: 1 } { name: '"Countdown"' type: 'pilot' count: 1 } { name: '"Pure Sabacc"' type: 'pilot' count: 1 } { name: 'Black Squadron Scout' type: 'pilot' count: 3 } { name: 'Planetary Sentinel' type: 'pilot' count: 3 } { name: 'Rexler Brath' type: 'pilot' count: 1 } { name: 'Colonel Vessery' type: 'pilot' count: 1 } { name: 'Countess Ryad' type: 'pilot' count: 1 } { name: 'Onyx Squadron Ace' type: 'pilot' count: 2 } { name: 'Delta Squadron Pilot' type: 'pilot' count: 2 } { name: '"Double Edge"' type: 'pilot' count: 1 } { name: 'Lieutenant Kestal' type: 'pilot' count: 1 } { name: 'Onyx Squadron Scout' type: 'pilot' count: 2 } { name: 'Sienar Specialist' type: 'pilot' count: 2 } { name: '"Echo"' type: 'pilot' count: 1 } { name: '"Whisper"' type: 'pilot' count: 1 } { name: 'Imdaar Test Pilot' type: 'pilot' count: 2 } { name: "Sigma Squadron Ace" type: 'pilot' count: 2 } { name: 'Major Vynder' type: 'pilot' count: 1 } { name: 'Lieutenant Karsabi' type: 'pilot' count: 1 } { name: 'Rho Squadron Pilot' type: 'pilot' count: 2 } { name: 'Nu Squadron Pilot' type: 'pilot' count: 2 } { name: '"Redline"' type: 'pilot' count: 1 } { name: '"Deathrain"' type: 'pilot' count: 1 } { name: 'Cutlass Squadron Pilot' type: 'pilot' count: 2 } { name: 'Captain Kagi' type: 'pilot' count: 1 } { name: 'Colonel Jendon' type: 'pilot' count: 1 } { name: 'Lieutenant Sai' type: 'pilot' count: 1 } { name: 'Omicron Group Pilot' type: 'pilot' count: 1 } { name: 'Rear Admiral Chiraneau' type: 'pilot' count: 1 } { name: 'Captain Oicunn' type: 'pilot' count: 1 } { name: 'Patrol Leader' type: 'pilot' count: 2 } { name: 'Crack Shot' type: 'upgrade' count: 3 } { name: 'Daredevil' type: 'upgrade' count: 2 } { name: 'Debris Gambit' type: 'upgrade' count: 2 } { name: 'Elusive' type: 'upgrade' count: 2 } { name: 'Expert Handling' type: 'upgrade' count: 2 } { name: 'Intimidation' type: 'upgrade' count: 3 } { name: 'Juke' type: 'upgrade' count: 3 } { name: 'Lone Wolf' type: 'upgrade' count: 1 } { name: 'Marksmanship' type: 'upgrade' count: 2 } { name: 'Outmaneuver' type: 'upgrade' count: 3 } { name: 'Predator' type: 'upgrade' count: 3 } { name: 'Ruthless' type: 'upgrade' count: 3 } { name: 'Saturation Salvo' type: 'upgrade' count: 2 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: 'Trick Shot' type: 'upgrade' count: 3 } { name: 'Advanced Sensors' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'Trajectory Simulator' type: 'upgrade' count: 2 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 2 } { name: 'Ion Cannon' type: 'upgrade' count: 2 } { name: 'Jamming Beam' type: 'upgrade' count: 2 } { name: 'Tractor Beam' type: 'upgrade' count: 2 } { name: 'Dorsal Turret' type: 'upgrade' count: 2 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 2 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 3 } { name: 'Ion Torpedoes' type: 'upgrade' count: 3 } { name: 'Proton Torpedoes' type: 'upgrade' count: 3 } { name: 'Barrage Rockets' type: 'upgrade' count: 3 } { name: 'Cluster Missiles' type: 'upgrade' count: 3 } { name: 'Concussion Missiles' type: 'upgrade' count: 3 } { name: 'Homing Missiles' type: 'upgrade' count: 3 } { name: 'Ion Missiles' type: 'upgrade' count: 3 } { name: 'Proton Rockets' type: 'upgrade' count: 3 } { name: 'Admiral Sloane' type: 'upgrade' count: 1 } { name: 'Agent Kallus' type: 'upgrade' count: 1 } { name: 'Ciena Ree' type: 'upgrade' count: 1 } { name: 'Darth Vader' type: 'upgrade' count: 1 } { name: 'Emperor Palpatine' type: 'upgrade' count: 1 } { name: 'Freelance Slicer' type: 'upgrade' count: 2 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 2 } { name: 'Grand Inquisitor' type: 'upgrade' count: 1 } { name: 'Grand Moff Tarkin' type: 'upgrade' count: 1 } { name: 'Informant' type: 'upgrade' count: 1 } { name: 'Minister Tua' type: 'upgrade' count: 1 } { name: 'Moff Jerjerrod' type: 'upgrade' count: 1 } { name: 'Novice Technician' type: 'upgrade' count: 2 } { name: 'Perceptive Copilot' type: 'upgrade' count: 2 } { name: 'Seasoned Navigator' type: 'upgrade' count: 2 } { name: 'Seventh Sister' type: 'upgrade' count: 1 } { name: 'Tactical Officer' type: 'upgrade' count: 2 } { name: 'Fifth Brother' type: 'upgrade' count: 1 } { name: 'Hotshot Gunner' type: 'upgrade' count: 2 } { name: 'Skilled Bombardier' type: 'upgrade' count: 2 } { name: 'Veteran Turret Gunner' type: 'upgrade' count: 2 } { name: 'Bomblet Generator' type: 'upgrade' count: 1 } { name: 'Conner Nets' type: 'upgrade' count: 3 } { name: 'Proton Bombs' type: 'upgrade' count: 3 } { name: 'Proximity Mines' type: 'upgrade' count: 3 } { name: 'Seismic Charges' type: 'upgrade' count: 3 } { name: 'Dauntless' type: 'upgrade' count: 1 } { name: 'ST-321' type: 'upgrade' count: 1 } { name: 'Os-1 Arsenal Loadout' type: 'upgrade' count: 3 } { name: 'Xg-1 Assault Configuration' type: 'upgrade' count: 3 } { name: 'Ablative Plating' type: 'upgrade' count: 2 } { name: 'Advanced SLAM' type: 'upgrade' count: 2 } { name: 'Electronic Baffle' type: 'upgrade' count: 2 } { name: 'Hull Upgrade' type: 'upgrade' count: 2 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Tactical Scrambler' type: 'upgrade' count: 2 } ] 'Scum and Villainy Conversion Kit': [ { name: 'Joy Rekkoff' type: 'pilot' count: 1 } { name: 'Koshka Frost' type: 'pilot' count: 1 } { name: 'Marauder' type: 'upgrade' count: 1 } { name: 'Fenn Rau' type: 'pilot' count: 1 } { name: 'Kad Solus' type: 'pilot' count: 1 } { name: 'Old Teroch' type: 'pilot' count: 1 } { name: 'Skull Squadron Pilot' type: 'pilot' count: 2 } { name: 'Zealous Recruit' type: 'pilot' count: 3 } { name: 'Constable Zuvio' type: 'pilot' count: 1 } { name: 'Sarco Plank' type: 'pilot' count: 1 } { name: 'Unkar Plutt' type: 'pilot' count: 1 } { name: 'Jakku Gunrunner' type: 'pilot' count: 3 } { name: 'Drea Renthal' type: 'pilot' count: 1 } { name: 'Kavil' type: 'pilot' count: 1 } { name: 'Crymorah Goon' type: 'pilot' count: 2 } { name: 'Hired Gun' type: 'pilot' count: 2 } { name: "Kaa'to Leeachos" type: 'pilot' count: 1 } { name: 'Nashtah Pup' type: 'pilot' count: 1 } { name: "N'dru Suhlak" type: 'pilot' count: 1 } { name: 'Black Sun Soldier' type: 'pilot' count: 3 } { name: 'Binayre Pirate' type: 'pilot' count: 3 } { name: 'Dace Bonearm' type: 'pilot' count: 1 } { name: 'Palob Godalhi' type: 'pilot' count: 1 } { name: 'Torkil Mux' type: 'pilot' count: 1 } { name: 'Spice Runner' type: 'pilot' count: 3 } { name: 'Dalan Oberos (StarViper)' type: 'pilot' count: 1 } { name: 'Guri' type: 'pilot' count: 1 } { name: 'Prince Xizor' type: 'pilot' count: 1 } { name: 'Black Sun Assassin' type: 'pilot' count: 2 } { name: 'Black Sun Enforcer' type: 'pilot' count: 2 } { name: 'Genesis Red' type: 'pilot' count: 1 } { name: 'Inaldra' type: 'pilot' count: 1 } { name: "Laetin A'shera" type: 'pilot' count: 1 } { name: 'Quinn Jast' type: 'pilot' count: 1 } { name: 'Serissu' type: 'pilot' count: 1 } { name: 'Sunny Bounder' type: 'pilot' count: 1 } { name: 'Tansarii Point Veteran' type: 'pilot' count: 4 } { name: 'Cartel Spacer' type: 'pilot' count: 4 } { name: 'Captain Jostero' type: 'pilot' count: 1 } { name: 'Graz' type: 'pilot' count: 1 } { name: 'Talonbane Cobra' type: 'pilot' count: 1 } { name: 'Viktor Hel' type: 'pilot' count: 1 } { name: 'Black Sun Ace' type: 'pilot' count: 3 } { name: 'Cartel Marauder' type: 'pilot' count: 3 } { name: 'Boba Fett' type: 'pilot' count: 1 } { name: 'Emon Azzameen' type: 'pilot' count: 1 } { name: 'Kath Scarlet' type: 'pilot' count: 1 } { name: 'Krassis Trelix' type: 'pilot' count: 1 } { name: 'Bounty Hunter' type: 'pilot' count: 2 } { name: 'IG-88A' type: 'pilot' count: 1 } { name: 'IG-88B' type: 'pilot' count: 1 } { name: 'IG-88C' type: 'pilot' count: 1 } { name: 'IG-88D' type: 'pilot' count: 1 } { name: '4-LOM' type: 'pilot' count: 1 } { name: 'Zuckuss' type: 'pilot' count: 1 } { name: 'Gand Findsman' type: 'pilot' count: 2 } { name: 'Captain Nym' type: 'pilot' count: 1 } { name: 'Sol Sixxa' type: 'pilot' count: 1 } { name: 'Lok Revenant' type: 'pilot' count: 2 } { name: 'Dalan Oberos' type: 'pilot' count: 1 } { name: 'Torani Kulda' type: 'pilot' count: 1 } { name: 'Cartel Executioner' type: 'pilot' count: 2 } { name: 'Bossk' type: 'pilot' count: 1 } { name: 'Latts Razzi' type: 'pilot' count: 1 } { name: 'Moralo Eval' type: 'pilot' count: 1 } { name: 'Trandoshan Slaver' type: 'pilot' count: 1 } { name: 'Dengar' type: 'pilot' count: 1 } { name: 'Manaroo' type: 'pilot' count: 1 } { name: 'Tel Trevura' type: 'pilot' count: 1 } { name: 'Contracted Scout' type: 'pilot' count: 1 } { name: 'Asajj Ventress' type: 'pilot' count: 1 } { name: 'Ketsu Onyo' type: 'pilot' count: 1 } { name: 'Sabine Wren (Scum)' type: 'pilot' count: 1 } { name: 'Shadowport Hunter' type: 'pilot' count: 1 } { name: 'Crack Shot' type: 'upgrade' count: 3 } { name: 'Daredevil' type: 'upgrade' count: 2 } { name: 'Debris Gambit' type: 'upgrade' count: 2 } { name: 'Elusive' type: 'upgrade' count: 2 } { name: 'Expert Handling' type: 'upgrade' count: 2 } { name: 'Fearless' type: 'upgrade' count: 3 } { name: 'Intimidation' type: 'upgrade' count: 3 } { name: 'Juke' type: 'upgrade' count: 2 } { name: 'Lone Wolf' type: 'upgrade' count: 1 } { name: 'Marksmanship' type: 'upgrade' count: 2 } { name: 'Outmaneuver' type: 'upgrade' count: 2 } { name: 'Predator' type: 'upgrade' count: 2 } { name: 'Saturation Salvo' type: 'upgrade' count: 2 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: 'Trick Shot' type: 'upgrade' count: 2 } { name: 'Advanced Sensors' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'Trajectory Simulator' type: 'upgrade' count: 2 } { name: 'Cloaking Device' type: 'upgrade' count: 1 } { name: 'Contraband Cybernetics' type: 'upgrade' count: 2 } { name: "Deadman's Switch" type: 'upgrade' count: 3 } { name: 'Feedback Array' type: 'upgrade' count: 3 } { name: 'Inertial Dampeners' type: 'upgrade' count: 2 } { name: 'Rigged Cargo Chute' type: 'upgrade' count: 2 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 2 } { name: 'Ion Cannon' type: 'upgrade' count: 2 } { name: 'Jamming Beam' type: 'upgrade' count: 2 } { name: 'Tractor Beam' type: 'upgrade' count: 2 } { name: 'Dorsal Turret' type: 'upgrade' count: 2 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 2 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 2 } { name: 'Ion Torpedoes' type: 'upgrade' count: 2 } { name: 'Proton Torpedoes' type: 'upgrade' count: 2 } { name: '0-0-0' type: 'upgrade' count: 1 } { name: '4-LOM' type: 'upgrade' count: 1 } { name: 'Boba Fett' type: 'upgrade' count: 1 } { name: 'Cad Bane' type: 'upgrade' count: 1 } { name: 'Cikatro Vizago' type: 'upgrade' count: 1 } { name: 'Freelance Slicer' type: 'upgrade' count: 2 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 2 } { name: 'IG-88D' type: 'upgrade' count: 1 } { name: 'Informant' type: 'upgrade' count: 1 } { name: 'Jabba the Hutt' type: 'upgrade' count: 1 } { name: 'Ketsu Onyo' type: 'upgrade' count: 1 } { name: 'Latts Razzi' type: 'upgrade' count: 1 } { name: 'Maul' type: 'upgrade' count: 1 } { name: 'Novice Technician' type: 'upgrade' count: 2 } { name: 'Perceptive Copilot' type: 'upgrade' count: 2 } { name: 'Seasoned Navigator' type: 'upgrade' count: 2 } { name: 'Tactical Officer' type: 'upgrade' count: 2 } { name: 'Unkar Plutt' type: 'upgrade' count: 1 } { name: 'Zuckuss' type: 'upgrade' count: 1 } { name: 'Bossk' type: 'upgrade' count: 1 } { name: 'BT-1' type: 'upgrade' count: 1 } { name: 'Dengar' type: 'upgrade' count: 1 } { name: 'Greedo' type: 'upgrade' count: 1 } { name: 'Hotshot Gunner' type: 'upgrade' count: 2 } { name: 'Skilled Bombardier' type: 'upgrade' count: 2 } { name: 'Veteran Tail Gunner' type: 'upgrade' count: 2 } { name: 'Veteran Turret Gunner' type: 'upgrade' count: 2 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Concussion Missiles' type: 'upgrade' count: 2 } { name: 'Homing Missiles' type: 'upgrade' count: 2 } { name: 'Ion Missiles' type: 'upgrade' count: 2 } { name: 'Proton Rockets' type: 'upgrade' count: 2 } { name: 'Bomblet Generator' type: 'upgrade' count: 1 } { name: 'Conner Nets' type: 'upgrade' count: 2 } { name: 'Proton Bombs' type: 'upgrade' count: 2 } { name: 'Proximity Mines' type: 'upgrade' count: 2 } { name: 'Seismic Charges' type: 'upgrade' count: 2 } { name: 'Andrasta' type: 'upgrade' count: 1 } { name: 'Havoc' type: 'upgrade' count: 1 } { name: "Hound's Tooth" type: 'upgrade' count: 1 } { name: 'IG-2000' type: 'upgrade' count: 2 } { name: 'Mist Hunter' type: 'upgrade' count: 1 } { name: 'Punishing One' type: 'upgrade' count: 1 } { name: 'Shadow Caster' type: 'upgrade' count: 1 } { name: 'Slave I' type: 'upgrade' count: 1 } { name: 'Virago' type: 'upgrade' count: 1 } { name: 'Ablative Plating' type: 'upgrade' count: 2 } { name: 'Electronic Baffle' type: 'upgrade' count: 2 } { name: 'Engine Upgrade' type: 'upgrade' count: 2 } { name: 'Hull Upgrade' type: 'upgrade' count: 2 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Tactical Scrambler' type: 'upgrade' count: 2 } { name: '"Genius"' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 2 } { name: 'R3 Astromech' type: 'upgrade' count: 2 } { name: 'R4 Astromech' type: 'upgrade' count: 2 } { name: 'R5 Astromech' type: 'upgrade' count: 2 } { name: 'R5-P8' type: 'upgrade' count: 1 } { name: 'R5-TK' type: 'upgrade' count: 1 } ] 'T-65 X-Wing Expansion Pack' : [ { name: 'X-Wing' type: 'ship' count: 1 } { name: 'Wedge Antilles' type: 'pilot' count: 1 } { name: 'Thane Kyrell' type: 'pilot' count: 1 } { name: 'Garven Dreis (X-Wing)' type: 'pilot' count: 1 } { name: 'Biggs Darklighter' type: 'pilot' count: 1 } { name: 'Red Squadron Veteran' type: 'pilot' count: 1 } { name: 'Blue Squadron Escort' type: 'pilot' count: 1 } { name: 'Selfless' type: 'upgrade' count: 1 } { name: 'Ion Torpedoes' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 1 } { name: 'R4 Astromech' type: 'upgrade' count: 1 } { name: 'Servomotor S-Foils' type: 'upgrade' count: 1 } ] 'BTL-A4 Y-Wing Expansion Pack' : [ { name: 'Y-Wing' type: 'ship' count: 1 } { name: 'Horton Salm' type: 'pilot' count: 1 } { name: 'Norra Wexley (Y-Wing)' type: 'pilot' count: 1 } { name: '"Dutch" Vander' type: 'pilot' count: 1 } { name: 'Evaan Verlaine' type: 'pilot' count: 1 } { name: 'Gold Squadron Veteran' type: 'pilot' count: 1 } { name: 'Gray Squadron Bomber' type: 'pilot' count: 1 } { name: 'R5 Astromech' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 1 } { name: 'Proton Bombs' type: 'upgrade' count: 1 } { name: 'Seismic Charges' type: 'upgrade' count: 1 } { name: 'Veteran Turret Gunner' type: 'upgrade' count: 1 } ] 'TIE/ln Fighter Expansion Pack': [ { name: 'TIE Fighter' type: 'ship' count: 1 } { name: '"Howlrunner"' type: 'pilot' count: 1 } { name: '"Mauler" Mithel' type: 'pilot' count: 1 } { name: 'Gideon Hask' type: 'pilot' count: 1 } { name: '"Scourge" Skutu' type: 'pilot' count: 1 } { name: 'Seyn Marana' type: 'pilot' count: 1 } { name: 'Del Meeko' type: 'pilot' count: 1 } { name: '"Wampa"' type: 'pilot' count: 1 } { name: 'Black Squadron Ace' type: 'pilot' count: 1 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 1 } { name: 'Academy Pilot' type: 'pilot' count: 1 } { name: 'Crack Shot' type: 'upgrade' count: 1 } { name: 'Juke' type: 'upgrade' count: 1 } { name: 'Marksmanship' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'upgrade' count: 1 } ] 'TIE Advanced x1 Expansion Pack': [ { name: 'TIE Advanced' type: 'ship' count: 1 } { name: 'Darth Vader' type: 'pilot' count: 1 } { name: 'Maarek Stele' type: 'pilot' count: 1 } { name: 'Ved Foslo' type: 'pilot' count: 1 } { name: 'Zertik Strom' type: 'pilot' count: 1 } { name: 'Storm Squadron Ace' type: 'pilot' count: 1 } { name: 'Tempest Squadron Pilot' type: 'pilot' count: 1 } { name: 'Heightened Perception' type: 'upgrade' count: 1 } { name: 'Supernatural Reflexes' type: 'upgrade' count: 1 } { name: 'Ruthless' type: 'upgrade' count: 1 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Fire-Control System' type: 'upgrade' count: 1 } ] 'Slave I Expansion Pack': [ { name: 'Firespray-31' type: 'ship' count: 1 } { name: 'Boba Fett' type: 'pilot' count: 1 } { name: 'Kath Scarlet' type: 'pilot' count: 1 } { name: 'Emon Azzameen' type: 'pilot' count: 1 } { name: 'Koshka Frost' type: 'pilot' count: 1 } { name: 'Krassis Trelix' type: 'pilot' count: 1 } { name: 'Bounty Hunter' type: 'pilot' count: 1 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 1 } { name: 'Boba Fett' type: 'upgrade' count: 1 } { name: 'Perceptive Copilot' type: 'upgrade' count: 1 } { name: 'Proximity Mines' type: 'upgrade' count: 1 } { name: 'Seismic Charges' type: 'upgrade' count: 1 } { name: 'Veteran Tail Gunner' type: 'upgrade' count: 1 } { name: 'Inertial Dampeners' type: 'upgrade' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } { name: 'Lone Wolf' type: 'upgrade' count: 1 } { name: 'Andrasta' type: 'upgrade' count: 1 } { name: 'Marauder' type: 'upgrade' count: 1 } { name: 'Slave I' type: 'upgrade' count: 1 } ] 'Fang Fighter Expansion Pack': [ { name: 'Fang Fighter' type: 'ship' count: 1 } { name: 'Fenn Rau' type: 'pilot' count: 1 } { name: 'Old Teroch' type: 'pilot' count: 1 } { name: 'Kad Solus' type: 'pilot' count: 1 } { name: 'Joy Rekkoff' type: 'pilot' count: 1 } { name: 'Skull Squadron Pilot' type: 'pilot' count: 1 } { name: 'Zealous Recruit' type: 'pilot' count: 1 } { name: 'Afterburners' type: 'upgrade' count: 1 } { name: 'Fearless' type: 'upgrade' count: 1 } { name: 'Daredevil' type: 'upgrade' count: 1 } { name: 'Ion Torpedoes' type: 'upgrade' count: 1 } ] "Lando's Millennium Falcon Expansion Pack": [ { name: 'Customized YT-1300' type: 'ship' count: 1 } { name: 'Escape Craft' type: 'ship' count: 1 } { name: 'Han Solo (Scum)' type: 'pilot' count: 1 } { name: 'Lando Calrissian (Scum)' type: 'pilot' count: 1 } { name: 'L3-37' type: 'pilot' count: 1 } { name: 'Freighter Captain' type: 'pilot' count: 1 } { name: 'Lando Calrissian (Scum) (Escape Craft)' type: 'pilot' count: 1 } { name: 'Outer Rim Pioneer' type: 'pilot' count: 1 } { name: 'L3-37 (Escape Craft)' type: 'pilot' count: 1 } { name: 'Autopilot Drone' type: 'pilot' count: 1 } { name: 'L3-37' type: 'upgrade' count: 1 } { name: 'Chewbacca (Scum)' type: 'upgrade' count: 1 } { name: 'Lando Calrissian (Scum)' type: 'upgrade' count: 1 } { name: "Qi'ra" type: 'upgrade' count: 1 } { name: 'Tobias Beckett' type: 'upgrade' count: 1 } { name: 'Seasoned Navigator' type: 'upgrade' count: 1 } { name: 'Han Solo (Scum)' type: 'upgrade' count: 1 } { name: 'Agile Gunner' type: 'upgrade' count: 1 } { name: 'Composure' type: 'upgrade' count: 1 } { name: 'Intimidation' type: 'upgrade' count: 1 } { name: "Lando's Millennium Falcon" type: 'upgrade' count: 1 } { name: 'Rigged Cargo Chute' type: 'upgrade' count: 1 } { name: 'Tactical Scrambler' type: 'upgrade' count: 1 } ] 'Resistance Conversion Kit': [ { name: 'Finch Dallow' type: 'pilot' count: 1 } { name: 'Edon Kappehl' type: 'pilot' count: 1 } { name: 'Ben Teene' type: 'pilot' count: 1 } { name: 'Vennie' type: 'pilot' count: 1 } { name: 'Cat' type: 'pilot' count: 1 } { name: 'Cobalt Squadron Bomber' type: 'pilot' count: 3 } { name: 'Rey' type: 'pilot' count: 1 } { name: 'Han Solo (Resistance)' type: 'pilot' count: 1 } { name: 'Chewbacca (Resistance)' type: 'pilot' count: 1 } { name: 'Resistance Sympathizer' type: 'pilot' count: 3 } { name: 'Poe Dameron' type: 'pilot' count: 1 } { name: 'Ello Asty' type: 'pilot' count: 1 } { name: 'Nien Nunb' type: 'pilot' count: 1 } { name: 'Temmin Wexley' type: 'pilot' count: 1 } { name: 'Kare Kun' type: 'pilot' count: 1 } { name: 'Jessika Pava' type: 'pilot' count: 1 } { name: 'Joph Seastriker' type: 'pilot' count: 1 } { name: 'Jaycris Tubbs' type: 'pilot' count: 1 } { name: 'Lieutenant Bastian' type: 'pilot' count: 1 } { name: 'Black Squadron Ace (T-70)' type: 'pilot' count: 1 } { name: 'Red Squadron Expert' type: 'pilot' count: 4 } { name: 'Blue Squadron Rookie' type: 'pilot' count: 4 } { name: 'R2-HA' type: 'upgrade' count: 1 } { name: 'BB-8' type: 'upgrade' count: 1 } { name: 'R5-X3' type: 'upgrade' count: 1 } { name: 'BB Astromech' type: 'upgrade' count: 4 } { name: 'R2 Astromech' type: 'upgrade' count: 2 } { name: 'R3 Astromech' type: 'upgrade' count: 2 } { name: 'R4 Astromech' type: 'upgrade' count: 2 } { name: 'R5 Astromech' type: 'upgrade' count: 2 } { name: 'M9-G8' type: 'upgrade' count: 1 } { name: 'C-3PO (Resistance)' type: 'upgrade' count: 1 } { name: 'Rey' type: 'upgrade' count: 1 } { name: 'Finn' type: 'upgrade' count: 1 } { name: 'Han Solo (Resistance)' type: 'upgrade' count: 1 } { name: 'Chewbacca (Resistance)' type: 'upgrade' count: 1 } { name: "Rey's Millennium Falcon" type: 'upgrade' count: 1 } { name: 'Black One' type: 'upgrade' count: 1 } { name: 'Integrated S-Foils' type: 'upgrade' count: 4 } { name: 'Rose Tico' type: 'upgrade' count: 1 } { name: 'Paige Tico' type: 'upgrade' count: 1 } { name: 'Crack Shot' type: 'upgrade' count: 2 } { name: 'Daredevil' type: 'upgrade' count: 2 } { name: 'Debris Gambit' type: 'upgrade' count: 2 } { name: 'Elusive' type: 'upgrade' count: 2 } { name: 'Heroic' type: 'upgrade' count: 3 } { name: 'Intimidation' type: 'upgrade' count: 2 } { name: 'Juke' type: 'upgrade' count: 2 } { name: 'Lone Wolf' type: 'upgrade' count: 1 } { name: 'Marksmanship' type: 'upgrade' count: 2 } { name: 'Outmaneuver' type: 'upgrade' count: 2 } { name: 'Predator' type: 'upgrade' count: 2 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: 'Trick Shot' type: 'upgrade' count: 2 } { name: 'Advanced Optics' type: 'upgrade' count: 2 } { name: 'Pattern Analyzer' type: 'upgrade' count: 2 } { name: 'Primed Thrusters' type: 'upgrade' count: 2 } { name: 'Targeting Synchronizer' type: 'upgrade' count: 2 } { name: 'Advanced Sensors' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'Trajectory Simulator' type: 'upgrade' count: 2 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 2 } { name: 'Ion Cannon' type: 'upgrade' count: 2 } { name: 'Jamming Beam' type: 'upgrade' count: 2 } { name: 'Tractor Beam' type: 'upgrade' count: 2 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 2 } { name: 'Proton Torpedoes' type: 'upgrade' count: 2 } { name: 'Ion Torpedoes' type: 'upgrade' count: 2 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Concussion Missiles' type: 'upgrade' count: 2 } { name: 'Homing Missiles' type: 'upgrade' count: 2 } { name: 'Ion Missiles' type: 'upgrade' count: 2 } { name: 'Proton Rockets' type: 'upgrade' count: 2 } { name: 'Freelance Slicer' type: 'upgrade' count: 2 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 2 } { name: 'Informant' type: 'upgrade' count: 1 } { name: 'Novice Technician' type: 'upgrade' count: 2 } { name: 'Perceptive Copilot' type: 'upgrade' count: 2 } { name: 'Seasoned Navigator' type: 'upgrade' count: 2 } { name: 'Tactical Officer' type: 'upgrade' count: 2 } { name: 'Hotshot Gunner' type: 'upgrade' count: 2 } { name: 'Skilled Bombardier' type: 'upgrade' count: 2 } { name: 'Veteran Turret Gunner' type: 'upgrade' count: 2 } { name: 'Contraband Cybernetics' type: 'upgrade' count: 2 } { name: "Deadman's Switch" type: 'upgrade' count: 2 } { name: 'Feedback Array' type: 'upgrade' count: 2 } { name: 'Inertial Dampeners' type: 'upgrade' count: 2 } { name: 'Rigged Cargo Chute' type: 'upgrade' count: 2 } { name: 'Bomblet Generator' type: 'upgrade' count: 1 } { name: 'Conner Nets' type: 'upgrade' count: 2 } { name: 'Proton Bombs' type: 'upgrade' count: 2 } { name: 'Proximity Mines' type: 'upgrade' count: 2 } { name: 'Seismic Charges' type: 'upgrade' count: 2 } { name: 'Ablative Plating' type: 'upgrade' count: 2 } { name: 'Advanced SLAM' type: 'upgrade' count: 1 } { name: 'Electronic Baffle' type: 'upgrade' count: 2 } { name: 'Engine Upgrade' type: 'upgrade' count: 2 } { name: 'Hull Upgrade' type: 'upgrade' count: 2 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Tactical Scrambler' type: 'upgrade' count: 2 } ] 'T-70 X-Wing Expansion Pack': [ { name: 'T-70 X-Wing' type: 'ship' count: 1 } { name: 'Poe Dameron' type: 'pilot' count: 1 } { name: 'Ello Asty' type: 'pilot' count: 1 } { name: 'Nien Nunb' type: 'pilot' count: 1 } { name: 'Temmin Wexley' type: 'pilot' count: 1 } { name: 'Kare Kun' type: 'pilot' count: 1 } { name: 'Jessika Pava' type: 'pilot' count: 1 } { name: 'Joph Seastriker' type: 'pilot' count: 1 } { name: 'Jaycris Tubbs' type: 'pilot' count: 1 } { name: 'Lieutenant Bastian' type: 'pilot' count: 1 } { name: 'Black Squadron Ace (T-70)' type: 'pilot' count: 1 } { name: 'Red Squadron Expert' type: 'pilot' count: 1 } { name: 'Blue Squadron Rookie' type: 'pilot' count: 1 } { name: 'Black One' type: 'upgrade' count: 1 } { name: 'BB-8' type: 'upgrade' count: 1 } { name: 'BB Astromech' type: 'upgrade' count: 1 } { name: 'Integrated S-Foils' type: 'upgrade' count: 1 } { name: 'M9-G8' type: 'upgrade' count: 1 } { name: 'Targeting Synchronizer' type: 'upgrade' count: 1 } ] 'RZ-2 A-Wing Expansion Pack': [ { name: 'RZ-2 A-Wing' type: 'ship' count: 1 } { name: "L'ulo L'ampar" type: 'pilot' count: 1 } { name: 'Greer Sonnel' type: 'pilot' count: 1 } { name: 'Tallissan Lintra' type: 'pilot' count: 1 } { name: 'Zari Bangel' type: 'pilot' count: 1 } { name: 'Green Squadron Expert' type: 'pilot' count: 1 } { name: 'Blue Squadron Recruit' type: 'pilot' count: 1 } { name: 'Heroic' type: 'upgrade' count: 1 } { name: 'Ferrosphere Paint' type: 'upgrade' count: 1 } { name: 'Homing Missiles' type: 'upgrade' count: 1 } { name: 'Primed Thrusters' type: 'upgrade' count: 1 } { name: 'Proton Rockets' type: 'upgrade' count: 1 } ] 'Mining Guild TIE Expansion Pack': [ { name: 'Mining Guild TIE Fighter' type: 'ship' count: 1 } { name: 'Foreman Proach' type: 'pilot' count: 1 } { name: 'Ahhav' type: 'pilot' count: 1 } { name: 'Captain Seevor' type: 'pilot' count: 1 } { name: 'Overseer Yushyn' type: 'pilot' count: 1 } { name: 'Mining Guild Surveyor' type: 'pilot' count: 1 } { name: 'Mining Guild Sentry' type: 'pilot' count: 1 } { name: 'Hull Upgrade' type: 'upgrade' count: 1 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 1 } { name: 'Elusive' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } { name: 'Trick Shot' type: 'upgrade' count: 1 } ] 'First Order Conversion Kit': [ { name: 'Commander Malarus' type: 'pilot' count: 1 } { name: 'Lieutenant Rivas' type: 'pilot' count: 1 } { name: 'TN-3465' type: 'pilot' count: 1 } { name: 'Epsilon Squadron Cadet' type: 'pilot' count: 7 } { name: 'Zeta Squadron Pilot' type: 'pilot' count: 7 } { name: 'Omega Squadron Ace' type: 'pilot' count: 6 } { name: '"Null"' type: 'pilot' count: 1 } { name: '"Muse"' type: 'pilot' count: 1 } { name: '"Longshot"' type: 'pilot' count: 1 } { name: '"Static"' type: 'pilot' count: 1 } { name: '"Scorch"' type: 'pilot' count: 1 } { name: '"Midnight"' type: 'pilot' count: 1 } { name: '"Quickdraw"' type: 'pilot' count: 1 } { name: '"Backdraft"' type: 'pilot' count: 1 } { name: "Omega Squadron Expert" type: 'pilot' count: 4 } { name: "Zeta Squadron Survivor" type: 'pilot' count: 5 } { name: "Kylo Ren" type: 'pilot' count: 1 } { name: '"Blackout"' type: 'pilot' count: 1 } { name: '"Recoil"' type: 'pilot' count: 1 } { name: '"Avenger"' type: 'pilot' count: 1 } { name: "First Order Test Pilot" type: 'pilot' count: 3 } { name: "Sienar-Jaemus Engineer" type: 'pilot' count: 3 } { name: "Captain Cardinal" type: 'pilot' count: 1 } { name: "Major Stridan" type: 'pilot' count: 1 } { name: "Lieutenant Tavson" type: 'pilot' count: 1 } { name: "Lieutenant Dormitz" type: 'pilot' count: 1 } { name: "Petty Officer Thanisson" type: 'pilot' count: 1 } { name: "Starkiller Base Pilot" type: 'pilot' count: 3 } { name: "Primed Thrusters" type: 'upgrade' count: 1 } { name: "Hyperspace Tracking Data" type: 'upgrade' count: 1 } { name: "Special Forces Gunner" type: 'upgrade' count: 4 } { name: "Supreme Leader Snoke" type: 'upgrade' count: 1 } { name: "Petty Officer Thanisson" type: 'upgrade' count: 1 } { name: "Kylo Ren" type: 'upgrade' count: 1 } { name: "General Hux" type: 'upgrade' count: 1 } { name: "Captain Phasma" type: 'upgrade' count: 1 } { name: "Biohexacrypt Codes" type: 'upgrade' count: 1 } { name: "Predictive Shot" type: 'upgrade' count: 1 } { name: "Hate" type: 'upgrade' count: 1 } { name: 'Crack Shot' type: 'upgrade' count: 2 } { name: 'Daredevil' type: 'upgrade' count: 2 } { name: 'Debris Gambit' type: 'upgrade' count: 2 } { name: 'Elusive' type: 'upgrade' count: 2 } { name: 'Fanatical' type: 'upgrade' count: 3 } { name: 'Intimidation' type: 'upgrade' count: 2 } { name: 'Juke' type: 'upgrade' count: 2 } { name: 'Lone Wolf' type: 'upgrade' count: 1 } { name: 'Marksmanship' type: 'upgrade' count: 2 } { name: 'Outmaneuver' type: 'upgrade' count: 2 } { name: 'Predator' type: 'upgrade' count: 2 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: 'Trick Shot' type: 'upgrade' count: 2 } { name: 'Advanced Optics' type: 'upgrade' count: 2 } { name: 'Pattern Analyzer' type: 'upgrade' count: 2 } { name: 'Primed Thrusters' type: 'upgrade' count: 2 } { name: 'Targeting Synchronizer' type: 'upgrade' count: 2 } { name: 'Hyperspace Tracking Data' type: 'upgrade' count: 2 } { name: 'Advanced Sensors' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 2 } { name: 'Ion Cannon' type: 'upgrade' count: 2 } { name: 'Jamming Beam' type: 'upgrade' count: 2 } { name: 'Tractor Beam' type: 'upgrade' count: 2 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 2 } { name: 'Proton Torpedoes' type: 'upgrade' count: 2 } { name: 'Ion Torpedoes' type: 'upgrade' count: 2 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Concussion Missiles' type: 'upgrade' count: 2 } { name: 'Homing Missiles' type: 'upgrade' count: 2 } { name: 'Ion Missiles' type: 'upgrade' count: 2 } { name: 'Proton Rockets' type: 'upgrade' count: 2 } { name: 'Freelance Slicer' type: 'upgrade' count: 2 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 2 } { name: 'Informant' type: 'upgrade' count: 1 } { name: 'Novice Technician' type: 'upgrade' count: 2 } { name: 'Perceptive Copilot' type: 'upgrade' count: 2 } { name: 'Seasoned Navigator' type: 'upgrade' count: 2 } { name: 'Hotshot Gunner' type: 'upgrade' count: 2 } { name: 'Ablative Plating' type: 'upgrade' count: 2 } { name: 'Electronic Baffle' type: 'upgrade' count: 2 } { name: 'Engine Upgrade' type: 'upgrade' count: 2 } { name: 'Hull Upgrade' type: 'upgrade' count: 2 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Tactical Scrambler' type: 'upgrade' count: 2 } ] 'TIE/FO Fighter Expansion Pack': [ { name: 'TIE/FO Fighter' type: 'ship' count: 1 } { name: 'Epsilon Squadron Cadet' type: 'pilot' count: 1 } { name: 'Zeta Squadron Pilot' type: 'pilot' count: 1 } { name: 'Omega Squadron Ace' type: 'pilot' count: 1 } { name: '"Null"' type: 'pilot' count: 1 } { name: 'Lieutenant Rivas' type: 'pilot' count: 1 } { name: '"Muse"' type: 'pilot' count: 1 } { name: 'TN-3465' type: 'pilot' count: 1 } { name: '"Longshot"' type: 'pilot' count: 1 } { name: '"Static"' type: 'pilot' count: 1 } { name: '"Scorch"' type: 'pilot' count: 1 } { name: 'Commander Malarus' type: 'pilot' count: 1 } { name: '"Midnight"' type: 'pilot' count: 1 } { name: 'Fanatical' type: 'upgrade' count: 1 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } { name: 'Advanced Optics' type: 'upgrade' count: 1 } { name: 'Targeting Synchronizer' type: 'upgrade' count: 1 } ] 'Servants of Strife Squadron Pack': [ { name: 'Belbullab-22 Starfighter' type: 'ship' count: 1 } { name: 'Vulture-class Droid Fighter' type: 'ship' count: 2 } { name: 'General Grievous' type: 'pilot' count: 1 } { name: 'Captain Sear' type: 'pilot' count: 1 } { name: 'Wat Tambor' type: 'pilot' count: 1 } { name: 'Skakoan Ace' type: 'pilot' count: 1 } { name: 'Feethan Ottraw Autopilot' type: 'pilot' count: 1 } { name: 'Trade Federation Drone' type: 'pilot' count: 2 } { name: 'Separatist Drone' type: 'pilot' count: 2 } { name: 'DFS-081' type: 'pilot' count: 1 } { name: 'Precise Hunter' type: 'pilot' count: 2 } { name: 'Haor Chall Prototype' type: 'pilot' count: 2 } { name: 'Soulless One' type: 'upgrade' count: 1 } { name: 'Grappling Struts' type: 'upgrade' count: 2 } { name: 'TV-94' type: 'upgrade' count: 1 } { name: 'Kraken' type: 'upgrade' count: 1 } { name: 'Composure' type: 'upgrade' count: 2 } { name: 'Crack Shot' type: 'upgrade' count: 2 } { name: 'Daredevil' type: 'upgrade' count: 2 } { name: 'Intimidation' type: 'upgrade' count: 2 } { name: 'Juke' type: 'upgrade' count: 2 } { name: 'Lone Wolf' type: 'upgrade' count: 1 } { name: 'Marksmanship' type: 'upgrade' count: 2 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: 'Treacherous' type: 'upgrade' count: 2 } { name: 'Trick Shot' type: 'upgrade' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 2 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Homing Missiles' type: 'upgrade' count: 2 } { name: 'Proton Rockets' type: 'upgrade' count: 2 } { name: 'Energy-Shell Charges' type: 'upgrade' count: 2 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Afterburners' type: 'upgrade' count: 3 } { name: 'Electronic Baffle' type: 'upgrade' count: 2 } { name: 'Impervium Plating' type: 'upgrade' count: 1 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 3 } { name: 'Stealth Device' type: 'upgrade' count: 3 } ] 'Sith Infiltrator Expansion Pack': [ { name: 'Sith Infiltrator' type: 'ship' count: 1 } { name: 'Dark Courier' type: 'pilot' count: 1 } { name: '0-66' type: 'pilot' count: 1 } { name: 'Count Dooku' type: 'pilot' count: 1 } { name: 'Darth Maul' type: 'pilot' count: 1 } { name: 'Brilliant Evasion' type: 'upgrade' count: 1 } { name: 'Hate' type: 'upgrade' count: 1 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 1 } { name: 'Count Dooku' type: 'upgrade' count: 1 } { name: 'General Grievous' type: 'upgrade' count: 1 } { name: 'K2-B4' type: 'upgrade' count: 1 } { name: 'DRK-1 Probe Droids' type: 'upgrade' count: 1 } { name: 'Scimitar' type: 'upgrade' count: 1 } { name: 'Chancellor Palpatine' type: 'upgrade' count: 1 } ] 'Vulture-class Droid Fighter Expansion': [ { name: 'Vulture-class Droid Fighter' type: 'ship' count: 1 } { name: 'Haor Chall Prototype' type: 'pilot' count: 1 } { name: 'Separatist Drone' type: 'pilot' count: 1 } { name: 'Precise Hunter' type: 'pilot' count: 1 } { name: 'DFS-311' type: 'pilot' count: 1 } { name: 'Trade Federation Drone' type: 'pilot' count: 1 } { name: 'Grappling Struts' type: 'upgrade' count: 1 } { name: 'Energy-Shell Charges' type: 'upgrade' count: 1 } { name: 'Discord Missiles' type: 'upgrade' count: 1 } { name: 'Munitions Failsafe' type: 'upgrade' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } ] 'Guardians of the Republic Squadron Pack': [ { name: 'Delta-7 Aethersprite' type: 'ship' count: 1 } { name: 'V-19 Torrent' type: 'ship' count: 2 } { name: 'Obi-Wan Kenobi' type: 'pilot' count: 1 } { name: 'Plo Koon' type: 'pilot' count: 1 } { name: 'Mace Windu' type: 'pilot' count: 1 } { name: 'Saesee Tiin' type: 'pilot' count: 1 } { name: 'Jedi Knight' type: 'pilot' count: 1 } { name: '"Odd Ball"' type: 'pilot' count: 1 } { name: '"Kickback"' type: 'pilot' count: 1 } { name: '"Swoop"' type: 'pilot' count: 1 } { name: '"Axe"' type: 'pilot' count: 1 } { name: '"Tucker"' type: 'pilot' count: 1 } { name: 'Blue Squadron Protector' type: 'pilot' count: 2 } { name: 'Gold Squadron Trooper' type: 'pilot' count: 2 } { name: 'R4 Astromech' type: 'upgrade' count: 1 } { name: 'R4-P Astromech' type: 'upgrade' count: 1 } { name: 'R5 Astromech' type: 'upgrade' count: 1 } { name: 'R4-P17' type: 'upgrade' count: 1 } { name: 'Delta-7B' type: 'upgrade' count: 1 } { name: 'Calibrated Laser Targeting' type: 'upgrade' count: 1 } { name: 'Brilliant Evasion' type: 'upgrade' count: 1 } { name: 'Battle Meditation' type: 'upgrade' count: 1 } { name: 'Predictive Shot' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Concussion Missiles' type: 'upgrade' count: 2 } { name: 'Homing Missiles' type: 'upgrade' count: 2 } { name: 'Proton Rockets' type: 'upgrade' count: 2 } { name: 'Composure' type: 'upgrade' count: 2 } { name: 'Crack Shot' type: 'upgrade' count: 2 } { name: 'Dedicated' type: 'upgrade' count: 2 } { name: 'Expert Handling' type: 'upgrade' count: 2 } { name: 'Intimidation' type: 'upgrade' count: 2 } { name: 'Juke' type: 'upgrade' count: 2 } { name: 'Lone Wolf' type: 'upgrade' count: 1 } { name: 'Marksmanship' type: 'upgrade' count: 2 } { name: 'Saturation Salvo' type: 'upgrade' count: 2 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: 'Trick Shot' type: 'upgrade' count: 2 } { name: 'Afterburners' type: 'upgrade' count: 2 } { name: 'Electronic Baffle' type: 'upgrade' count: 1 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Spare Parts Canisters' type: 'upgrade' count: 1 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Synchronized Console' type: 'upgrade' count: 3 } ] 'ARC-170 Starfighter Expansion': [ { name: 'ARC-170' type: 'ship' count: 1 } { name: '"Wolffe"' type: 'pilot' count: 1 } { name: '"Sinker"' type: 'pilot' count: 1 } { name: '"Odd Ball" (ARC-170)' type: 'pilot' count: 1 } { name: '"Jag"' type: 'pilot' count: 1 } { name: 'Squad Seven Veteran' type: 'pilot' count: 1 } { name: '104th Battalion Pilot' type: 'pilot' count: 1 } { name: 'Dedicated' type: 'upgrade' count: 1 } { name: 'R4-P44' type: 'upgrade' count: 1 } { name: 'Chancellor Palpatine' type: 'upgrade' count: 1 } { name: 'Clone Commander Cody' type: 'upgrade' count: 1 } { name: 'Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'Seventh Fleet Gunner' type: 'upgrade' count: 1 } { name: 'Synchronized Console' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } ] 'Delta-7 Aethersprite Expansion': [ { name: 'Delta-7 Aethersprite' type: 'ship' count: 1 } { name: 'Anakin Skywalker' type: 'pilot' count: 1 } { name: 'Ahsoka Tano' type: 'pilot' count: 1 } { name: 'Barriss Offee' type: 'pilot' count: 1 } { name: 'Luminara Unduli' type: 'pilot' count: 1 } { name: 'Jedi Knight' type: 'pilot' count: 1 } { name: 'Delta-7B' type: 'upgrade' count: 1 } { name: 'Calibrated Laser Targeting' type: 'upgrade' count: 1 } { name: 'R4-P Astromech' type: 'upgrade' count: 1 } { name: 'R3 Astromech' type: 'upgrade' count: 1 } { name: 'Brilliant Evasion' type: 'upgrade' count: 1 } { name: 'Battle Meditation' type: 'upgrade' count: 1 } { name: 'Composure' type: 'upgrade' count: 1 } { name: 'Dedicated' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } { name: 'Juke' type: 'upgrade' count: 1 } { name: 'Saturation Salvo' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } ] 'Z-95-AF4 Headhunter Expansion Pack': [ { name: 'Z-95 Headhunter' type: 'ship' count: 1 } { name: "N'dru Suhlak" type: 'pilot' count: 1 } { name: "Kaa'to Leeachos" type: 'pilot' count: 1 } { name: 'Black Sun Soldier' type: 'pilot' count: 1 } { name: 'Binayre Pirate' type: 'pilot' count: 1 } { name: 'Crack Shot' type: 'upgrade' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: "Deadman's Switch" type: 'upgrade' count: 1 } { name: 'Munitions Failsafe' type: 'upgrade' count: 1 } ] 'TIE/sk Striker Expansion Pack': [ { name: 'TIE Striker' type: 'ship' count: 1 } { name: '"Countdown"' type: 'pilot' count: 1 } { name: '"Pure Sabacc"' type: 'pilot' count: 1 } { name: '"Duchess"' type: 'pilot' count: 1 } { name: 'Black Squadron Scout' type: 'pilot' count: 1 } { name: 'Planetary Sentinel' type: 'pilot' count: 1 } { name: 'Proton Bombs' type: 'upgrade' count: 1 } { name: 'Conner Nets' type: 'upgrade' count: 1 } { name: 'Skilled Bombardier' type: 'upgrade' count: 1 } { name: 'Trick Shot' type: 'upgrade' count: 1 } { name: 'Intimidation' type: 'upgrade' count: 1 } ] 'Naboo Royal N-1 Starfighter Expansion Pack': [ { name: 'Naboo Royal N-1 Starfighter' type: 'ship' count: 1 } { name: 'Ric Olié' type: 'pilot' count: 1 } { name: 'Anakin Skywalker (N-1 Starfighter)' type: 'pilot' count: 1 } { name: 'Padmé Amidala' type: 'pilot' count: 1 } { name: 'Dineé Ellberger' type: 'pilot' count: 1 } { name: 'Naboo Handmaiden' type: 'pilot' count: 1 } { name: 'Bravo Flight Officer' type: 'pilot' count: 1 } { name: 'Daredevil' type: 'upgrade' count: 1 } { name: 'Collision Detector' type: 'upgrade' count: 1 } { name: 'Passive Sensors' type: 'upgrade' count: 1 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'R2-A6' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 1 } { name: 'R2-C4' type: 'upgrade' count: 1 } { name: 'R4 Astromech' type: 'upgrade' count: 1 } ] 'Hyena-Class Droid Bomber Expansion Pack': [ { name: 'Hyena-Class Droid Bomber' type: 'ship' count: 1 } { name: 'DBS-404' type: 'pilot' count: 1 } { name: 'DBS-32C' type: 'pilot' count: 1 } { name: 'Bombardment Drone' type: 'pilot' count: 1 } { name: 'Baktoid Prototype' type: 'pilot' count: 1 } { name: 'Techno Union Bomber' type: 'pilot' count: 1 } { name: 'Separatist Bomber' type: 'pilot' count: 1 } { name: 'Passive Sensors' type: 'upgrade' count: 1 } { name: 'Trajectory Simulator' type: 'upgrade' count: 1 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'Barrage Rockets' type: 'upgrade' count: 1 } { name: 'Diamond-Boron Missiles' type: 'upgrade' count: 1 } { name: 'TA-175' type: 'upgrade' count: 1 } { name: 'Bomblet Generator' type: 'upgrade' count: 1 } { name: 'Electro-Proton Bomb' type: 'upgrade' count: 1 } { name: 'Delayed Fuses' type: 'upgrade' count: 1 } { name: 'Landing Struts' type: 'upgrade' count: 1 } ] 'A/SF-01 B-Wing Expansion Pack': [ { name: 'B-Wing' type: 'ship' count: 1 } { name: 'Braylen Stramm' type: 'pilot' count: 1 } { name: 'Ten Numb' type: 'pilot' count: 1 } { name: 'Blade Squadron Veteran' type: 'pilot' count: 1 } { name: 'Blue Squadron Pilot' type: 'pilot' count: 1 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 1 } { name: 'Ion Cannon' type: 'upgrade' count: 1 } { name: 'Jamming Beam' type: 'upgrade' count: 1 } { name: 'Afterburners' type: 'upgrade' count: 1 } { name: 'Electronic Baffle' type: 'upgrade' count: 1 } { name: 'Fire-Control System' type: 'upgrade' count: 1 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 1 } ] 'Millennium Falcon Expansion Pack': [ { name: 'YT-1300' type: 'ship' count: 1 } { name: 'Han Solo' type: 'pilot' count: 1 } { name: 'Chewbacca' type: 'pilot' count: 1 } { name: 'Lando Calrissian' type: 'pilot' count: 1 } { name: 'Outer Rim Smuggler' type: 'pilot' count: 1 } { name: 'C-3PO' type: 'upgrade' count: 1 } { name: 'Chewbacca' type: 'upgrade' count: 1 } { name: 'Informant' type: 'upgrade' count: 1 } { name: 'Lando Calrissian' type: 'upgrade' count: 1 } { name: 'Leia Organa' type: 'upgrade' count: 1 } { name: 'Nien Nunb' type: 'upgrade' count: 1 } { name: 'Homing Missiles' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } { name: 'Millennium Falcon' type: 'upgrade' count: 1 } ] 'VT-49 Decimator Expansion Pack': [ { name: 'VT-49 Decimator' type: 'ship' count: 1 } { name: 'Rear Admiral Chiraneau' type: 'pilot' count: 1 } { name: 'Captain Oicunn' type: 'pilot' count: 1 } { name: 'Patrol Leader' type: 'pilot' count: 1 } { name: 'Lone Wolf' type: 'upgrade' count: 1 } { name: 'Agent Kallus' type: 'upgrade' count: 1 } { name: 'Darth Vader' type: 'upgrade' count: 1 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 1 } { name: 'Grand Inquisitor' type: 'upgrade' count: 1 } { name: 'Seventh Sister' type: 'upgrade' count: 1 } { name: 'BT-1' type: 'upgrade' count: 1 } { name: '0-0-0' type: 'upgrade' count: 1 } ] 'TIE/VN Silencer Expansion Pack': [ { name: 'TIE/VN Silencer' type: 'ship' count: 1 } { name: 'Kylo Ren' type: 'pilot' count: 1 } { name: '"Blackout"' type: 'pilot' count: 1 } { name: '"Recoil"' type: 'pilot' count: 1 } { name: '"Avenger"' type: 'pilot' count: 1 } { name: 'First Order Test Pilot' type: 'pilot' count: 1 } { name: 'Sienar-Jaemus Engineer' type: 'pilot' count: 1 } { name: 'Hate' type: 'upgrade' count: 1 } { name: 'Predictive Shot' type: 'upgrade' count: 1 } { name: 'Marksmanship' type: 'upgrade' count: 1 } { name: 'Primed Thrusters' type: 'upgrade' count: 1 } { name: 'Collision Detector' type: 'upgrade' count: 1 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 1 } ] 'TIE/SF Fighter Expansion Pack': [ { name: 'TIE/SF Fighter' type: 'ship' count: 1 } { name: '"Quickdraw"' type: 'pilot' count: 1 } { name: '"Backdraft"' type: 'pilot' count: 1 } { name: 'Omega Squadron Expert' type: 'pilot' count: 1 } { name: 'Zeta Squadron Survivor' type: 'pilot' count: 1 } { name: 'Hotshot Gunner' type: 'upgrade' count: 1 } { name: 'Special Forces Gunner' type: 'upgrade' count: 1 } { name: 'Ion Missiles' type: 'upgrade' count: 1 } { name: 'Afterburners' type: 'upgrade' count: 1 } { name: 'Collision Detector' type: 'upgrade' count: 1 } { name: 'Juke' type: 'upgrade' count: 1 } { name: 'Pattern Analyzer' type: 'upgrade' count: 1 } ] 'Resistance Transport Expansion Pack': [ { name: 'Resistance Transport' type: 'ship' count: 1 } { name: 'Resistance Transport Pod' type: 'ship' count: 1 } { name: 'BB-8' type: 'pilot' count: 1 } { name: 'Finn' type: 'pilot' count: 1 } { name: 'Rose Tico' type: 'pilot' count: 1 } { name: 'Vi Moradi' type: 'pilot' count: 1 } { name: 'Cova Nell' type: 'pilot' count: 1 } { name: 'Pammich Nerro Goode' type: 'pilot' count: 1 } { name: 'Nodin Chavdri' type: 'pilot' count: 1 } { name: 'Logistics Division Pilot' type: 'pilot' count: 1 } { name: 'Composure' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } { name: 'Passive Sensors' type: 'upgrade' count: 1 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'Autoblasters' type: 'upgrade' count: 1 } { name: 'Amilyn Holdo' type: 'upgrade' count: 1 } { name: 'Leia Organa (Resistance)' type: 'upgrade' count: 1 } { name: 'GA-97' type: 'upgrade' count: 1 } { name: 'Kaydel Connix' type: 'upgrade' count: 1 } { name: 'Korr Sella' type: 'upgrade' count: 1 } { name: "Larma D'Acy" type: 'upgrade' count: 1 } { name: 'PZ-4CO' type: 'upgrade' count: 1 } { name: 'R2-HA' type: 'upgrade' count: 1 } { name: 'R5-X3' type: 'upgrade' count: 1 } { name: 'Afterburners' type: 'upgrade' count: 1 } { name: 'Angled Deflectors' type: 'upgrade' count: 1 } { name: 'Spare Parts Canisters' type: 'upgrade' count: 1 } ] 'BTL-B Y-Wing Expansion Pack': [ { name: 'BTL-B Y-Wing' type: 'ship' count: 1 } { name: 'Anakin Skywalker (Y-Wing)' type: 'pilot' count: 1 } { name: '"Odd Ball" (Y-Wing)' type: 'pilot' count: 1 } { name: '"Matchstick"' type: 'pilot' count: 1 } { name: '"Broadside"' type: 'pilot' count: 1 } { name: 'R2-D2' type: 'pilot' count: 1 } { name: '"Goji"' type: 'pilot' count: 1 } { name: 'Shadow Squadron Veteran' type: 'pilot' count: 1 } { name: 'Red Squadron Bomber' type: 'pilot' count: 1 } { name: 'Precognitive Reflexes' type: 'upgrade' count: 1 } { name: 'Foresight' type: 'upgrade' count: 1 } { name: 'Snap Shot' type: 'upgrade' count: 1 } { name: 'Ahsoka Tano' type: 'upgrade' count: 1 } { name: 'C-3PO (Republic)' type: 'upgrade' count: 1 } { name: 'C1-10P' type: 'upgrade' count: 1 } { name: 'Delayed Fuses' type: 'upgrade' count: 1 } { name: 'Electro-Proton Bomb' type: 'upgrade' count: 1 } { name: 'Proton Bombs' type: 'upgrade' count: 1 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 1 } ] 'Nantex-class Starfighter Expansion Pack': [ { name: 'Nantex-Class Starfighter' type: 'ship' count: 1 } { name: 'Sun Fac' type: 'pilot' count: 1 } { name: 'Berwer Kret' type: 'pilot' count: 1 } { name: 'Chertek' type: 'pilot' count: 1 } { name: 'Gorgol' type: 'pilot' count: 1 } { name: 'Petranaki Arena Ace' type: 'pilot' count: 1 } { name: 'Stalgasin Hive Guard' type: 'pilot' count: 1 } { name: 'Ensnare' type: 'upgrade' count: 1 } { name: 'Gravitic Deflection' type: 'upgrade' count: 1 } { name: 'Juke' type: 'upgrade' count: 1 } { name: 'Snap Shot' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'upgrade' count: 1 } { name: 'Targeting Computer' type: 'upgrade' count: 1 } ] 'Punishing One Expansion Pack': [ { name: 'JumpMaster 5000' type: 'ship' count: 1 } { name: 'Dengar' type: 'pilot' count: 1 } { name: 'Manaroo' type: 'pilot' count: 1 } { name: 'Tel Trevura' type: 'pilot' count: 1 } { name: 'Contracted Scout' type: 'pilot' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 1 } { name: 'R5-P8' type: 'upgrade' count: 1 } { name: '0-0-0' type: 'upgrade' count: 1 } { name: 'Informant' type: 'upgrade' count: 1 } { name: 'Latts Razzi' type: 'upgrade' count: 1 } { name: 'Dengar' type: 'upgrade' count: 1 } { name: 'Lone Wolf' type: 'upgrade' count: 1 } { name: 'Punishing One' type: 'upgrade' count: 1 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'Ion Torpedoes' type: 'upgrade' count: 1 } { name: 'Contraband Cybernetics' type: 'upgrade' count: 1 } { name: 'Perceptive Copilot' type: 'upgrade' count: 1 } ] 'M3-A Interceptor Expansion Pack': [ { name: 'M3-A Interceptor' type: 'ship' count: 1 } { name: 'Genesis Red' type: 'pilot' count: 1 } { name: 'Inaldra' type: 'pilot' count: 1 } { name: "Laetin A'shera" type: 'pilot' count: 1 } { name: 'Quinn Jast' type: 'pilot' count: 1 } { name: 'Serissu' type: 'pilot' count: 1 } { name: 'Sunny Bounder' type: 'pilot' count: 1 } { name: 'Cartel Spacer' type: 'pilot' count: 1 } { name: 'Tansarii Point Veteran' type: 'pilot' count: 1 } { name: 'Ion Cannon' type: 'upgrade' count: 1 } { name: 'Jamming Beam' type: 'upgrade' count: 1 } { name: 'Proton Torpedoes' type: 'upgrade' count: 1 } { name: 'Ion Missiles' type: 'upgrade' count: 1 } { name: 'Intimidation' type: 'upgrade' count: 1 } ] 'Ghost Expansion Pack': [ { name: 'VCX-100' type: 'ship' count: 1 } { name: 'Sheathipede-Class Shuttle' type: 'ship' count: 1 } { name: 'AP-5' type: 'pilot' count: 1 } { name: 'Fenn Rau (Sheathipede)' type: 'pilot' count: 1 } { name: "Ezra Bridger (Sheathipede)" type: 'pilot' count: 1 } { name: '"Zeb" Orrelios (Sheathipede)' type: 'pilot' count: 1 } { name: 'Hera Syndulla (VCX-100)' type: 'pilot' count: 1 } { name: 'Kanan Jarrus' type: 'pilot' count: 1 } { name: '"Chopper"' type: 'pilot' count: 1 } { name: 'Lothal Rebel' type: 'pilot' count: 1 } { name: '"Chopper" (Astromech)' type: 'upgrade' count: 1 } { name: '"Chopper" (Crew)' type: 'upgrade' count: 1 } { name: 'Hera Syndulla' type: 'upgrade' count: 1 } { name: 'Kanan Jarrus' type: 'upgrade' count: 1 } { name: 'Maul' type: 'upgrade' count: 1 } { name: '"Zeb" Orrelios' type: 'upgrade' count: 1 } { name: 'Hate' type: 'upgrade' count: 1 } { name: 'Predictive Shot' type: 'upgrade' count: 1 } { name: 'Agile Gunner' type: 'upgrade' count: 1 } { name: 'Tactical Scrambler' type: 'upgrade' count: 1 } { name: 'Collision Detector' type: 'upgrade' count: 1 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Ghost' type: 'upgrade' count: 1 } { name: 'Phantom' type: 'upgrade' count: 1 } { name: 'Ion Torpedoes' type: 'upgrade' count: 1 } { name: 'Dorsal Turret' type: 'upgrade' count: 1 } ] "Inquisitors' TIE Expansion Pack": [ { name: 'TIE Advanced Prototype' type: 'ship' count: 1 } { name: 'Grand Inquisitor' type: 'pilot' count: 1 } { name: 'Seventh Sister' type: 'pilot' count: 1 } { name: 'Inquisitor' type: 'pilot' count: 1 } { name: 'Baron of the Empire' type: 'pilot' count: 1 } { name: 'Hate' type: 'upgrade' count: 1 } { name: 'Predictive Shot' type: 'upgrade' count: 1 } { name: 'Heightened Perception' type: 'upgrade' count: 1 } { name: 'Proton Rockets' type: 'upgrade' count: 1 } { name: 'Afterburners' type: 'upgrade' count: 1 } ] 'Loose Ships': [ { name: 'A-Wing' type: 'ship' count: 3 } { name: 'Auzituck Gunship' type: 'ship' count: 2 } { name: 'E-Wing' type: 'ship' count: 2 } { name: 'HWK-290' type: 'ship' count: 2 } { name: 'K-Wing' type: 'ship' count: 2 } { name: 'YT-1300' type: 'ship' count: 2 } { name: 'Attack Shuttle' type: 'ship' count: 2 } { name: 'YT-2400' type: 'ship' count: 2 } { name: 'Alpha-Class Star Wing' type: 'ship' count: 3 } { name: 'Lambda-Class Shuttle' type: 'ship' count: 2 } { name: 'TIE Aggressor' type: 'ship' count: 3 } { name: 'TIE Bomber' type: 'ship' count: 3 } { name: 'TIE Defender' type: 'ship' count: 2 } { name: 'TIE Interceptor' type: 'ship' count: 3 } { name: 'TIE Phantom' type: 'ship' count: 2 } { name: 'TIE Punisher' type: 'ship' count: 2 } { name: 'Kihraxz Fighter' type: 'ship' count: 3 } { name: 'YV-666' type: 'ship' count: 2 } { name: 'Aggressor' type: 'ship' count: 2 } { name: 'HWK-290' type: 'ship' count: 2 } { name: 'M12-L Kimogila Fighter' type: 'ship' count: 2 } { name: 'G-1A Starfighter' type: 'ship' count: 2 } { name: 'Quadjumper' type: 'ship' count: 3 } { name: 'Scurrg H-6 Bomber' type: 'ship' count: 2 } { name: 'Lancer-Class Pursuit Craft' type: 'ship' count: 2 } { name: 'StarViper' type: 'ship' count: 2 } { name: 'MG-100 StarFortress' type: 'ship' count: 3 } { name: 'TIE/SF Fighter' type: 'ship' count: 3 } { name: 'TIE/VN Silencer' type: 'ship' count: 3 } { name: 'Upsilon-Class Command Shuttle' type: 'ship' count: 3 } { name: 'Scavenged YT-1300' type: 'ship' count: 3 } ] class exportObj.Collection constructor: (args) -> @expansions = args.expansions ? {} @singletons = args.singletons ? {} @checks = args.checks ? {} # To save collection (optional) @backend = args.backend @setupUI() @setupHandlers() @reset() @language = 'English' reset: -> @shelf = {} @table = {} for expansion, count of @expansions try count = parseInt count catch count = 0 for _ in [0...count] for card in (exportObj.manifestByExpansion[expansion] ? []) for _ in [0...card.count] ((@shelf[card.type] ?= {})[card.name] ?= []).push expansion for type, counts of @singletons for name, count of counts if count > 0 for _ in [0...count] ((@shelf[type] ?= {})[name] ?= []).push 'singleton' else if count < 0 for _ in [0...count] if ((@shelf[type] ?= {})[name] ?= []).length > 0 @shelf[type][name].pop() @counts = {} for own type of @shelf for own thing of @shelf[type] (@counts[type] ?= {})[thing] ?= 0 @counts[type][thing] += @shelf[type][thing].length # Create list of released singletons singletonsByType = {} for expname, items of exportObj.manifestByExpansion for item in items (singletonsByType[item.type] ?= {})[item.name] = true for type, names of singletonsByType sorted_names = (name for name of names).sort((a,b) -> sortWithoutQuotes(a,b,type)) singletonsByType[type] = sorted_names component_content = $ @modal.find('.collection-inventory-content') component_content.text '' card_totals_by_type = {} card_different_by_type = {} for own type, things of @counts if singletonsByType[type]? card_totals_by_type[type] = 0 card_different_by_type[type] = 0 contents = component_content.append $.trim """ <div class="row-fluid"> <div class="span12"><h5>#{type.capitalize()}</h5></div> </div> <div class="row-fluid"> <ul id="counts-#{type}" class="span12"></ul> </div> """ ul = $ contents.find("ul#counts-#{type}") for thing in Object.keys(things).sort((a,b) -> sortWithoutQuotes(a,b,type)) card_totals_by_type[type] += things[thing] if thing in singletonsByType[type] card_different_by_type[type]++ if type == 'pilot' ul.append """<li>#{if exportObj.pilots[thing].display_name then exportObj.pilots[thing].display_name else thing} - #{things[thing]}</li>""" if type == 'upgrade' ul.append """<li>#{if exportObj.upgrades[thing].display_name then exportObj.upgrades[thing].display_name else thing} - #{things[thing]}</li>""" if type == 'ship' ul.append """<li>#{if exportObj.ships[thing].display_name then exportObj.ships[thing].display_name else thing} - #{things[thing]}</li>""" summary = "" for type in Object.keys(card_totals_by_type) summary += """<li>#{type.capitalize()} - #{card_totals_by_type[type]} (#{card_different_by_type[type]} different)</li>""" component_content.append $.trim """ <div class="row-fluid"> <div class="span12"><h5>Summary</h5></div> </div> <div class = "row-fluid"> <ul id="counts-summary" class="span12"> #{summary} </ul> </div> """ check: (where, type, name) -> (((where[type] ? {})[name] ? []).length ? 0) != 0 checkShelf: (type, name) -> @check @shelf, type, name checkTable: (type, name) -> @check @table, type, name use: (type, name) -> try card = @shelf[type][name].pop() catch e return false unless card? if card? ((@table[type] ?= {})[name] ?= []).push card true else false release: (type, name) -> try card = @table[type][name].pop() catch e return false unless card? if card? ((@shelf[type] ?= {})[name] ?= []).push card true else false save: (cb=$.noop) -> @backend.saveCollection(this, cb) if @backend? @load: (backend, cb) -> backend.loadCollection cb setupUI: -> # Create list of released singletons singletonsByType = {} for expname, items of exportObj.manifestByExpansion for item in items (singletonsByType[item.type] ?= {})[item.name] = true for type, names of singletonsByType sorted_names = (name for name of names).sort((a,b) -> sortWithoutQuotes(a,b,type)) singletonsByType[type] = sorted_names @modal = $ document.createElement 'DIV' @modal.addClass 'modal hide fade collection-modal hidden-print' $('body').append @modal @modal.append $.trim """ <div class="modal-header"> <button type="button" class="close hidden-print" data-dismiss="modal" aria-hidden="true">&times;</button> <h4>Your Collection</h4> </div> <div class="modal-body"> <ul class="nav nav-tabs"> <li class="active"><a data-target="#collection-expansions" data-toggle="tab">Expansions</a><li> <li><a data-target="#collection-ships" data-toggle="tab">Ships</a><li> <li><a data-target="#collection-pilots" data-toggle="tab">Pilots</a><li> <li><a data-target="#collection-upgrades" data-toggle="tab">Upgrades</a><li> <li><a data-target="#collection-components" data-toggle="tab">Inventory</a><li> </ul> <div class="tab-content"> <div id="collection-expansions" class="tab-pane active container-fluid collection-content"></div> <div id="collection-ships" class="tab-pane active container-fluid collection-ship-content"></div> <div id="collection-pilots" class="tab-pane active container-fluid collection-pilot-content"></div> <div id="collection-upgrades" class="tab-pane active container-fluid collection-upgrade-content"></div> <div id="collection-components" class="tab-pane container-fluid collection-inventory-content"></div> </div> </div> <div class="modal-footer hidden-print"> <span class="collection-status"></span> &nbsp; <label class="checkbox-check-collection"> Check Collection Requirements <input type="checkbox" class="check-collection"/> </label> &nbsp; <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> """ @modal_status = $ @modal.find('.collection-status') if @checks.collectioncheck? if @checks.collectioncheck != "false" @modal.find('.check-collection').prop('checked', true) else @checks.collectioncheck = true @modal.find('.check-collection').prop('checked', true) @modal.find('.checkbox-check-collection').show() collection_content = $ @modal.find('.collection-content') for expansion in exportObj.expansions count = parseInt(@expansions[expansion] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="expansion-count" type="number" size="3" value="#{count}" /> <span class="expansion-name">#{expansion}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'expansion', expansion input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.expansion-name').data 'name', expansion if expansion != 'Loose Ships' or 'Hyperspace' collection_content.append row shipcollection_content = $ @modal.find('.collection-ship-content') for ship in singletonsByType.ship count = parseInt(@singletons.ship?[ship] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="ship-name">#{if exportObj.ships[ship].display_name then exportObj.ships[ship].display_name else ship}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'ship' input.data 'singletonName', ship input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.ship-name').data 'name', ship shipcollection_content.append row pilotcollection_content = $ @modal.find('.collection-pilot-content') for pilot in singletonsByType.pilot count = parseInt(@singletons.pilot?[pilot] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="pilot-name">#{if exportObj.pilots[pilot].display_name then exportObj.pilots[pilot].display_name else pilot}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'pilot' input.data 'singletonName', pilot input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.pilot-name').data 'name', pilot pilotcollection_content.append row upgradecollection_content = $ @modal.find('.collection-upgrade-content') for upgrade in singletonsByType.upgrade count = parseInt(@singletons.upgrade?[upgrade] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="upgrade-name">#{if exportObj.upgrades[upgrade].display_name then exportObj.upgrades[upgrade].display_name else upgrade}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'upgrade' input.data 'singletonName', upgrade input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.upgrade-name').data 'name', upgrade upgradecollection_content.append row destroyUI: -> @modal.modal 'hide' @modal.remove() $(exportObj).trigger 'xwing-collection:destroyed', this setupHandlers: -> $(exportObj).trigger 'xwing-collection:created', this $(exportObj).on 'xwing-backend:authenticationChanged', (e, authenticated, backend) => # console.log "deauthed, destroying collection UI" @destroyUI() unless authenticated .on 'xwing-collection:saved', (e, collection) => @modal_status.text 'Collection saved' @modal_status.fadeIn 100, => @modal_status.fadeOut 1000 .on 'xwing:languageChanged', @onLanguageChange .on 'xwing:CollectionCheck', @onCollectionCheckSet $ @modal.find('input.expansion-count').change (e) => target = $(e.target) val = target.val() target.val(0) if val < 0 or isNaN(parseInt(val)) @expansions[target.data 'expansion'] = parseInt(target.val()) target.closest('div').css 'background-color', @countToBackgroundColor(target.val()) # console.log "Input changed, triggering collection change" $(exportObj).trigger 'xwing-collection:changed', this $ @modal.find('input.singleton-count').change (e) => target = $(e.target) val = target.val() target.val(0) if isNaN(parseInt(val)) (@singletons[target.data 'singletonType'] ?= {})[target.data 'singletonName'] = parseInt(target.val()) target.closest('div').css 'background-color', @countToBackgroundColor(target.val()) # console.log "Input changed, triggering collection change" $(exportObj).trigger 'xwing-collection:changed', this $ @modal.find('.check-collection').change (e) => if @modal.find('.check-collection').prop('checked') == false result = false @modal_status.text """Collection Tracking Disabled""" else result = true @modal_status.text """Collection Tracking Active""" @checks.collectioncheck = result @modal_status.fadeIn 100, => @modal_status.fadeOut 1000 $(exportObj).trigger 'xwing-collection:changed', this countToBackgroundColor: (count) -> count = parseInt(count) switch when count < 0 'red' when count == 0 '' when count > 0 i = parseInt(200 * Math.pow(0.9, count - 1)) "rgb(#{i}, 255, #{i})" else '' onLanguageChange: (e, language) => @language = language if language != @old_language @old_language = language # console.log "language changed to #{language}" do (language) => @modal.find('.expansion-name').each -> # console.log "translating #{$(this).text()} (#{$(this).data('name')}) to #{language}" $(this).text exportObj.translate language, 'sources', $(this).data('name') @modal.find('.ship-name').each -> $(this).text (if exportObj.ships[$(this).data('name')].display_name then exportObj.ships[$(this).data('name')].display_name else $(this).data('name')) @modal.find('.pilot-name').each -> $(this).text (if exportObj.pilots[$(this).data('name')].display_name then exportObj.pilots[$(this).data('name')].display_name else $(this).data('name')) @modal.find('.upgrade-name').each -> $(this).text (if exportObj.upgrades[$(this).data('name')].display_name then exportObj.upgrades[$(this).data('name')].display_name else $(this).data('name'))
75613
exportObj = exports ? this String::startsWith ?= (t) -> @indexOf t == 0 sortWithoutQuotes = (a, b, type = '') -> a_name = displayName(a,type).replace /[^a-z0-9]/ig, '' b_name = displayName(b,type).replace /[^a-z0-9]/ig, '' if a_name < b_name -1 else if a_name > b_name 1 else 0 displayName = (name, type) -> obj = undefined if type == 'ship' obj = exportObj.ships[name] else if type == 'upgrade' obj = exportObj.upgrades[name] else if type == 'pilot' obj = exportObj.pilots[name] else return name if obj and obj.display_name return obj.display_name return name exportObj.manifestBySettings = 'collectioncheck': true exportObj.manifestByExpansion = 'Second Edition Core Set': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Black Squadron Ace' type: 'pilot' count: 2 } { name: '"Night Beast"' type: 'pilot' count: 1 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 2 } { name: 'Academy Pilot' type: 'pilot' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME> Re<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>-<NAME>2' type: 'upgrade' count: 1 } { name: 'R3 <NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'R5-D8' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] "Saw's Renegades Expansion Pack" : [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 3 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'TIE Reaper Expansion Pack' : [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>oph' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME> Base Pi<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'ISB Slicer' type: 'upgrade' count: 2 } { name: '<NAME>actical Offic<NAME>' type: 'upgrade' count: 2 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } ] 'Rebel Alliance Conversion Kit': [ { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (Y-<NAME>)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (X-Wing)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> Squadron E<NAME>' type: 'pilot' count: 2 } { name: 'Red Squadron Veteran' type: 'pilot' count: 2 } { name: '"<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Gold Squadron Veteran' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Green Squadron Pilot' type: 'pilot' count: 2 } { name: 'Phoenix Squadron Pilot' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Blue Squadron Pilot' type: 'pilot' count: 2 } { name: 'Blade <NAME>ron <NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> Squadron Pi<NAME>' type: 'pilot' count: 3 } { name: 'Tala Squadron Pilot' type: 'pilot' count: 3 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>' type: 'pilot' count: 1 } { name: 'AP-<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (Sheathipe<NAME>)' type: 'pilot' count: 1 } { name: '<NAME> (Sheathipe<NAME>)' type: 'pilot' count: 1 } { name: '"<NAME>" <NAME> (Sheathipede)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (TIE Fighter)' type: 'pilot' count: 1 } { name: '<NAME> (TIE Fighter)' type: 'pilot' count: 1 } { name: '"<NAME>" <NAME> (TIE Fighter)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Blue Squadron Scout' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Warden Squadron Pilot' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME> (VCX-100)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> Tact<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'Cloaking Device' type: 'upgrade' count: 1 } { name: 'Contraband Cybernetics' type: 'upgrade' count: 2 } { name: "<NAME>" type: 'upgrade' count: 2 } { name: 'Feedback Array' type: 'upgrade' count: 2 } { name: 'Inertial Dampeners' type: 'upgrade' count: 2 } { name: '<NAME>igged Cargo Chute' type: 'upgrade' count: 2 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 2 } { name: 'Ion Cannon' type: 'upgrade' count: 2 } { name: '<NAME>ming Be<NAME>' type: 'upgrade' count: 2 } { name: 'Tractor Beam' type: 'upgrade' count: 2 } { name: 'Dorsal Turret' type: 'upgrade' count: 2 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '"<NAME>" (Crew)' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Novice Technician' type: 'upgrade' count: 2 } { name: 'Perceptive Copilot' type: 'upgrade' count: 2 } { name: 'R2-D2 (Crew)' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Seasoned Navigator' type: 'upgrade' count: 1 } { name: 'Tactical Officer' type: 'upgrade' count: 1 } { name: '"<NAME>" Or<NAME>' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Concussion Missiles' type: 'upgrade' count: 2 } { name: 'Homing Missiles' type: 'upgrade' count: 2 } { name: 'Ion Missiles' type: 'upgrade' count: 2 } { name: 'Proton Rockets' type: 'upgrade' count: 2 } { name: 'Bomblet Generator' type: 'upgrade' count: 1 } { name: '<NAME>ner Nets' type: 'upgrade' count: 2 } { name: 'Proton Bombs' type: 'upgrade' count: 2 } { name: 'Proximity Mines' type: 'upgrade' count: 2 } { name: 'Seismic <NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '"<NAME>" (Astromech)' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 2 } { name: 'R3 Astromech' type: 'upgrade' count: 2 } { name: 'R4 Astromech' type: 'upgrade' count: 2 } { name: 'R5 Astromech' type: 'upgrade' count: 2 } { name: 'Ablative Plating' type: 'upgrade' count: 2 } { name: 'Advanced SLAM' type: 'upgrade' count: 2 } { name: 'Electronic Baffle' type: 'upgrade' count: 2 } { name: 'Engine Upgrade' type: 'upgrade' count: 2 } { name: 'Hull Upgrade' type: 'upgrade' count: 2 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: '<NAME>actical Scrambler' type: 'upgrade' count: 2 } ] 'Galactic Empire Conversion Kit': [ { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>" <NAME>' type: 'pilot' count: 1 } { name: '"<NAME>" <NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: 'Black Squadron Ace' type: 'pilot' count: 4 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 4 } { name: '<NAME>cademy Pilot' type: 'pilot' count: 4 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Storm Squadron Ace' type: 'pilot' count: 2 } { name: 'Tempest Squadron Pilot' type: 'pilot' count: 2 } { name: '<NAME>itor' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 3 } { name: '<NAME>' type: 'pilot' count: 3 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Alpha Squadron Pilot' type: 'pilot' count: 2 } { name: 'Saber Squadron Ace' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: 'Gamma Squadron Ace' type: 'pilot' count: 3 } { name: 'Scimitar Squadron Pilot' type: 'pilot' count: 3 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: 'Black Squadron Scout' type: 'pilot' count: 3 } { name: 'Planetary Sentinel' type: 'pilot' count: 3 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Onyx Squadron Ace' type: 'pilot' count: 2 } { name: 'Delta Squadron Pilot' type: 'pilot' count: 2 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Onyx Squadron Scout' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: "Sigma Squadron Ace" type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Rho Squadron Pilot' type: 'pilot' count: 2 } { name: 'Nu Squadron Pilot' type: 'pilot' count: 2 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: 'Cutlass Squadron Pilot' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>ron Group Pilot' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: '<NAME> Shot' type: 'upgrade' count: 3 } { name: '<NAME> Sensors' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'Trajectory Simulator' type: 'upgrade' count: 2 } { name: '<NAME>avy Laser Cannon' type: 'upgrade' count: 2 } { name: 'Ion Cannon' type: 'upgrade' count: 2 } { name: '<NAME>amming Beam' type: 'upgrade' count: 2 } { name: '<NAME>actor Beam' type: 'upgrade' count: 2 } { name: '<NAME>orsal Turret' type: 'upgrade' count: 2 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 2 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 3 } { name: 'Ion Torpedoes' type: 'upgrade' count: 3 } { name: 'Proton Torpedoes' type: 'upgrade' count: 3 } { name: 'Barrage Rockets' type: 'upgrade' count: 3 } { name: 'Cluster Missiles' type: 'upgrade' count: 3 } { name: 'Concussion Missiles' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME> "<NAME>" <NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>nician' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>let <NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>imity M<NAME>' type: 'upgrade' count: 3 } { name: 'Seismic Char<NAME>' type: 'upgrade' count: 3 } { name: 'Dauntless' type: 'upgrade' count: 1 } { name: 'ST-321' type: 'upgrade' count: 1 } { name: 'Os-1 Arsenal Loadout' type: 'upgrade' count: 3 } { name: 'Xg-1 Assault Configuration' type: 'upgrade' count: 3 } { name: 'Ablative Plating' type: 'upgrade' count: 2 } { name: 'Advanced SLAM' type: 'upgrade' count: 2 } { name: 'Electronic Baffle' type: 'upgrade' count: 2 } { name: 'Hull Upgrade' type: 'upgrade' count: 2 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } ] 'Scum and Villainy Conversion Kit': [ { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 3 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 3 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 2 } { name: "<NAME>" type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 3 } { name: '<NAME>' type: 'pilot' count: 3 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 3 } { name: '<NAME> (StarViper)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 4 } { name: '<NAME>' type: 'pilot' count: 4 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 3 } { name: '<NAME>' type: 'pilot' count: 3 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>-8<NAME>' type: 'pilot' count: 1 } { name: '<NAME>-8<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (<NAME>)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'Expert Handling' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'Advanced Sensors' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'Trajectory Simulator' type: 'upgrade' count: 2 } { name: 'Cloaking Device' type: 'upgrade' count: 1 } { name: '<NAME>net<NAME>' type: 'upgrade' count: 2 } { name: "<NAME>" type: 'upgrade' count: 3 } { name: 'Feedback <NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME> Laser C<NAME>' type: 'upgrade' count: 2 } { name: '<NAME> Cannon' type: 'upgrade' count: 2 } { name: '<NAME>amming Beam' type: 'upgrade' count: 2 } { name: '<NAME>actor Be<NAME>' type: 'upgrade' count: 2 } { name: 'Dorsal Turret' type: 'upgrade' count: 2 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 2 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 2 } { name: 'Ion Torpedoes' type: 'upgrade' count: 2 } { name: 'Proton Torpedoes' type: 'upgrade' count: 2 } { name: '0-0-0' type: 'upgrade' count: 1 } { name: '4-LOM' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 2 } { name: 'IG-88D' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Novice Technician' type: 'upgrade' count: 2 } { name: '<NAME>ceptive Copilot' type: 'upgrade' count: 2 } { name: '<NAME>ed Navigator' type: 'upgrade' count: 2 } { name: '<NAME>actical Offic<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME> Missiles' type: 'upgrade' count: 2 } { name: '<NAME>cussion Miss<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>iss<NAME>' type: 'upgrade' count: 2 } { name: '<NAME> Rocket<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>omblet Generator' type: 'upgrade' count: 1 } { name: '<NAME>ner N<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>ton B<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>imity Mines' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: 'IG-2000' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'Engine Upgrade' type: 'upgrade' count: 2 } { name: '<NAME>ull <NAME>' type: 'upgrade' count: 2 } { name: '<NAME>itions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Tactical Scrambler' type: 'upgrade' count: 2 } { name: '"<NAME>"' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 2 } { name: 'R3 Astromech' type: 'upgrade' count: 2 } { name: 'R4 Astromech' type: 'upgrade' count: 2 } { name: 'R5 Astromech' type: 'upgrade' count: 2 } { name: 'R5-P8' type: 'upgrade' count: 1 } { name: 'R5-TK' type: 'upgrade' count: 1 } ] 'T-65 X-Wing Expansion Pack' : [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (X-<NAME>ing)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'R<NAME>' type: 'upgrade' count: 1 } { name: 'R4 Ast<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'BTL-A4 Y-Wing Expansion Pack' : [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (Y-Wing)' type: 'pilot' count: 1 } { name: '"<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Ex<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'TIE/ln Fighter Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 1 } { name: 'Academy Pilot' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'upgrade' count: 1 } ] 'TIE Advanced x1 Expansion Pack': [ { name: 'TIE Advanced' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Storm Squadron Ace' type: 'pilot' count: 1 } { name: 'Tempest Squadron Pilot' type: 'pilot' count: 1 } { name: 'Heightened Perception' type: 'upgrade' count: 1 } { name: 'Supernatural Reflexes' type: 'upgrade' count: 1 } { name: 'Ruthless' type: 'upgrade' count: 1 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Fire-Control System' type: 'upgrade' count: 1 } ] 'Slave I Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'Fang Fighter Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] "Lando's Millennium Falcon Expansion Pack": [ { name: 'Customized YT-1300' type: 'ship' count: 1 } { name: 'Escape <NAME>' type: 'ship' count: 1 } { name: '<NAME> (Scum)' type: 'pilot' count: 1 } { name: '<NAME> (Scum)' type: 'pilot' count: 1 } { name: '<NAME>-3<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (Scum) (Escape Craft)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'L3-37 (Escape Craft)' type: 'pilot' count: 1 } { name: 'Autopilot Drone' type: 'pilot' count: 1 } { name: 'L3-<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> (Scum)' type: 'upgrade' count: 1 } { name: '<NAME> (Scum)' type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> Navigator' type: 'upgrade' count: 1 } { name: '<NAME> (Scum)' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'Resistance Conversion Kit': [ { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 3 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (Resistance)' type: 'pilot' count: 1 } { name: '<NAME> (Resistance)' type: 'pilot' count: 1 } { name: 'Resistance Sympathizer' type: 'pilot' count: 3 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Black Squadron Ace (T-70)' type: 'pilot' count: 1 } { name: 'Red Squadron Expert' type: 'pilot' count: 4 } { name: 'Blue Squadron Rookie' type: 'pilot' count: 4 } { name: 'R2-HA' type: 'upgrade' count: 1 } { name: 'BB-8' type: 'upgrade' count: 1 } { name: 'R5-X3' type: 'upgrade' count: 1 } { name: 'BB Astromech' type: 'upgrade' count: 4 } { name: 'R2 Astromech' type: 'upgrade' count: 2 } { name: 'R3 Astromech' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> (Resistance)' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> (Resistance)' type: 'upgrade' count: 1 } { name: '<NAME> (Resistance)' type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 4 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>arm Tactics' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'Advanced Optics' type: 'upgrade' count: 2 } { name: 'Pattern Analyzer' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>ing Synchron<NAME>' type: 'upgrade' count: 2 } { name: 'Advanced Sensors' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'Trajectory Simulator' type: 'upgrade' count: 2 } { name: '<NAME>avy Laser Cannon' type: 'upgrade' count: 2 } { name: 'Ion Cannon' type: 'upgrade' count: 2 } { name: '<NAME>amming Beam' type: 'upgrade' count: 2 } { name: '<NAME>actor Beam' type: 'upgrade' count: 2 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 2 } { name: '<NAME>ton Torpedoes' type: 'upgrade' count: 2 } { name: 'Ion Torpedoes' type: 'upgrade' count: 2 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Concussion Missiles' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: "<NAME>" type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'Proximity Mines' type: 'upgrade' count: 2 } { name: 'Seismic Charges' type: 'upgrade' count: 2 } { name: 'Ablative Plating' type: 'upgrade' count: 2 } { name: 'Advanced SLAM' type: 'upgrade' count: 1 } { name: 'Electronic Baffle' type: 'upgrade' count: 2 } { name: 'Engine Upgrade' type: 'upgrade' count: 2 } { name: 'Hull Upgrade' type: 'upgrade' count: 2 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Tactical Scrambler' type: 'upgrade' count: 2 } ] 'T-70 X-Wing Expansion Pack': [ { name: 'T-70 X-Wing' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Black Squadron Ace (T-70)' type: 'pilot' count: 1 } { name: 'Red Squadron Expert' type: 'pilot' count: 1 } { name: 'Blue <NAME> R<NAME>' type: 'pilot' count: 1 } { name: 'Black One' type: 'upgrade' count: 1 } { name: 'BB-8' type: 'upgrade' count: 1 } { name: 'BB Astromech' type: 'upgrade' count: 1 } { name: 'Integrated S-Foils' type: 'upgrade' count: 1 } { name: 'M9-G8' type: 'upgrade' count: 1 } { name: 'Targeting Synchronizer' type: 'upgrade' count: 1 } ] 'RZ-2 A-Wing Expansion Pack': [ { name: 'RZ-2 A-Wing' type: 'ship' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Green Squadron Expert' type: 'pilot' count: 1 } { name: 'Blue Squadron Recruit' type: 'pilot' count: 1 } { name: 'Heroic' type: 'upgrade' count: 1 } { name: 'Ferrosphere Paint' type: 'upgrade' count: 1 } { name: 'Homing Missiles' type: 'upgrade' count: 1 } { name: 'Primed Thrusters' type: 'upgrade' count: 1 } { name: 'Proton Rockets' type: 'upgrade' count: 1 } ] 'Mining Guild TIE Expansion Pack': [ { name: 'Mining Guild TIE Fighter' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Mining Guild Surveyor' type: 'pilot' count: 1 } { name: 'Mining Guild Sentry' type: 'pilot' count: 1 } { name: 'Hull Upgrade' type: 'upgrade' count: 1 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 1 } { name: 'Elusive' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } { name: 'Trick Shot' type: 'upgrade' count: 1 } ] 'First Order Conversion Kit': [ { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'TN-3465' type: 'pilot' count: 1 } { name: 'Epsilon Squadron Cadet' type: 'pilot' count: 7 } { name: 'Zeta Squadron Pilot' type: 'pilot' count: 7 } { name: 'Omega Squadron Ace' type: 'pilot' count: 6 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: "Omega Squadron Expert" type: 'pilot' count: 4 } { name: "<NAME> Surviv<NAME>" type: 'pilot' count: 5 } { name: "<NAME>" type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: "<NAME> Order Test Pilot" type: 'pilot' count: 3 } { name: "<NAME>" type: 'pilot' count: 3 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>iller Base Pilot" type: 'pilot' count: 3 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "<NAME>space Tracking Data" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 4 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "<NAME>ac<NAME>" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 3 } { name: '<NAME>idation' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'Advanced Optics' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>ing Synchronizer' type: 'upgrade' count: 2 } { name: 'Hyperspace Tracking Data' type: 'upgrade' count: 2 } { name: 'Advanced Sensors' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: '<NAME> Laser Cannon' type: 'upgrade' count: 2 } { name: '<NAME> Cannon' type: 'upgrade' count: 2 } { name: '<NAME>ming Be<NAME>' type: 'upgrade' count: 2 } { name: '<NAME> Be<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>ance <NAME>' type: 'upgrade' count: 2 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>ed Navigator' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'Engine Upgrade' type: 'upgrade' count: 2 } { name: '<NAME>ull Upgrade' type: 'upgrade' count: 2 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Tactical Scrambler' type: 'upgrade' count: 2 } ] 'TIE/FO Fighter Expansion Pack': [ { name: '<NAME>/<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Zeta Squadron Pi<NAME>' type: 'pilot' count: 1 } { name: 'Omega Squadron Ace' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>-3465' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } { name: 'Advanced Optics' type: 'upgrade' count: 1 } { name: 'Targeting Synchronizer' type: 'upgrade' count: 1 } ] 'Servants of Strife Squadron Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: 'Vulture-class Droid Fight<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> Federation Dr<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>-08<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'pilot' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME> T<NAME>' type: 'upgrade' count: 2 } { name: 'T<NAME>erous' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>cussion M<NAME>' type: 'upgrade' count: 2 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Homing Missiles' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: 'Energy-Shell Char<NAME>' type: 'upgrade' count: 2 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Afterburners' type: 'upgrade' count: 3 } { name: '<NAME>ic B<NAME>le' type: 'upgrade' count: 2 } { name: '<NAME>ervium Plating' type: 'upgrade' count: 1 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 3 } { name: 'Stealth Device' type: 'upgrade' count: 3 } ] 'Sith Infiltrator Expansion Pack': [ { name: 'Sith Infiltrator' type: 'ship' count: 1 } { name: '<NAME> Courier' type: 'pilot' count: 1 } { name: '0-66' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>illiant E<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>. Proton <NAME>' type: 'upgrade' count: 1 } { name: '<NAME> Laser Cannon' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'K2-B4' type: 'upgrade' count: 1 } { name: '<NAME>K-1 Probe Droids' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'Vulture-class Droid Fighter Expansion': [ { name: 'Vulture-class Droid Fighter' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>atist Dr<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'DFS-311' type: 'pilot' count: 1 } { name: 'Trade Federation Drone' type: 'pilot' count: 1 } { name: 'Grappling Struts' type: 'upgrade' count: 1 } { name: 'Energy-Shell Charges' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'Guardians of the Republic Squadron Pack': [ { name: '<NAME>-7 Aethersprite' type: 'ship' count: 1 } { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: 'Blue Squadron Protector' type: 'pilot' count: 2 } { name: 'Gold Squadron Trooper' type: 'pilot' count: 2 } { name: 'R4 Astromech' type: 'upgrade' count: 1 } { name: 'R4-P Astromech' type: 'upgrade' count: 1 } { name: 'R5 Astromech' type: 'upgrade' count: 1 } { name: 'R4-P17' type: 'upgrade' count: 1 } { name: 'Delta-7B' type: 'upgrade' count: 1 } { name: 'Calibrated Laser Targeting' type: 'upgrade' count: 1 } { name: 'Brilliant Evasion' type: 'upgrade' count: 1 } { name: 'Battle Meditation' type: 'upgrade' count: 1 } { name: 'Predictive Shot' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Concussion Missiles' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>pert Handling' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 2 } { name: '<NAME>uration Salvo' type: 'upgrade' count: 2 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: '<NAME>ick Shot' type: 'upgrade' count: 2 } { name: 'Afterburners' type: 'upgrade' count: 2 } { name: 'Electronic Baffle' type: 'upgrade' count: 1 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Spare Parts Canisters' type: 'upgrade' count: 1 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Synchronized Console' type: 'upgrade' count: 3 } ] 'ARC-170 Starfighter Expansion': [ { name: '<NAME>7<NAME>' type: 'ship' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>" (ARC-170)' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'R4-P44' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } ] 'Delta-7 Aethersprite Expansion': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Calibrated Laser Target<NAME>' type: 'upgrade' count: 1 } { name: 'R4-P Astromech' type: 'upgrade' count: 1 } { name: 'R3 <NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>uration <NAME>' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } ] 'Z-95-AF4 Headhunter Expansion Pack': [ { name: 'Z-95 Headhunter' type: 'ship' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: "<NAME>" type: 'pilot' count: 1 } { name: 'Black Sun Soldier' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: "<NAME> Switch" type: 'upgrade' count: 1 } { name: 'Munitions Failsafe' type: 'upgrade' count: 1 } ] 'TIE/sk Striker Expansion Pack': [ { name: 'TIE Striker' type: 'ship' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: 'Black Squadron Scout' type: 'pilot' count: 1 } { name: 'Planetary Sentinel' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'Naboo Royal N-1 Starfighter Expansion Pack': [ { name: 'Naboo Royal N-1 Starfighter' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME> (N-1 Starfighter)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Collision Detector' type: 'upgrade' count: 1 } { name: '<NAME>ive Sensors' type: 'upgrade' count: 1 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'R2-A6' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 1 } { name: 'R2-C4' type: 'upgrade' count: 1 } { name: 'R4 Astromech' type: 'upgrade' count: 1 } ] 'Hyena-Class Droid Bomber Expansion Pack': [ { name: 'Hyena-Class Droid Bomber' type: 'ship' count: 1 } { name: 'DBS-404' type: 'pilot' count: 1 } { name: 'DBS-32C' type: 'pilot' count: 1 } { name: 'Bombardment Drone' type: 'pilot' count: 1 } { name: 'Baktoid Prototype' type: 'pilot' count: 1 } { name: 'Techno Union Bomber' type: 'pilot' count: 1 } { name: 'Separatist Bomber' type: 'pilot' count: 1 } { name: 'Passive Sensors' type: 'upgrade' count: 1 } { name: 'Trajectory Simulator' type: 'upgrade' count: 1 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'Barrage Rockets' type: 'upgrade' count: 1 } { name: 'Diamond-Boron Missiles' type: 'upgrade' count: 1 } { name: 'TA-175' type: 'upgrade' count: 1 } { name: 'Bomblet Generator' type: 'upgrade' count: 1 } { name: 'Electro-Proton Bomb' type: 'upgrade' count: 1 } { name: 'Delayed Fuses' type: 'upgrade' count: 1 } { name: 'Landing Struts' type: 'upgrade' count: 1 } ] 'A/SF-01 B-Wing Expansion Pack': [ { name: 'B-<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Blade <NAME>ron <NAME>' type: 'pilot' count: 1 } { name: 'Blue Squadron Pilot' type: 'pilot' count: 1 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: '<NAME> Laser Cannon' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>burn<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>ic B<NAME>le' type: 'upgrade' count: 1 } { name: 'Fire-Control System' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'Millennium Falcon Expansion Pack': [ { name: '<NAME>-13<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> Tact<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'VT-49 Decimator Expansion Pack': [ { name: 'VT-49 Decimator' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> "<NAME>" <NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'BT-1' type: 'upgrade' count: 1 } { name: '0-0-0' type: 'upgrade' count: 1 } ] 'TIE/VN Silencer Expansion Pack': [ { name: 'TIE/VN Silencer' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME> Order Test Pi<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Collision <NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'TIE/SF Fighter Expansion Pack': [ { name: '<NAME>/<NAME>' type: 'ship' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME> Squadron Ex<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> Detector' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Pattern Analyzer' type: 'upgrade' count: 1 } ] 'Resistance Transport Expansion Pack': [ { name: 'Resistance Transport' type: 'ship' count: 1 } { name: 'Resistance Transport Pod' type: 'ship' count: 1 } { name: 'BB-8' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: 'Logistics Division Pilot' type: 'pilot' count: 1 } { name: 'Composure' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } { name: 'Passive Sensors' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> (Resistance)' type: 'upgrade' count: 1 } { name: 'GA-97' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: "<NAME>" type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>-<NAME>' type: 'upgrade' count: 1 } { name: 'Afterburners' type: 'upgrade' count: 1 } { name: 'Angled Deflectors' type: 'upgrade' count: 1 } { name: 'Spare Parts Canisters' type: 'upgrade' count: 1 } ] 'BTL-B Y-Wing Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME> (Y-Wing)' type: 'pilot' count: 1 } { name: '"<NAME>" (Y-Wing)' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>ron <NAME>' type: 'pilot' count: 1 } { name: 'Precognitive Reflexes' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME> T<NAME>' type: 'upgrade' count: 1 } { name: 'C-3PO (Republic)' type: 'upgrade' count: 1 } { name: 'C1-10P' type: 'upgrade' count: 1 } { name: 'Delayed Fuses' type: 'upgrade' count: 1 } { name: 'Electro-Proton Bomb' type: 'upgrade' count: 1 } { name: 'Proton Bombs' type: 'upgrade' count: 1 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 1 } ] 'Nantex-class Starfighter Expansion Pack': [ { name: 'Nantex-Class Starfighter' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>avitic Deflection' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'upgrade' count: 1 } { name: 'Targeting Computer' type: 'upgrade' count: 1 } ] 'Punishing One Expansion Pack': [ { name: '<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: 'R5-P8' type: 'upgrade' count: 1 } { name: '0-0-0' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'M3-A Interceptor Expansion Pack': [ { name: '<NAME>-<NAME>' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: "<NAME> <NAME>" type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'Ghost Expansion Pack': [ { name: 'VCX-100' type: 'ship' count: 1 } { name: 'Sheathipede-Class Shuttle' type: 'ship' count: 1 } { name: 'AP-5' type: 'pilot' count: 1 } { name: '<NAME> (Sheathipe<NAME>)' type: 'pilot' count: 1 } { name: "<NAME> (Sheathipede)" type: 'pilot' count: 1 } { name: '"<NAME> (Sheathipede)' type: 'pilot' count: 1 } { name: '<NAME> (VCX-100)' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>"' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '"<NAME>" (Astromech)' type: 'upgrade' count: 1 } { name: '"<NAME>" (Cre<NAME>)' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '"<NAME>" <NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] "Inquisitors' TIE Expansion Pack": [ { name: 'TIE Advanced Prototype' type: 'ship' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'pilot' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } { name: '<NAME>' type: 'upgrade' count: 1 } ] 'Loose Ships': [ { name: '<NAME>' type: 'ship' count: 3 } { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>-2<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>-130<NAME>' type: 'ship' count: 2 } { name: '<NAME>tle' type: 'ship' count: 2 } { name: 'YT-2400' type: 'ship' count: 2 } { name: '<NAME>-<NAME> Star <NAME>' type: 'ship' count: 3 } { name: '<NAME>-Class <NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'ship' count: 3 } { name: '<NAME>' type: 'ship' count: 3 } { name: '<NAME>E Defender' type: 'ship' count: 2 } { name: '<NAME>' type: 'ship' count: 3 } { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'ship' count: 3 } { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>K-29<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'ship' count: 2 } { name: '<NAME>' type: 'ship' count: 3 } { name: '<NAME>' type: 'ship' count: 2 } { name: 'Lancer-Class Pursuit Craft' type: 'ship' count: 2 } { name: '<NAME>' type: 'ship' count: 2 } { name: 'MG-100 <NAME>' type: 'ship' count: 3 } { name: '<NAME>/<NAME>' type: 'ship' count: 3 } { name: '<NAME>/<NAME>' type: 'ship' count: 3 } { name: 'Upsilon-Class Command Shuttle' type: 'ship' count: 3 } { name: '<NAME>T-1300' type: 'ship' count: 3 } ] class exportObj.Collection constructor: (args) -> @expansions = args.expansions ? {} @singletons = args.singletons ? {} @checks = args.checks ? {} # To save collection (optional) @backend = args.backend @setupUI() @setupHandlers() @reset() @language = 'English' reset: -> @shelf = {} @table = {} for expansion, count of @expansions try count = parseInt count catch count = 0 for _ in [0...count] for card in (exportObj.manifestByExpansion[expansion] ? []) for _ in [0...card.count] ((@shelf[card.type] ?= {})[card.name] ?= []).push expansion for type, counts of @singletons for name, count of counts if count > 0 for _ in [0...count] ((@shelf[type] ?= {})[name] ?= []).push 'singleton' else if count < 0 for _ in [0...count] if ((@shelf[type] ?= {})[name] ?= []).length > 0 @shelf[type][name].pop() @counts = {} for own type of @shelf for own thing of @shelf[type] (@counts[type] ?= {})[thing] ?= 0 @counts[type][thing] += @shelf[type][thing].length # Create list of released singletons singletonsByType = {} for expname, items of exportObj.manifestByExpansion for item in items (singletonsByType[item.type] ?= {})[item.name] = true for type, names of singletonsByType sorted_names = (name for name of names).sort((a,b) -> sortWithoutQuotes(a,b,type)) singletonsByType[type] = sorted_names component_content = $ @modal.find('.collection-inventory-content') component_content.text '' card_totals_by_type = {} card_different_by_type = {} for own type, things of @counts if singletonsByType[type]? card_totals_by_type[type] = 0 card_different_by_type[type] = 0 contents = component_content.append $.trim """ <div class="row-fluid"> <div class="span12"><h5>#{type.capitalize()}</h5></div> </div> <div class="row-fluid"> <ul id="counts-#{type}" class="span12"></ul> </div> """ ul = $ contents.find("ul#counts-#{type}") for thing in Object.keys(things).sort((a,b) -> sortWithoutQuotes(a,b,type)) card_totals_by_type[type] += things[thing] if thing in singletonsByType[type] card_different_by_type[type]++ if type == 'pilot' ul.append """<li>#{if exportObj.pilots[thing].display_name then exportObj.pilots[thing].display_name else thing} - #{things[thing]}</li>""" if type == 'upgrade' ul.append """<li>#{if exportObj.upgrades[thing].display_name then exportObj.upgrades[thing].display_name else thing} - #{things[thing]}</li>""" if type == 'ship' ul.append """<li>#{if exportObj.ships[thing].display_name then exportObj.ships[thing].display_name else thing} - #{things[thing]}</li>""" summary = "" for type in Object.keys(card_totals_by_type) summary += """<li>#{type.capitalize()} - #{card_totals_by_type[type]} (#{card_different_by_type[type]} different)</li>""" component_content.append $.trim """ <div class="row-fluid"> <div class="span12"><h5>Summary</h5></div> </div> <div class = "row-fluid"> <ul id="counts-summary" class="span12"> #{summary} </ul> </div> """ check: (where, type, name) -> (((where[type] ? {})[name] ? []).length ? 0) != 0 checkShelf: (type, name) -> @check @shelf, type, name checkTable: (type, name) -> @check @table, type, name use: (type, name) -> try card = @shelf[type][name].pop() catch e return false unless card? if card? ((@table[type] ?= {})[name] ?= []).push card true else false release: (type, name) -> try card = @table[type][name].pop() catch e return false unless card? if card? ((@shelf[type] ?= {})[name] ?= []).push card true else false save: (cb=$.noop) -> @backend.saveCollection(this, cb) if @backend? @load: (backend, cb) -> backend.loadCollection cb setupUI: -> # Create list of released singletons singletonsByType = {} for expname, items of exportObj.manifestByExpansion for item in items (singletonsByType[item.type] ?= {})[item.name] = true for type, names of singletonsByType sorted_names = (name for name of names).sort((a,b) -> sortWithoutQuotes(a,b,type)) singletonsByType[type] = sorted_names @modal = $ document.createElement 'DIV' @modal.addClass 'modal hide fade collection-modal hidden-print' $('body').append @modal @modal.append $.trim """ <div class="modal-header"> <button type="button" class="close hidden-print" data-dismiss="modal" aria-hidden="true">&times;</button> <h4>Your Collection</h4> </div> <div class="modal-body"> <ul class="nav nav-tabs"> <li class="active"><a data-target="#collection-expansions" data-toggle="tab">Expansions</a><li> <li><a data-target="#collection-ships" data-toggle="tab">Ships</a><li> <li><a data-target="#collection-pilots" data-toggle="tab">Pilots</a><li> <li><a data-target="#collection-upgrades" data-toggle="tab">Upgrades</a><li> <li><a data-target="#collection-components" data-toggle="tab">Inventory</a><li> </ul> <div class="tab-content"> <div id="collection-expansions" class="tab-pane active container-fluid collection-content"></div> <div id="collection-ships" class="tab-pane active container-fluid collection-ship-content"></div> <div id="collection-pilots" class="tab-pane active container-fluid collection-pilot-content"></div> <div id="collection-upgrades" class="tab-pane active container-fluid collection-upgrade-content"></div> <div id="collection-components" class="tab-pane container-fluid collection-inventory-content"></div> </div> </div> <div class="modal-footer hidden-print"> <span class="collection-status"></span> &nbsp; <label class="checkbox-check-collection"> Check Collection Requirements <input type="checkbox" class="check-collection"/> </label> &nbsp; <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> """ @modal_status = $ @modal.find('.collection-status') if @checks.collectioncheck? if @checks.collectioncheck != "false" @modal.find('.check-collection').prop('checked', true) else @checks.collectioncheck = true @modal.find('.check-collection').prop('checked', true) @modal.find('.checkbox-check-collection').show() collection_content = $ @modal.find('.collection-content') for expansion in exportObj.expansions count = parseInt(@expansions[expansion] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="expansion-count" type="number" size="3" value="#{count}" /> <span class="expansion-name">#{expansion}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'expansion', expansion input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.expansion-name').data 'name', expansion if expansion != 'Loose Ships' or 'Hyperspace' collection_content.append row shipcollection_content = $ @modal.find('.collection-ship-content') for ship in singletonsByType.ship count = parseInt(@singletons.ship?[ship] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="ship-name">#{if exportObj.ships[ship].display_name then exportObj.ships[ship].display_name else ship}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'ship' input.data 'singletonName', ship input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.ship-name').data 'name', ship shipcollection_content.append row pilotcollection_content = $ @modal.find('.collection-pilot-content') for pilot in singletonsByType.pilot count = parseInt(@singletons.pilot?[pilot] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="pilot-name">#{if exportObj.pilots[pilot].display_name then exportObj.pilots[pilot].display_name else pilot}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'pilot' input.data 'singletonName', pilot input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.pilot-name').data 'name', pilot pilotcollection_content.append row upgradecollection_content = $ @modal.find('.collection-upgrade-content') for upgrade in singletonsByType.upgrade count = parseInt(@singletons.upgrade?[upgrade] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="upgrade-name">#{if exportObj.upgrades[upgrade].display_name then exportObj.upgrades[upgrade].display_name else upgrade}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'upgrade' input.data 'singletonName', upgrade input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.upgrade-name').data 'name', upgrade upgradecollection_content.append row destroyUI: -> @modal.modal 'hide' @modal.remove() $(exportObj).trigger 'xwing-collection:destroyed', this setupHandlers: -> $(exportObj).trigger 'xwing-collection:created', this $(exportObj).on 'xwing-backend:authenticationChanged', (e, authenticated, backend) => # console.log "deauthed, destroying collection UI" @destroyUI() unless authenticated .on 'xwing-collection:saved', (e, collection) => @modal_status.text 'Collection saved' @modal_status.fadeIn 100, => @modal_status.fadeOut 1000 .on 'xwing:languageChanged', @onLanguageChange .on 'xwing:CollectionCheck', @onCollectionCheckSet $ @modal.find('input.expansion-count').change (e) => target = $(e.target) val = target.val() target.val(0) if val < 0 or isNaN(parseInt(val)) @expansions[target.data 'expansion'] = parseInt(target.val()) target.closest('div').css 'background-color', @countToBackgroundColor(target.val()) # console.log "Input changed, triggering collection change" $(exportObj).trigger 'xwing-collection:changed', this $ @modal.find('input.singleton-count').change (e) => target = $(e.target) val = target.val() target.val(0) if isNaN(parseInt(val)) (@singletons[target.data 'singletonType'] ?= {})[target.data 'singletonName'] = parseInt(target.val()) target.closest('div').css 'background-color', @countToBackgroundColor(target.val()) # console.log "Input changed, triggering collection change" $(exportObj).trigger 'xwing-collection:changed', this $ @modal.find('.check-collection').change (e) => if @modal.find('.check-collection').prop('checked') == false result = false @modal_status.text """Collection Tracking Disabled""" else result = true @modal_status.text """Collection Tracking Active""" @checks.collectioncheck = result @modal_status.fadeIn 100, => @modal_status.fadeOut 1000 $(exportObj).trigger 'xwing-collection:changed', this countToBackgroundColor: (count) -> count = parseInt(count) switch when count < 0 'red' when count == 0 '' when count > 0 i = parseInt(200 * Math.pow(0.9, count - 1)) "rgb(#{i}, 255, #{i})" else '' onLanguageChange: (e, language) => @language = language if language != @old_language @old_language = language # console.log "language changed to #{language}" do (language) => @modal.find('.expansion-name').each -> # console.log "translating #{$(this).text()} (#{$(this).data('name')}) to #{language}" $(this).text exportObj.translate language, 'sources', $(this).data('name') @modal.find('.ship-name').each -> $(this).text (if exportObj.ships[$(this).data('name')].display_name then exportObj.ships[$(this).data('name')].display_name else $(this).data('name')) @modal.find('.pilot-name').each -> $(this).text (if exportObj.pilots[$(this).data('name')].display_name then exportObj.pilots[$(this).data('name')].display_name else $(this).data('name')) @modal.find('.upgrade-name').each -> $(this).text (if exportObj.upgrades[$(this).data('name')].display_name then exportObj.upgrades[$(this).data('name')].display_name else $(this).data('name'))
true
exportObj = exports ? this String::startsWith ?= (t) -> @indexOf t == 0 sortWithoutQuotes = (a, b, type = '') -> a_name = displayName(a,type).replace /[^a-z0-9]/ig, '' b_name = displayName(b,type).replace /[^a-z0-9]/ig, '' if a_name < b_name -1 else if a_name > b_name 1 else 0 displayName = (name, type) -> obj = undefined if type == 'ship' obj = exportObj.ships[name] else if type == 'upgrade' obj = exportObj.upgrades[name] else if type == 'pilot' obj = exportObj.pilots[name] else return name if obj and obj.display_name return obj.display_name return name exportObj.manifestBySettings = 'collectioncheck': true exportObj.manifestByExpansion = 'Second Edition Core Set': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Black Squadron Ace' type: 'pilot' count: 2 } { name: '"Night Beast"' type: 'pilot' count: 1 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 2 } { name: 'Academy Pilot' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI RePI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI2' type: 'upgrade' count: 1 } { name: 'R3 PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'R5-D8' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] "Saw's Renegades Expansion Pack" : [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'TIE Reaper Expansion Pack' : [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PIoph' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI Base PiPI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'ISB Slicer' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIactical OfficPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } ] 'Rebel Alliance Conversion Kit': [ { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Y-PI:NAME:<NAME>END_PI)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (X-Wing)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI Squadron EPI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'Red Squadron Veteran' type: 'pilot' count: 2 } { name: '"PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Gold Squadron Veteran' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Green Squadron Pilot' type: 'pilot' count: 2 } { name: 'Phoenix Squadron Pilot' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Blue Squadron Pilot' type: 'pilot' count: 2 } { name: 'Blade PI:NAME:<NAME>END_PIron PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI Squadron PiPI:NAME:<NAME>END_PI' type: 'pilot' count: 3 } { name: 'Tala Squadron Pilot' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'AP-PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (SheathipePI:NAME:<NAME>END_PI)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (SheathipePI:NAME:<NAME>END_PI)' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI (Sheathipede)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (TIE Fighter)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (TIE Fighter)' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI (TIE Fighter)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Blue Squadron Scout' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Warden Squadron Pilot' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (VCX-100)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI TactPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'Cloaking Device' type: 'upgrade' count: 1 } { name: 'Contraband Cybernetics' type: 'upgrade' count: 2 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 2 } { name: 'Feedback Array' type: 'upgrade' count: 2 } { name: 'Inertial Dampeners' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIigged Cargo Chute' type: 'upgrade' count: 2 } { name: 'Heavy Laser Cannon' type: 'upgrade' count: 2 } { name: 'Ion Cannon' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIming BePI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Tractor Beam' type: 'upgrade' count: 2 } { name: 'Dorsal Turret' type: 'upgrade' count: 2 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: '"PI:NAME:<NAME>END_PI" (Crew)' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Novice Technician' type: 'upgrade' count: 2 } { name: 'Perceptive Copilot' type: 'upgrade' count: 2 } { name: 'R2-D2 (Crew)' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Seasoned Navigator' type: 'upgrade' count: 1 } { name: 'Tactical Officer' type: 'upgrade' count: 1 } { name: '"PI:NAME:<NAME>END_PI" OrPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Concussion Missiles' type: 'upgrade' count: 2 } { name: 'Homing Missiles' type: 'upgrade' count: 2 } { name: 'Ion Missiles' type: 'upgrade' count: 2 } { name: 'Proton Rockets' type: 'upgrade' count: 2 } { name: 'Bomblet Generator' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIner Nets' type: 'upgrade' count: 2 } { name: 'Proton Bombs' type: 'upgrade' count: 2 } { name: 'Proximity Mines' type: 'upgrade' count: 2 } { name: 'Seismic PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: '"PI:NAME:<NAME>END_PI" (Astromech)' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 2 } { name: 'R3 Astromech' type: 'upgrade' count: 2 } { name: 'R4 Astromech' type: 'upgrade' count: 2 } { name: 'R5 Astromech' type: 'upgrade' count: 2 } { name: 'Ablative Plating' type: 'upgrade' count: 2 } { name: 'Advanced SLAM' type: 'upgrade' count: 2 } { name: 'Electronic Baffle' type: 'upgrade' count: 2 } { name: 'Engine Upgrade' type: 'upgrade' count: 2 } { name: 'Hull Upgrade' type: 'upgrade' count: 2 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIactical Scrambler' type: 'upgrade' count: 2 } ] 'Galactic Empire Conversion Kit': [ { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'Black Squadron Ace' type: 'pilot' count: 4 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 4 } { name: 'PI:NAME:<NAME>END_PIcademy Pilot' type: 'pilot' count: 4 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Storm Squadron Ace' type: 'pilot' count: 2 } { name: 'Tempest Squadron Pilot' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PIitor' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Alpha Squadron Pilot' type: 'pilot' count: 2 } { name: 'Saber Squadron Ace' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'Gamma Squadron Ace' type: 'pilot' count: 3 } { name: 'Scimitar Squadron Pilot' type: 'pilot' count: 3 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'Black Squadron Scout' type: 'pilot' count: 3 } { name: 'Planetary Sentinel' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Onyx Squadron Ace' type: 'pilot' count: 2 } { name: 'Delta Squadron Pilot' type: 'pilot' count: 2 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Onyx Squadron Scout' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: "Sigma Squadron Ace" type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Rho Squadron Pilot' type: 'pilot' count: 2 } { name: 'Nu Squadron Pilot' type: 'pilot' count: 2 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'Cutlass Squadron Pilot' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PIron Group Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI Shot' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI Sensors' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'Trajectory Simulator' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIavy Laser Cannon' type: 'upgrade' count: 2 } { name: 'Ion Cannon' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIamming Beam' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIactor Beam' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIorsal Turret' type: 'upgrade' count: 2 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 2 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 3 } { name: 'Ion Torpedoes' type: 'upgrade' count: 3 } { name: 'Proton Torpedoes' type: 'upgrade' count: 3 } { name: 'Barrage Rockets' type: 'upgrade' count: 3 } { name: 'Cluster Missiles' type: 'upgrade' count: 3 } { name: 'Concussion Missiles' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PInician' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIlet PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PIimity MPI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'Seismic CharPI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'Dauntless' type: 'upgrade' count: 1 } { name: 'ST-321' type: 'upgrade' count: 1 } { name: 'Os-1 Arsenal Loadout' type: 'upgrade' count: 3 } { name: 'Xg-1 Assault Configuration' type: 'upgrade' count: 3 } { name: 'Ablative Plating' type: 'upgrade' count: 2 } { name: 'Advanced SLAM' type: 'upgrade' count: 2 } { name: 'Electronic Baffle' type: 'upgrade' count: 2 } { name: 'Hull Upgrade' type: 'upgrade' count: 2 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } ] 'Scum and Villainy Conversion Kit': [ { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI (StarViper)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 4 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 4 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI-8PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI-8PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Expert Handling' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Advanced Sensors' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'Trajectory Simulator' type: 'upgrade' count: 2 } { name: 'Cloaking Device' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PInetPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 3 } { name: 'Feedback PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI Laser CPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI Cannon' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIamming Beam' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIactor BePI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Dorsal Turret' type: 'upgrade' count: 2 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 2 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 2 } { name: 'Ion Torpedoes' type: 'upgrade' count: 2 } { name: 'Proton Torpedoes' type: 'upgrade' count: 2 } { name: '0-0-0' type: 'upgrade' count: 1 } { name: '4-LOM' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 2 } { name: 'IG-88D' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Novice Technician' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIceptive Copilot' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIed Navigator' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIactical OfficPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI Missiles' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIcussion MissPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIissPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI RocketPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIomblet Generator' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIner NPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIton BPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIimity Mines' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: 'IG-2000' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Engine Upgrade' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIull PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Tactical Scrambler' type: 'upgrade' count: 2 } { name: '"PI:NAME:<NAME>END_PI"' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 2 } { name: 'R3 Astromech' type: 'upgrade' count: 2 } { name: 'R4 Astromech' type: 'upgrade' count: 2 } { name: 'R5 Astromech' type: 'upgrade' count: 2 } { name: 'R5-P8' type: 'upgrade' count: 1 } { name: 'R5-TK' type: 'upgrade' count: 1 } ] 'T-65 X-Wing Expansion Pack' : [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (X-PI:NAME:<NAME>END_PIing)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'RPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'R4 AstPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'BTL-A4 Y-Wing Expansion Pack' : [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Y-Wing)' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'ExPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'TIE/ln Fighter Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Obsidian Squadron Pilot' type: 'pilot' count: 1 } { name: 'Academy Pilot' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'upgrade' count: 1 } ] 'TIE Advanced x1 Expansion Pack': [ { name: 'TIE Advanced' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Storm Squadron Ace' type: 'pilot' count: 1 } { name: 'Tempest Squadron Pilot' type: 'pilot' count: 1 } { name: 'Heightened Perception' type: 'upgrade' count: 1 } { name: 'Supernatural Reflexes' type: 'upgrade' count: 1 } { name: 'Ruthless' type: 'upgrade' count: 1 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Fire-Control System' type: 'upgrade' count: 1 } ] 'Slave I Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'Fang Fighter Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] "Lando's Millennium Falcon Expansion Pack": [ { name: 'Customized YT-1300' type: 'ship' count: 1 } { name: 'Escape PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Scum)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Scum)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI-3PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Scum) (Escape Craft)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'L3-37 (Escape Craft)' type: 'pilot' count: 1 } { name: 'Autopilot Drone' type: 'pilot' count: 1 } { name: 'L3-PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Scum)' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Scum)' type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI Navigator' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Scum)' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'Resistance Conversion Kit': [ { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Resistance)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Resistance)' type: 'pilot' count: 1 } { name: 'Resistance Sympathizer' type: 'pilot' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Black Squadron Ace (T-70)' type: 'pilot' count: 1 } { name: 'Red Squadron Expert' type: 'pilot' count: 4 } { name: 'Blue Squadron Rookie' type: 'pilot' count: 4 } { name: 'R2-HA' type: 'upgrade' count: 1 } { name: 'BB-8' type: 'upgrade' count: 1 } { name: 'R5-X3' type: 'upgrade' count: 1 } { name: 'BB Astromech' type: 'upgrade' count: 4 } { name: 'R2 Astromech' type: 'upgrade' count: 2 } { name: 'R3 Astromech' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Resistance)' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Resistance)' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Resistance)' type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 4 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIarm Tactics' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Advanced Optics' type: 'upgrade' count: 2 } { name: 'Pattern Analyzer' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIing SynchronPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Advanced Sensors' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'Trajectory Simulator' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIavy Laser Cannon' type: 'upgrade' count: 2 } { name: 'Ion Cannon' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIamming Beam' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIactor Beam' type: 'upgrade' count: 2 } { name: 'Adv. Proton Torpedoes' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIton Torpedoes' type: 'upgrade' count: 2 } { name: 'Ion Torpedoes' type: 'upgrade' count: 2 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Concussion Missiles' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Proximity Mines' type: 'upgrade' count: 2 } { name: 'Seismic Charges' type: 'upgrade' count: 2 } { name: 'Ablative Plating' type: 'upgrade' count: 2 } { name: 'Advanced SLAM' type: 'upgrade' count: 1 } { name: 'Electronic Baffle' type: 'upgrade' count: 2 } { name: 'Engine Upgrade' type: 'upgrade' count: 2 } { name: 'Hull Upgrade' type: 'upgrade' count: 2 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Tactical Scrambler' type: 'upgrade' count: 2 } ] 'T-70 X-Wing Expansion Pack': [ { name: 'T-70 X-Wing' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Black Squadron Ace (T-70)' type: 'pilot' count: 1 } { name: 'Red Squadron Expert' type: 'pilot' count: 1 } { name: 'Blue PI:NAME:<NAME>END_PI RPI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Black One' type: 'upgrade' count: 1 } { name: 'BB-8' type: 'upgrade' count: 1 } { name: 'BB Astromech' type: 'upgrade' count: 1 } { name: 'Integrated S-Foils' type: 'upgrade' count: 1 } { name: 'M9-G8' type: 'upgrade' count: 1 } { name: 'Targeting Synchronizer' type: 'upgrade' count: 1 } ] 'RZ-2 A-Wing Expansion Pack': [ { name: 'RZ-2 A-Wing' type: 'ship' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Green Squadron Expert' type: 'pilot' count: 1 } { name: 'Blue Squadron Recruit' type: 'pilot' count: 1 } { name: 'Heroic' type: 'upgrade' count: 1 } { name: 'Ferrosphere Paint' type: 'upgrade' count: 1 } { name: 'Homing Missiles' type: 'upgrade' count: 1 } { name: 'Primed Thrusters' type: 'upgrade' count: 1 } { name: 'Proton Rockets' type: 'upgrade' count: 1 } ] 'Mining Guild TIE Expansion Pack': [ { name: 'Mining Guild TIE Fighter' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Mining Guild Surveyor' type: 'pilot' count: 1 } { name: 'Mining Guild Sentry' type: 'pilot' count: 1 } { name: 'Hull Upgrade' type: 'upgrade' count: 1 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 1 } { name: 'Elusive' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } { name: 'Trick Shot' type: 'upgrade' count: 1 } ] 'First Order Conversion Kit': [ { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'TN-3465' type: 'pilot' count: 1 } { name: 'Epsilon Squadron Cadet' type: 'pilot' count: 7 } { name: 'Zeta Squadron Pilot' type: 'pilot' count: 7 } { name: 'Omega Squadron Ace' type: 'pilot' count: 6 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: "Omega Squadron Expert" type: 'pilot' count: 4 } { name: "PI:NAME:<NAME>END_PI SurvivPI:NAME:<NAME>END_PI" type: 'pilot' count: 5 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI Order Test Pilot" type: 'pilot' count: 3 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 3 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PIiller Base Pilot" type: 'pilot' count: 3 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PIspace Tracking Data" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 4 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PIacPI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PIidation' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Advanced Optics' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIing Synchronizer' type: 'upgrade' count: 2 } { name: 'Hyperspace Tracking Data' type: 'upgrade' count: 2 } { name: 'Advanced Sensors' type: 'upgrade' count: 2 } { name: 'Collision Detector' type: 'upgrade' count: 2 } { name: 'Fire-Control System' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI Laser Cannon' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI Cannon' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIming BePI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI BePI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIance PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'GNK "Gonk" Droid' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIed Navigator' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Engine Upgrade' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIull Upgrade' type: 'upgrade' count: 2 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Shield Upgrade' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 2 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Tactical Scrambler' type: 'upgrade' count: 2 } ] 'TIE/FO Fighter Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI/PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Zeta Squadron PiPI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Omega Squadron Ace' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI-3465' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } { name: 'Advanced Optics' type: 'upgrade' count: 1 } { name: 'Targeting Synchronizer' type: 'upgrade' count: 1 } ] 'Servants of Strife Squadron Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'Vulture-class Droid FightPI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI Federation DrPI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI-08PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI TPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'TPI:NAME:<NAME>END_PIerous' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIcussion MPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Homing Missiles' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Energy-Shell CharPI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Afterburners' type: 'upgrade' count: 3 } { name: 'PI:NAME:<NAME>END_PIic BPI:NAME:<NAME>END_PIle' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIervium Plating' type: 'upgrade' count: 1 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 3 } { name: 'Stealth Device' type: 'upgrade' count: 3 } ] 'Sith Infiltrator Expansion Pack': [ { name: 'Sith Infiltrator' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI Courier' type: 'pilot' count: 1 } { name: '0-66' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PIilliant EPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI. Proton PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI Laser Cannon' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'K2-B4' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIK-1 Probe Droids' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'Vulture-class Droid Fighter Expansion': [ { name: 'Vulture-class Droid Fighter' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PIatist DrPI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'DFS-311' type: 'pilot' count: 1 } { name: 'Trade Federation Drone' type: 'pilot' count: 1 } { name: 'Grappling Struts' type: 'upgrade' count: 1 } { name: 'Energy-Shell Charges' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'Guardians of the Republic Squadron Pack': [ { name: 'PI:NAME:<NAME>END_PI-7 Aethersprite' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'Blue Squadron Protector' type: 'pilot' count: 2 } { name: 'Gold Squadron Trooper' type: 'pilot' count: 2 } { name: 'R4 Astromech' type: 'upgrade' count: 1 } { name: 'R4-P Astromech' type: 'upgrade' count: 1 } { name: 'R5 Astromech' type: 'upgrade' count: 1 } { name: 'R4-P17' type: 'upgrade' count: 1 } { name: 'Delta-7B' type: 'upgrade' count: 1 } { name: 'Calibrated Laser Targeting' type: 'upgrade' count: 1 } { name: 'Brilliant Evasion' type: 'upgrade' count: 1 } { name: 'Battle Meditation' type: 'upgrade' count: 1 } { name: 'Predictive Shot' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 2 } { name: 'Concussion Missiles' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIpert Handling' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIuration Salvo' type: 'upgrade' count: 2 } { name: 'Swarm Tactics' type: 'upgrade' count: 2 } { name: 'PI:NAME:<NAME>END_PIick Shot' type: 'upgrade' count: 2 } { name: 'Afterburners' type: 'upgrade' count: 2 } { name: 'Electronic Baffle' type: 'upgrade' count: 1 } { name: 'Munitions Failsafe' type: 'upgrade' count: 2 } { name: 'Spare Parts Canisters' type: 'upgrade' count: 1 } { name: 'Static Discharge Vanes' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'upgrade' count: 2 } { name: 'Synchronized Console' type: 'upgrade' count: 3 } ] 'ARC-170 Starfighter Expansion': [ { name: 'PI:NAME:<NAME>END_PI7PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI" (ARC-170)' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'R4-P44' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } ] 'Delta-7 Aethersprite Expansion': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Calibrated Laser TargetPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'R4-P Astromech' type: 'upgrade' count: 1 } { name: 'R3 PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIuration PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Swarm Tactics' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } ] 'Z-95-AF4 Headhunter Expansion Pack': [ { name: 'Z-95 Headhunter' type: 'ship' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: 'Black Sun Soldier' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Concussion Missiles' type: 'upgrade' count: 1 } { name: 'Cluster Missiles' type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI Switch" type: 'upgrade' count: 1 } { name: 'Munitions Failsafe' type: 'upgrade' count: 1 } ] 'TIE/sk Striker Expansion Pack': [ { name: 'TIE Striker' type: 'ship' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'Black Squadron Scout' type: 'pilot' count: 1 } { name: 'Planetary Sentinel' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'Naboo Royal N-1 Starfighter Expansion Pack': [ { name: 'Naboo Royal N-1 Starfighter' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (N-1 Starfighter)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Collision Detector' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIive Sensors' type: 'upgrade' count: 1 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'R2-A6' type: 'upgrade' count: 1 } { name: 'R2 Astromech' type: 'upgrade' count: 1 } { name: 'R2-C4' type: 'upgrade' count: 1 } { name: 'R4 Astromech' type: 'upgrade' count: 1 } ] 'Hyena-Class Droid Bomber Expansion Pack': [ { name: 'Hyena-Class Droid Bomber' type: 'ship' count: 1 } { name: 'DBS-404' type: 'pilot' count: 1 } { name: 'DBS-32C' type: 'pilot' count: 1 } { name: 'Bombardment Drone' type: 'pilot' count: 1 } { name: 'Baktoid Prototype' type: 'pilot' count: 1 } { name: 'Techno Union Bomber' type: 'pilot' count: 1 } { name: 'Separatist Bomber' type: 'pilot' count: 1 } { name: 'Passive Sensors' type: 'upgrade' count: 1 } { name: 'Trajectory Simulator' type: 'upgrade' count: 1 } { name: 'Plasma Torpedoes' type: 'upgrade' count: 1 } { name: 'Barrage Rockets' type: 'upgrade' count: 1 } { name: 'Diamond-Boron Missiles' type: 'upgrade' count: 1 } { name: 'TA-175' type: 'upgrade' count: 1 } { name: 'Bomblet Generator' type: 'upgrade' count: 1 } { name: 'Electro-Proton Bomb' type: 'upgrade' count: 1 } { name: 'Delayed Fuses' type: 'upgrade' count: 1 } { name: 'Landing Struts' type: 'upgrade' count: 1 } ] 'A/SF-01 B-Wing Expansion Pack': [ { name: 'B-PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Blade PI:NAME:<NAME>END_PIron PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Blue Squadron Pilot' type: 'pilot' count: 1 } { name: 'Squad Leader' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI Laser Cannon' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIburnPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIic BPI:NAME:<NAME>END_PIle' type: 'upgrade' count: 1 } { name: 'Fire-Control System' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'Millennium Falcon Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI-13PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI TactPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'VT-49 Decimator Expansion Pack': [ { name: 'VT-49 Decimator' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'BT-1' type: 'upgrade' count: 1 } { name: '0-0-0' type: 'upgrade' count: 1 } ] 'TIE/VN Silencer Expansion Pack': [ { name: 'TIE/VN Silencer' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI Order Test PiPI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Collision PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'TIE/SF Fighter Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI/PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI Squadron ExPI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI Detector' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Pattern Analyzer' type: 'upgrade' count: 1 } ] 'Resistance Transport Expansion Pack': [ { name: 'Resistance Transport' type: 'ship' count: 1 } { name: 'Resistance Transport Pod' type: 'ship' count: 1 } { name: 'BB-8' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Logistics Division Pilot' type: 'pilot' count: 1 } { name: 'Composure' type: 'upgrade' count: 1 } { name: 'Expert Handling' type: 'upgrade' count: 1 } { name: 'Passive Sensors' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Resistance)' type: 'upgrade' count: 1 } { name: 'GA-97' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: "PI:NAME:<NAME>END_PI" type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Afterburners' type: 'upgrade' count: 1 } { name: 'Angled Deflectors' type: 'upgrade' count: 1 } { name: 'Spare Parts Canisters' type: 'upgrade' count: 1 } ] 'BTL-B Y-Wing Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI (Y-Wing)' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI" (Y-Wing)' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PIron PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'Precognitive Reflexes' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI TPI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'C-3PO (Republic)' type: 'upgrade' count: 1 } { name: 'C1-10P' type: 'upgrade' count: 1 } { name: 'Delayed Fuses' type: 'upgrade' count: 1 } { name: 'Electro-Proton Bomb' type: 'upgrade' count: 1 } { name: 'Proton Bombs' type: 'upgrade' count: 1 } { name: 'Ion Cannon Turret' type: 'upgrade' count: 1 } ] 'Nantex-class Starfighter Expansion Pack': [ { name: 'Nantex-Class Starfighter' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PIavitic Deflection' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'Stealth Device' type: 'upgrade' count: 1 } { name: 'Targeting Computer' type: 'upgrade' count: 1 } ] 'Punishing One Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'R5-P8' type: 'upgrade' count: 1 } { name: '0-0-0' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'M3-A Interceptor Expansion Pack': [ { name: 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'Ghost Expansion Pack': [ { name: 'VCX-100' type: 'ship' count: 1 } { name: 'Sheathipede-Class Shuttle' type: 'ship' count: 1 } { name: 'AP-5' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (SheathipePI:NAME:<NAME>END_PI)' type: 'pilot' count: 1 } { name: "PI:NAME:<NAME>END_PI (Sheathipede)" type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI (Sheathipede)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI (VCX-100)' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI"' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: '"PI:NAME:<NAME>END_PI" (Astromech)' type: 'upgrade' count: 1 } { name: '"PI:NAME:<NAME>END_PI" (CrePI:NAME:<NAME>END_PI)' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] "Inquisitors' TIE Expansion Pack": [ { name: 'TIE Advanced Prototype' type: 'ship' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'pilot' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } { name: 'PI:NAME:<NAME>END_PI' type: 'upgrade' count: 1 } ] 'Loose Ships': [ { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI-2PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI-130PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PItle' type: 'ship' count: 2 } { name: 'YT-2400' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI Star PI:NAME:<NAME>END_PI' type: 'ship' count: 3 } { name: 'PI:NAME:<NAME>END_PI-Class PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 3 } { name: 'PI:NAME:<NAME>END_PIE Defender' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PIK-29PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 3 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'Lancer-Class Pursuit Craft' type: 'ship' count: 2 } { name: 'PI:NAME:<NAME>END_PI' type: 'ship' count: 2 } { name: 'MG-100 PI:NAME:<NAME>END_PI' type: 'ship' count: 3 } { name: 'PI:NAME:<NAME>END_PI/PI:NAME:<NAME>END_PI' type: 'ship' count: 3 } { name: 'PI:NAME:<NAME>END_PI/PI:NAME:<NAME>END_PI' type: 'ship' count: 3 } { name: 'Upsilon-Class Command Shuttle' type: 'ship' count: 3 } { name: 'PI:NAME:<NAME>END_PIT-1300' type: 'ship' count: 3 } ] class exportObj.Collection constructor: (args) -> @expansions = args.expansions ? {} @singletons = args.singletons ? {} @checks = args.checks ? {} # To save collection (optional) @backend = args.backend @setupUI() @setupHandlers() @reset() @language = 'English' reset: -> @shelf = {} @table = {} for expansion, count of @expansions try count = parseInt count catch count = 0 for _ in [0...count] for card in (exportObj.manifestByExpansion[expansion] ? []) for _ in [0...card.count] ((@shelf[card.type] ?= {})[card.name] ?= []).push expansion for type, counts of @singletons for name, count of counts if count > 0 for _ in [0...count] ((@shelf[type] ?= {})[name] ?= []).push 'singleton' else if count < 0 for _ in [0...count] if ((@shelf[type] ?= {})[name] ?= []).length > 0 @shelf[type][name].pop() @counts = {} for own type of @shelf for own thing of @shelf[type] (@counts[type] ?= {})[thing] ?= 0 @counts[type][thing] += @shelf[type][thing].length # Create list of released singletons singletonsByType = {} for expname, items of exportObj.manifestByExpansion for item in items (singletonsByType[item.type] ?= {})[item.name] = true for type, names of singletonsByType sorted_names = (name for name of names).sort((a,b) -> sortWithoutQuotes(a,b,type)) singletonsByType[type] = sorted_names component_content = $ @modal.find('.collection-inventory-content') component_content.text '' card_totals_by_type = {} card_different_by_type = {} for own type, things of @counts if singletonsByType[type]? card_totals_by_type[type] = 0 card_different_by_type[type] = 0 contents = component_content.append $.trim """ <div class="row-fluid"> <div class="span12"><h5>#{type.capitalize()}</h5></div> </div> <div class="row-fluid"> <ul id="counts-#{type}" class="span12"></ul> </div> """ ul = $ contents.find("ul#counts-#{type}") for thing in Object.keys(things).sort((a,b) -> sortWithoutQuotes(a,b,type)) card_totals_by_type[type] += things[thing] if thing in singletonsByType[type] card_different_by_type[type]++ if type == 'pilot' ul.append """<li>#{if exportObj.pilots[thing].display_name then exportObj.pilots[thing].display_name else thing} - #{things[thing]}</li>""" if type == 'upgrade' ul.append """<li>#{if exportObj.upgrades[thing].display_name then exportObj.upgrades[thing].display_name else thing} - #{things[thing]}</li>""" if type == 'ship' ul.append """<li>#{if exportObj.ships[thing].display_name then exportObj.ships[thing].display_name else thing} - #{things[thing]}</li>""" summary = "" for type in Object.keys(card_totals_by_type) summary += """<li>#{type.capitalize()} - #{card_totals_by_type[type]} (#{card_different_by_type[type]} different)</li>""" component_content.append $.trim """ <div class="row-fluid"> <div class="span12"><h5>Summary</h5></div> </div> <div class = "row-fluid"> <ul id="counts-summary" class="span12"> #{summary} </ul> </div> """ check: (where, type, name) -> (((where[type] ? {})[name] ? []).length ? 0) != 0 checkShelf: (type, name) -> @check @shelf, type, name checkTable: (type, name) -> @check @table, type, name use: (type, name) -> try card = @shelf[type][name].pop() catch e return false unless card? if card? ((@table[type] ?= {})[name] ?= []).push card true else false release: (type, name) -> try card = @table[type][name].pop() catch e return false unless card? if card? ((@shelf[type] ?= {})[name] ?= []).push card true else false save: (cb=$.noop) -> @backend.saveCollection(this, cb) if @backend? @load: (backend, cb) -> backend.loadCollection cb setupUI: -> # Create list of released singletons singletonsByType = {} for expname, items of exportObj.manifestByExpansion for item in items (singletonsByType[item.type] ?= {})[item.name] = true for type, names of singletonsByType sorted_names = (name for name of names).sort((a,b) -> sortWithoutQuotes(a,b,type)) singletonsByType[type] = sorted_names @modal = $ document.createElement 'DIV' @modal.addClass 'modal hide fade collection-modal hidden-print' $('body').append @modal @modal.append $.trim """ <div class="modal-header"> <button type="button" class="close hidden-print" data-dismiss="modal" aria-hidden="true">&times;</button> <h4>Your Collection</h4> </div> <div class="modal-body"> <ul class="nav nav-tabs"> <li class="active"><a data-target="#collection-expansions" data-toggle="tab">Expansions</a><li> <li><a data-target="#collection-ships" data-toggle="tab">Ships</a><li> <li><a data-target="#collection-pilots" data-toggle="tab">Pilots</a><li> <li><a data-target="#collection-upgrades" data-toggle="tab">Upgrades</a><li> <li><a data-target="#collection-components" data-toggle="tab">Inventory</a><li> </ul> <div class="tab-content"> <div id="collection-expansions" class="tab-pane active container-fluid collection-content"></div> <div id="collection-ships" class="tab-pane active container-fluid collection-ship-content"></div> <div id="collection-pilots" class="tab-pane active container-fluid collection-pilot-content"></div> <div id="collection-upgrades" class="tab-pane active container-fluid collection-upgrade-content"></div> <div id="collection-components" class="tab-pane container-fluid collection-inventory-content"></div> </div> </div> <div class="modal-footer hidden-print"> <span class="collection-status"></span> &nbsp; <label class="checkbox-check-collection"> Check Collection Requirements <input type="checkbox" class="check-collection"/> </label> &nbsp; <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div> """ @modal_status = $ @modal.find('.collection-status') if @checks.collectioncheck? if @checks.collectioncheck != "false" @modal.find('.check-collection').prop('checked', true) else @checks.collectioncheck = true @modal.find('.check-collection').prop('checked', true) @modal.find('.checkbox-check-collection').show() collection_content = $ @modal.find('.collection-content') for expansion in exportObj.expansions count = parseInt(@expansions[expansion] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="expansion-count" type="number" size="3" value="#{count}" /> <span class="expansion-name">#{expansion}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'expansion', expansion input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.expansion-name').data 'name', expansion if expansion != 'Loose Ships' or 'Hyperspace' collection_content.append row shipcollection_content = $ @modal.find('.collection-ship-content') for ship in singletonsByType.ship count = parseInt(@singletons.ship?[ship] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="ship-name">#{if exportObj.ships[ship].display_name then exportObj.ships[ship].display_name else ship}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'ship' input.data 'singletonName', ship input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.ship-name').data 'name', ship shipcollection_content.append row pilotcollection_content = $ @modal.find('.collection-pilot-content') for pilot in singletonsByType.pilot count = parseInt(@singletons.pilot?[pilot] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="pilot-name">#{if exportObj.pilots[pilot].display_name then exportObj.pilots[pilot].display_name else pilot}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'pilot' input.data 'singletonName', pilot input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.pilot-name').data 'name', pilot pilotcollection_content.append row upgradecollection_content = $ @modal.find('.collection-upgrade-content') for upgrade in singletonsByType.upgrade count = parseInt(@singletons.upgrade?[upgrade] ? 0) row = $.parseHTML $.trim """ <div class="row-fluid"> <div class="span12"> <label> <input class="singleton-count" type="number" size="3" value="#{count}" /> <span class="upgrade-name">#{if exportObj.upgrades[upgrade].display_name then exportObj.upgrades[upgrade].display_name else upgrade}</span> </label> </div> </div> """ input = $ $(row).find('input') input.data 'singletonType', 'upgrade' input.data 'singletonName', upgrade input.closest('div').css 'background-color', @countToBackgroundColor(input.val()) $(row).find('.upgrade-name').data 'name', upgrade upgradecollection_content.append row destroyUI: -> @modal.modal 'hide' @modal.remove() $(exportObj).trigger 'xwing-collection:destroyed', this setupHandlers: -> $(exportObj).trigger 'xwing-collection:created', this $(exportObj).on 'xwing-backend:authenticationChanged', (e, authenticated, backend) => # console.log "deauthed, destroying collection UI" @destroyUI() unless authenticated .on 'xwing-collection:saved', (e, collection) => @modal_status.text 'Collection saved' @modal_status.fadeIn 100, => @modal_status.fadeOut 1000 .on 'xwing:languageChanged', @onLanguageChange .on 'xwing:CollectionCheck', @onCollectionCheckSet $ @modal.find('input.expansion-count').change (e) => target = $(e.target) val = target.val() target.val(0) if val < 0 or isNaN(parseInt(val)) @expansions[target.data 'expansion'] = parseInt(target.val()) target.closest('div').css 'background-color', @countToBackgroundColor(target.val()) # console.log "Input changed, triggering collection change" $(exportObj).trigger 'xwing-collection:changed', this $ @modal.find('input.singleton-count').change (e) => target = $(e.target) val = target.val() target.val(0) if isNaN(parseInt(val)) (@singletons[target.data 'singletonType'] ?= {})[target.data 'singletonName'] = parseInt(target.val()) target.closest('div').css 'background-color', @countToBackgroundColor(target.val()) # console.log "Input changed, triggering collection change" $(exportObj).trigger 'xwing-collection:changed', this $ @modal.find('.check-collection').change (e) => if @modal.find('.check-collection').prop('checked') == false result = false @modal_status.text """Collection Tracking Disabled""" else result = true @modal_status.text """Collection Tracking Active""" @checks.collectioncheck = result @modal_status.fadeIn 100, => @modal_status.fadeOut 1000 $(exportObj).trigger 'xwing-collection:changed', this countToBackgroundColor: (count) -> count = parseInt(count) switch when count < 0 'red' when count == 0 '' when count > 0 i = parseInt(200 * Math.pow(0.9, count - 1)) "rgb(#{i}, 255, #{i})" else '' onLanguageChange: (e, language) => @language = language if language != @old_language @old_language = language # console.log "language changed to #{language}" do (language) => @modal.find('.expansion-name').each -> # console.log "translating #{$(this).text()} (#{$(this).data('name')}) to #{language}" $(this).text exportObj.translate language, 'sources', $(this).data('name') @modal.find('.ship-name').each -> $(this).text (if exportObj.ships[$(this).data('name')].display_name then exportObj.ships[$(this).data('name')].display_name else $(this).data('name')) @modal.find('.pilot-name').each -> $(this).text (if exportObj.pilots[$(this).data('name')].display_name then exportObj.pilots[$(this).data('name')].display_name else $(this).data('name')) @modal.find('.upgrade-name').each -> $(this).text (if exportObj.upgrades[$(this).data('name')].display_name then exportObj.upgrades[$(this).data('name')].display_name else $(this).data('name'))
[ { "context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L", "end": 35, "score": 0.9998762607574463, "start": 21, "tag": "NAME", "value": "JeongHoon Byun" }, { "context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.o...
test/parser/python-parser.test.coffee
uppalapatisujitha/CodingConventionofCommitHistory
421
# Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> should = require 'should' parser = require '../../src/parser/python-parser' describe 'python-parser >', -> describe 'indent >', -> it 'check space indent #1', -> convention = parser.indent 'a = 1;', {} convention.indent.space.should.equal 0 it 'check space indent #2', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check space indent #3', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check space indent #4', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check tab indent #1', -> convention = parser.indent '\ta = 1;', {} convention.indent.tab.should.equal 1 it 'check tab indent #2', -> convention = parser.indent '\t\ta = 1;', {} convention.indent.tab.should.equal 1 it 'check tab indent #3', -> convention = parser.indent '\t\t a = 1; ', {} convention.indent.tab.should.equal 1 it 'check tab indent #4', -> convention = parser.indent ' \ta = 1;', {} convention.indent.tab.should.equal 0 it 'check tab indent #5', -> convention = parser.indent 'a = 1;', {} convention.indent.tab.should.equal 0 describe 'linelength >', -> it 'line length is 80 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #3', -> convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 0 it 'line length is 120 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #3', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char120.should.equal 0 it 'line length is 150 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {} convention.linelength.char150.should.equal 1 describe 'imports >', -> it 'imports on separate lines #1', -> convention = parser.imports 'import os', {} convention.imports.separated.should.equal 1 it 'imports on separate lines #2', -> convention = parser.imports ' import foo.bar.yourclass', {} convention.imports.separated.should.equal 1 it 'imports on separate lines #3', -> convention = parser.imports ' import os # ,', {} convention.imports.separated.should.equal 1 it 'imports on separate lines #4', -> convention = parser.imports ' import os, sys', {} convention.imports.separated.should.equal 0 it 'imports on non-separate lines #1', -> convention = parser.imports 'import os, sys', {} convention.imports.noseparated.should.equal 1 it 'imports on non-separate lines #2', -> convention = parser.imports ' import os, sys', {} convention.imports.noseparated.should.equal 1 it 'imports on non-separate lines #3', -> convention = parser.imports 'import os', {} convention.imports.noseparated.should.equal 0 describe 'whitespace >', -> it 'no extraneous whitespace #1', -> convention = parser.whitespace 'spam(ham[1], {eggs: 2})', {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #2', -> convention = parser.whitespace 'if x == 4: print x, y; x, y = y, x', {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #3', -> convention = parser.whitespace 'spam(1)', {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #4', -> convention = parser.whitespace "dict['key'] = list[index]", {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #5', -> convention = parser.whitespace 'x = 1', {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #6', -> convention = parser.whitespace "dict ['key'] = list [index]", {} convention.whitespace.noextra.should.equal 0 it 'extraneous whitespace #1', -> convention = parser.whitespace 'spam( ham[ 1 ], { eggs: 2 } )', {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #2', -> convention = parser.whitespace 'if x == 4 : print x , y ; x , y = y , x', {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #3', -> convention = parser.whitespace 'spam (1)', {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #4', -> convention = parser.whitespace "dict ['key'] = list [index]", {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #5', -> convention = parser.whitespace 'x = 1', {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #6', -> convention = parser.whitespace 'if x == 4: print x, y; x, y = y, x', {} convention.whitespace.extra.should.equal 0
27590
# Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> should = require 'should' parser = require '../../src/parser/python-parser' describe 'python-parser >', -> describe 'indent >', -> it 'check space indent #1', -> convention = parser.indent 'a = 1;', {} convention.indent.space.should.equal 0 it 'check space indent #2', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check space indent #3', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check space indent #4', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check tab indent #1', -> convention = parser.indent '\ta = 1;', {} convention.indent.tab.should.equal 1 it 'check tab indent #2', -> convention = parser.indent '\t\ta = 1;', {} convention.indent.tab.should.equal 1 it 'check tab indent #3', -> convention = parser.indent '\t\t a = 1; ', {} convention.indent.tab.should.equal 1 it 'check tab indent #4', -> convention = parser.indent ' \ta = 1;', {} convention.indent.tab.should.equal 0 it 'check tab indent #5', -> convention = parser.indent 'a = 1;', {} convention.indent.tab.should.equal 0 describe 'linelength >', -> it 'line length is 80 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #3', -> convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 0 it 'line length is 120 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #3', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char120.should.equal 0 it 'line length is 150 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {} convention.linelength.char150.should.equal 1 describe 'imports >', -> it 'imports on separate lines #1', -> convention = parser.imports 'import os', {} convention.imports.separated.should.equal 1 it 'imports on separate lines #2', -> convention = parser.imports ' import foo.bar.yourclass', {} convention.imports.separated.should.equal 1 it 'imports on separate lines #3', -> convention = parser.imports ' import os # ,', {} convention.imports.separated.should.equal 1 it 'imports on separate lines #4', -> convention = parser.imports ' import os, sys', {} convention.imports.separated.should.equal 0 it 'imports on non-separate lines #1', -> convention = parser.imports 'import os, sys', {} convention.imports.noseparated.should.equal 1 it 'imports on non-separate lines #2', -> convention = parser.imports ' import os, sys', {} convention.imports.noseparated.should.equal 1 it 'imports on non-separate lines #3', -> convention = parser.imports 'import os', {} convention.imports.noseparated.should.equal 0 describe 'whitespace >', -> it 'no extraneous whitespace #1', -> convention = parser.whitespace 'spam(ham[1], {eggs: 2})', {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #2', -> convention = parser.whitespace 'if x == 4: print x, y; x, y = y, x', {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #3', -> convention = parser.whitespace 'spam(1)', {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #4', -> convention = parser.whitespace "dict['key'] = list[index]", {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #5', -> convention = parser.whitespace 'x = 1', {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #6', -> convention = parser.whitespace "dict ['key'] = list [index]", {} convention.whitespace.noextra.should.equal 0 it 'extraneous whitespace #1', -> convention = parser.whitespace 'spam( ham[ 1 ], { eggs: 2 } )', {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #2', -> convention = parser.whitespace 'if x == 4 : print x , y ; x , y = y , x', {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #3', -> convention = parser.whitespace 'spam (1)', {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #4', -> convention = parser.whitespace "dict ['key'] = list [index]", {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #5', -> convention = parser.whitespace 'x = 1', {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #6', -> convention = parser.whitespace 'if x == 4: print x, y; x, y = y, x', {} convention.whitespace.extra.should.equal 0
true
# Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> should = require 'should' parser = require '../../src/parser/python-parser' describe 'python-parser >', -> describe 'indent >', -> it 'check space indent #1', -> convention = parser.indent 'a = 1;', {} convention.indent.space.should.equal 0 it 'check space indent #2', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check space indent #3', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check space indent #4', -> convention = parser.indent ' a = 1;', {} convention.indent.space.should.equal 1 it 'check tab indent #1', -> convention = parser.indent '\ta = 1;', {} convention.indent.tab.should.equal 1 it 'check tab indent #2', -> convention = parser.indent '\t\ta = 1;', {} convention.indent.tab.should.equal 1 it 'check tab indent #3', -> convention = parser.indent '\t\t a = 1; ', {} convention.indent.tab.should.equal 1 it 'check tab indent #4', -> convention = parser.indent ' \ta = 1;', {} convention.indent.tab.should.equal 0 it 'check tab indent #5', -> convention = parser.indent 'a = 1;', {} convention.indent.tab.should.equal 0 describe 'linelength >', -> it 'line length is 80 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 1 it 'line length is 80 characters #3', -> convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char80.should.equal 0 it 'line length is 120 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #2', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {} convention.linelength.char120.should.equal 1 it 'line length is 120 characters #3', -> convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {} convention.linelength.char120.should.equal 0 it 'line length is 150 characters #1', -> convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {} convention.linelength.char150.should.equal 1 describe 'imports >', -> it 'imports on separate lines #1', -> convention = parser.imports 'import os', {} convention.imports.separated.should.equal 1 it 'imports on separate lines #2', -> convention = parser.imports ' import foo.bar.yourclass', {} convention.imports.separated.should.equal 1 it 'imports on separate lines #3', -> convention = parser.imports ' import os # ,', {} convention.imports.separated.should.equal 1 it 'imports on separate lines #4', -> convention = parser.imports ' import os, sys', {} convention.imports.separated.should.equal 0 it 'imports on non-separate lines #1', -> convention = parser.imports 'import os, sys', {} convention.imports.noseparated.should.equal 1 it 'imports on non-separate lines #2', -> convention = parser.imports ' import os, sys', {} convention.imports.noseparated.should.equal 1 it 'imports on non-separate lines #3', -> convention = parser.imports 'import os', {} convention.imports.noseparated.should.equal 0 describe 'whitespace >', -> it 'no extraneous whitespace #1', -> convention = parser.whitespace 'spam(ham[1], {eggs: 2})', {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #2', -> convention = parser.whitespace 'if x == 4: print x, y; x, y = y, x', {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #3', -> convention = parser.whitespace 'spam(1)', {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #4', -> convention = parser.whitespace "dict['key'] = list[index]", {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #5', -> convention = parser.whitespace 'x = 1', {} convention.whitespace.noextra.should.equal 1 it 'no extraneous whitespace #6', -> convention = parser.whitespace "dict ['key'] = list [index]", {} convention.whitespace.noextra.should.equal 0 it 'extraneous whitespace #1', -> convention = parser.whitespace 'spam( ham[ 1 ], { eggs: 2 } )', {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #2', -> convention = parser.whitespace 'if x == 4 : print x , y ; x , y = y , x', {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #3', -> convention = parser.whitespace 'spam (1)', {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #4', -> convention = parser.whitespace "dict ['key'] = list [index]", {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #5', -> convention = parser.whitespace 'x = 1', {} convention.whitespace.extra.should.equal 1 it 'extraneous whitespace #6', -> convention = parser.whitespace 'if x == 4: print x, y; x, y = y, x', {} convention.whitespace.extra.should.equal 0
[ { "context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @", "end": 33, "score": 0.9998894929885864, "start": 17, "tag": "NAME", "value": "Abdelhakim RAFIK" }, { "context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki...
src/app/models/clients.coffee
AbdelhakimRafik/Pharmalogy-API
0
### * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 Abdelhakim RAFIK * @date Mar 2021 ### { DataTypes, Model } = require 'sequelize' { sequelize } = require '../../database' ### Client model ### class Client extends Model # initialize model Client.init firstName: type: Sequelize.STRING lastName: type: Sequelize.STRING email: type: Sequelize.STRING phone: type: Sequelize.STRING 10 city: type: Sequelize.STRING country: type: Sequelize.STRING createdAt: allowNull: false type: Sequelize.DATE updatedAt: allowNull: false type: Sequelize.DATE
217754
### * @author <NAME> * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 <NAME> * @date Mar 2021 ### { DataTypes, Model } = require 'sequelize' { sequelize } = require '../../database' ### Client model ### class Client extends Model # initialize model Client.init firstName: type: Sequelize.STRING lastName: type: Sequelize.STRING email: type: Sequelize.STRING phone: type: Sequelize.STRING 10 city: type: Sequelize.STRING country: type: Sequelize.STRING createdAt: allowNull: false type: Sequelize.DATE updatedAt: allowNull: false type: Sequelize.DATE
true
### * @author PI:NAME:<NAME>END_PI * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI * @date Mar 2021 ### { DataTypes, Model } = require 'sequelize' { sequelize } = require '../../database' ### Client model ### class Client extends Model # initialize model Client.init firstName: type: Sequelize.STRING lastName: type: Sequelize.STRING email: type: Sequelize.STRING phone: type: Sequelize.STRING 10 city: type: Sequelize.STRING country: type: Sequelize.STRING createdAt: allowNull: false type: Sequelize.DATE updatedAt: allowNull: false type: Sequelize.DATE
[ { "context": " There's no do-while loop in coffeescript.\n key = randomWord()\n key = randomWord() while obj[key] != undefine", "end": 713, "score": 0.9762066602706909, "start": 703, "tag": "KEY", "value": "randomWord" } ]
test/json0-generator.coffee
p4posting/json0
323
json0 = require '../lib/json0' {randomInt, randomReal, randomWord} = require 'ot-fuzzer' # This is an awful function to clone a document snapshot for use by the random # op generator. .. Since we don't want to corrupt the original object with # the changes the op generator will make. clone = (o) -> JSON.parse(JSON.stringify(o)) randomKey = (obj) -> if Array.isArray(obj) if obj.length == 0 undefined else randomInt obj.length else count = 0 for key of obj result = key if randomReal() < 1/++count result # Generate a random new key for a value in obj. # obj must be an Object. randomNewKey = (obj) -> # There's no do-while loop in coffeescript. key = randomWord() key = randomWord() while obj[key] != undefined key # Generate a random object randomThing = -> switch randomInt 6 when 0 then null when 1 then '' when 2 then randomWord() when 3 obj = {} obj[randomNewKey(obj)] = randomThing() for [1..randomInt(5)] obj when 4 then (randomThing() for [1..randomInt(5)]) when 5 then randomInt(50) # Pick a random path to something in the object. randomPath = (data) -> path = [] while randomReal() > 0.85 and typeof data == 'object' key = randomKey data break unless key? path.push key data = data[key] path module.exports = genRandomOp = (data) -> pct = 0.95 container = data: clone data op = while randomReal() < pct pct *= 0.6 # Pick a random object in the document operate on. path = randomPath(container['data']) # parent = the container for the operand. parent[key] contains the operand. parent = container key = 'data' for p in path parent = parent[key] key = p operand = parent[key] if randomReal() < 0.4 and parent != container and Array.isArray(parent) # List move newIndex = randomInt parent.length # Remove the element from its current position in the list parent.splice key, 1 # Insert it in the new position. parent.splice newIndex, 0, operand {p:path, lm:newIndex} else if randomReal() < 0.3 or operand == null # Replace newValue = randomThing() parent[key] = newValue if Array.isArray(parent) {p:path, ld:operand, li:clone(newValue)} else {p:path, od:operand, oi:clone(newValue)} else if typeof operand == 'string' # String. This code is adapted from the text op generator. if randomReal() > 0.5 or operand.length == 0 # Insert pos = randomInt(operand.length + 1) str = randomWord() + ' ' path.push pos parent[key] = operand[...pos] + str + operand[pos..] c = {p:path, si:str} else # Delete pos = randomInt(operand.length) length = Math.min(randomInt(4), operand.length - pos) str = operand[pos...(pos + length)] path.push pos parent[key] = operand[...pos] + operand[pos + length..] c = {p:path, sd:str} if json0._testStringSubtype # Subtype subOp = {p:path.pop()} if c.si? subOp.i = c.si else subOp.d = c.sd c = {p:path, t:'text0', o:[subOp]} c else if typeof operand == 'number' # Number inc = randomInt(10) - 3 parent[key] += inc {p:path, na:inc} else if Array.isArray(operand) # Array. Replace is covered above, so we'll just randomly insert or delete. # This code looks remarkably similar to string insert, above. if randomReal() > 0.5 or operand.length == 0 # Insert pos = randomInt(operand.length + 1) obj = randomThing() path.push pos operand.splice pos, 0, obj {p:path, li:clone(obj)} else # Delete pos = randomInt operand.length obj = operand[pos] path.push pos operand.splice pos, 1 {p:path, ld:clone(obj)} else # Object k = randomKey(operand) if randomReal() > 0.5 or not k? # Insert k = randomNewKey(operand) obj = randomThing() path.push k operand[k] = obj {p:path, oi:clone(obj)} else obj = operand[k] path.push k delete operand[k] {p:path, od:clone(obj)} [op, container.data]
19024
json0 = require '../lib/json0' {randomInt, randomReal, randomWord} = require 'ot-fuzzer' # This is an awful function to clone a document snapshot for use by the random # op generator. .. Since we don't want to corrupt the original object with # the changes the op generator will make. clone = (o) -> JSON.parse(JSON.stringify(o)) randomKey = (obj) -> if Array.isArray(obj) if obj.length == 0 undefined else randomInt obj.length else count = 0 for key of obj result = key if randomReal() < 1/++count result # Generate a random new key for a value in obj. # obj must be an Object. randomNewKey = (obj) -> # There's no do-while loop in coffeescript. key = <KEY>() key = randomWord() while obj[key] != undefined key # Generate a random object randomThing = -> switch randomInt 6 when 0 then null when 1 then '' when 2 then randomWord() when 3 obj = {} obj[randomNewKey(obj)] = randomThing() for [1..randomInt(5)] obj when 4 then (randomThing() for [1..randomInt(5)]) when 5 then randomInt(50) # Pick a random path to something in the object. randomPath = (data) -> path = [] while randomReal() > 0.85 and typeof data == 'object' key = randomKey data break unless key? path.push key data = data[key] path module.exports = genRandomOp = (data) -> pct = 0.95 container = data: clone data op = while randomReal() < pct pct *= 0.6 # Pick a random object in the document operate on. path = randomPath(container['data']) # parent = the container for the operand. parent[key] contains the operand. parent = container key = 'data' for p in path parent = parent[key] key = p operand = parent[key] if randomReal() < 0.4 and parent != container and Array.isArray(parent) # List move newIndex = randomInt parent.length # Remove the element from its current position in the list parent.splice key, 1 # Insert it in the new position. parent.splice newIndex, 0, operand {p:path, lm:newIndex} else if randomReal() < 0.3 or operand == null # Replace newValue = randomThing() parent[key] = newValue if Array.isArray(parent) {p:path, ld:operand, li:clone(newValue)} else {p:path, od:operand, oi:clone(newValue)} else if typeof operand == 'string' # String. This code is adapted from the text op generator. if randomReal() > 0.5 or operand.length == 0 # Insert pos = randomInt(operand.length + 1) str = randomWord() + ' ' path.push pos parent[key] = operand[...pos] + str + operand[pos..] c = {p:path, si:str} else # Delete pos = randomInt(operand.length) length = Math.min(randomInt(4), operand.length - pos) str = operand[pos...(pos + length)] path.push pos parent[key] = operand[...pos] + operand[pos + length..] c = {p:path, sd:str} if json0._testStringSubtype # Subtype subOp = {p:path.pop()} if c.si? subOp.i = c.si else subOp.d = c.sd c = {p:path, t:'text0', o:[subOp]} c else if typeof operand == 'number' # Number inc = randomInt(10) - 3 parent[key] += inc {p:path, na:inc} else if Array.isArray(operand) # Array. Replace is covered above, so we'll just randomly insert or delete. # This code looks remarkably similar to string insert, above. if randomReal() > 0.5 or operand.length == 0 # Insert pos = randomInt(operand.length + 1) obj = randomThing() path.push pos operand.splice pos, 0, obj {p:path, li:clone(obj)} else # Delete pos = randomInt operand.length obj = operand[pos] path.push pos operand.splice pos, 1 {p:path, ld:clone(obj)} else # Object k = randomKey(operand) if randomReal() > 0.5 or not k? # Insert k = randomNewKey(operand) obj = randomThing() path.push k operand[k] = obj {p:path, oi:clone(obj)} else obj = operand[k] path.push k delete operand[k] {p:path, od:clone(obj)} [op, container.data]
true
json0 = require '../lib/json0' {randomInt, randomReal, randomWord} = require 'ot-fuzzer' # This is an awful function to clone a document snapshot for use by the random # op generator. .. Since we don't want to corrupt the original object with # the changes the op generator will make. clone = (o) -> JSON.parse(JSON.stringify(o)) randomKey = (obj) -> if Array.isArray(obj) if obj.length == 0 undefined else randomInt obj.length else count = 0 for key of obj result = key if randomReal() < 1/++count result # Generate a random new key for a value in obj. # obj must be an Object. randomNewKey = (obj) -> # There's no do-while loop in coffeescript. key = PI:KEY:<KEY>END_PI() key = randomWord() while obj[key] != undefined key # Generate a random object randomThing = -> switch randomInt 6 when 0 then null when 1 then '' when 2 then randomWord() when 3 obj = {} obj[randomNewKey(obj)] = randomThing() for [1..randomInt(5)] obj when 4 then (randomThing() for [1..randomInt(5)]) when 5 then randomInt(50) # Pick a random path to something in the object. randomPath = (data) -> path = [] while randomReal() > 0.85 and typeof data == 'object' key = randomKey data break unless key? path.push key data = data[key] path module.exports = genRandomOp = (data) -> pct = 0.95 container = data: clone data op = while randomReal() < pct pct *= 0.6 # Pick a random object in the document operate on. path = randomPath(container['data']) # parent = the container for the operand. parent[key] contains the operand. parent = container key = 'data' for p in path parent = parent[key] key = p operand = parent[key] if randomReal() < 0.4 and parent != container and Array.isArray(parent) # List move newIndex = randomInt parent.length # Remove the element from its current position in the list parent.splice key, 1 # Insert it in the new position. parent.splice newIndex, 0, operand {p:path, lm:newIndex} else if randomReal() < 0.3 or operand == null # Replace newValue = randomThing() parent[key] = newValue if Array.isArray(parent) {p:path, ld:operand, li:clone(newValue)} else {p:path, od:operand, oi:clone(newValue)} else if typeof operand == 'string' # String. This code is adapted from the text op generator. if randomReal() > 0.5 or operand.length == 0 # Insert pos = randomInt(operand.length + 1) str = randomWord() + ' ' path.push pos parent[key] = operand[...pos] + str + operand[pos..] c = {p:path, si:str} else # Delete pos = randomInt(operand.length) length = Math.min(randomInt(4), operand.length - pos) str = operand[pos...(pos + length)] path.push pos parent[key] = operand[...pos] + operand[pos + length..] c = {p:path, sd:str} if json0._testStringSubtype # Subtype subOp = {p:path.pop()} if c.si? subOp.i = c.si else subOp.d = c.sd c = {p:path, t:'text0', o:[subOp]} c else if typeof operand == 'number' # Number inc = randomInt(10) - 3 parent[key] += inc {p:path, na:inc} else if Array.isArray(operand) # Array. Replace is covered above, so we'll just randomly insert or delete. # This code looks remarkably similar to string insert, above. if randomReal() > 0.5 or operand.length == 0 # Insert pos = randomInt(operand.length + 1) obj = randomThing() path.push pos operand.splice pos, 0, obj {p:path, li:clone(obj)} else # Delete pos = randomInt operand.length obj = operand[pos] path.push pos operand.splice pos, 1 {p:path, ld:clone(obj)} else # Object k = randomKey(operand) if randomReal() > 0.5 or not k? # Insert k = randomNewKey(operand) obj = randomThing() path.push k operand[k] = obj {p:path, oi:clone(obj)} else obj = operand[k] path.push k delete operand[k] {p:path, od:clone(obj)} [op, container.data]
[ { "context": "# Copyright (C) 2013 John Judnich\n# Released under The MIT License - see \"LICENSE\" ", "end": 33, "score": 0.9998663663864136, "start": 21, "tag": "NAME", "value": "John Judnich" } ]
source/Planetfield.coffee
anandprabhakar0507/Kosmos
46
# Copyright (C) 2013 John Judnich # Released under The MIT License - see "LICENSE" file for details. root = exports ? this root.planetBufferSize = 100 root.planetColors = [ [[0.9, 0.7, 0.4], [0.6, 0.4, 0.2]], # dry, hot, boring desert [[0.7, 0.4, 0.0], [0.5, 0.0, 0.0]], # red mars light [[0.2, 0.6, 0.3], [0.4, 0.3, 0.1]], # green jungles [[0.562, 0.225, 0.0], [0.375, 0.0, 0.0]], # red mars dark [[1.2, 1.2, 1.5], [0.4, 0.4, 0.7]], # ice planet [[0.90, 0.95, 1.0], [0.5, 0.5, 0.5]], # gray moon [[0.0, -50.0, -50.0], [0.0, 10.0, 10.0]], # lava!! (red) [[0.2, 0.05, 0.2], [0.7, 0.1, 0.7]], # dark purple gas ] class root.Planetfield constructor: ({starfield, maxPlanetsPerSystem, minOrbitScale, maxOrbitScale, planetSize, nearMeshRange, farMeshRange, spriteRange}) -> @_starfield = starfield @_planetBufferSize = root.planetBufferSize @nearMeshRange = nearMeshRange @farMeshRange = farMeshRange @spriteRange = spriteRange @spriteNearRange = nearMeshRange * 0.25 @planetSize = planetSize @maxPlanetsPerSystem = maxPlanetsPerSystem @minOrbitScale = minOrbitScale @maxOrbitScale = maxOrbitScale @closestPlanetDist = null @closestPlanet = null @closestStarDist = null @closestStar = null randomStream = new RandomStream(universeSeed) # load planet shader @shader = xgl.loadProgram("planetfield") @shader.uniforms = xgl.getProgramUniforms(@shader, ["modelViewMat", "projMat", "spriteSizeAndViewRangeAndBlur"]) @shader.attribs = xgl.getProgramAttribs(@shader, ["aPos", "aUV"]) # we just re-use the index buffer from the starfield because the sprites are indexed the same @iBuff = @_starfield.iBuff if @_planetBufferSize*6 > @iBuff.numItems console.log("Warning: planetBufferSize should not be larger than starBufferSize. Setting planetBufferSize = starBufferSize.") @_planetBufferSize = @iBuff.numItems # prepare vertex buffer @buff = new Float32Array(@_planetBufferSize * 4 * 6) j = 0 for i in [0 .. @_planetBufferSize-1] randAngle = randomStream.range(0, Math.PI*2) for vi in [0..3] angle = ((vi - 0.5) / 2.0) * Math.PI + randAngle u = Math.sin(angle) * Math.sqrt(2) * 0.5 v = Math.cos(angle) * Math.sqrt(2) * 0.5 marker = if vi <= 1 then 1 else -1 @buff[j+3] = u @buff[j+4] = v @buff[j+5] = marker j += 6 @vBuff = gl.createBuffer() @vBuff.itemSize = 6 @vBuff.numItems = @_planetBufferSize * 4 # prepare to render geometric planet representations as well @farMesh = new PlanetFarMesh(8) @farMapGen = new FarMapGenerator(256) # low resolution maps for far planet meshes generateCallback = do (t = this) -> (seed, partial) -> return t.farGenerateCallback(seed, partial) @farMapCache = new ContentCache(16, generateCallback) @nearMesh = new PlanetNearMesh(64, 4096) @nearMapGen = new NearMapGenerator(4096) generateCallback = do (t = this) -> (seed, partial) -> return t.nearGenerateCallback(seed, partial) @nearMapCache = new ContentCache(4, generateCallback) # set up the detail map texture to load after the first few frames # this is because if we load immediately, too much initial loading lag makes loading time seem slow # instead, we want a basic render up and running ASAP so the Kosmos intro can be shown immediately @detailMapTex = null @detailMapTime = 5 # perform this many partial load steps per cube face map # larger means less load stutter, but longer load latency @progressiveLoadSteps = 128.0 @loadingHurryFactor = 1.0; farGenerateCallback: (seed, partial) -> return [true, @farMapGen.generate(seed)] nearGenerateCallback: (seed, partial) -> if partial == null progress = 0.0 maps = @nearMapGen.createMaps() face = 0 console.log("Loading high res maps for planet #{seed}") else progress = partial.progress maps = partial.maps face = partial.face if progress < 1.0-0.0000001 progressPlusOne = progress + (2.0 / @progressiveLoadSteps) * @loadingHurryFactor if progressPlusOne > 1.0 then progressPlusOne = 1.0 @nearMapGen.generateSubMap(maps, seed, face, progress, progressPlusOne) else progressPlusOne = progress + 16 * (2.0 / @progressiveLoadSteps) * @loadingHurryFactor if progressPlusOne > 2.0 then progressPlusOne = 2.0 @nearMapGen.generateSubFinalMap(maps, seed, face, progress-1.0, progressPlusOne-1.0) if progressPlusOne >= 2.0-0.0000001 # we're done with this face face++ progress = 0 else # still more loading to do on this face progress = progressPlusOne if face >= 6 @nearMapGen.finalizeMaps(maps) # all faces have been loaded! time to return the final maps console.log("Done loading high res maps for planet #{seed}!") return [true, maps] else # still more faces to load, so return a partial result return [false, {maps: maps, progress: progress, face: face}] isLoadingComplete: -> return @nearMapCache.isUpToDate() and @farMapCache.isUpToDate() and @detailMapTex != null setPlanetSprite: (index, position) -> j = index * 6*4 for vi in [0..3] @buff[j] = position[0] @buff[j+1] = position[1] @buff[j+2] = position[2] j += 6 render: (camera, originOffset, blur) -> # get list of nearby stars, sorted from nearest to farthest @starList = @_starfield.queryStars(camera.position, originOffset, @spriteRange) @starList.sort( ([ax,ay,az,aw], [cx,cy,cz,cw]) -> (ax*ax + ay*ay + az*az) - (cx*cx + cy*cy + cz*cz) ) # populate vertex buffer with planet positions, and track positions of mesh-range planets @generatePlanetPositions() # determine where the nearest light source is, for planet shader lighting calculations @calculateLightSource() # draw distant planets as sprite dots on the screen @renderSprites(camera, originOffset, blur) # draw medium range planets as a low res sphere @renderFarMeshes(camera, originOffset) # draw the full resolution planets when really close @renderNearMeshes(camera, originOffset) # configure loading speed based on proximity to planet nearestPlanetDist = @getDistanceToClosestPlanet() @_oldHurry = @loadingHurryFactor if nearestPlanetDist < 2.0 then @loadingHurryFactor = 4.0 else if nearestPlanetDist < 5.0 then @loadingHurryFactor = 2.0 else @loadingHurryFactor = 1.0 # load maps that were requested from the cache @farMapGen.start() @farMapCache.update(1) @farMapGen.finish() @nearMapGen.start() @nearMapCache.update(1) @nearMapGen.finish() # generate planet detail map after the first few frames have been rendered, since this creates the perception # of too much loading lag if we load it before displaying anything at all if @detailMapTex == null if @detailMapTime <= 0 console.log("Generating detail maps") detailMapGen = new DetailMapGenerator(512) @detailMapTex = detailMapGen.generate() console.log("Done generating detail maps") else @detailMapTime-- # these functions return the closest distance, or null if no such object is populated getDistanceToClosestPlanet: -> Math.max(@closestPlanetDist - 0.985, 0.0) or @_starfield.viewRange getDistanceToClosestStar: -> Math.max(@closestStarDist - 100.0, 100) or @_starfield.viewRange getDistanceToClosestObject: -> Math.min(@getDistanceToClosestPlanet(), @getDistanceToClosestStar()) getClosestStar: -> @closestStar getClosestPlanet: -> @closestPlanet generatePlanetPositions: -> randomStream = new RandomStream() @numPlanets = 0 @meshPlanets = [] numMeshPlanets = 0 @closestPlanetDist = null @closestPlanet = null @closestStarDist = null @closestStar = null for [dx, dy, dz, w] in @starList randomStream.seed = Math.floor(w * 1000000) systemPlanets = randomStream.intRange(0, @maxPlanetsPerSystem) if @numPlanets + systemPlanets > @_planetBufferSize then break for i in [1 .. systemPlanets] radius = @_starfield.starSize * randomStream.range(@minOrbitScale, @maxOrbitScale) angle = randomStream.radianAngle() [x, y, z] = [dx + radius * Math.sin(angle), dy + radius * Math.cos(angle), dz + w * Math.sin(angle)] # store in @meshPlanets if this is close enough that it will be rendered as a mesh dist = Math.sqrt(x*x + y*y + z*z) alpha = 2.0 - (dist / @farMeshRange) * 0.5 pw = randomStream.unit() if alpha > 0.001 @meshPlanets[numMeshPlanets] = [x, y, z, pw, alpha] numMeshPlanets++ # add this to the vertex buffer to render as a sprite @setPlanetSprite(@numPlanets, [x, y, z]) @numPlanets++ # keep track of closest planet (for autopilot stuff) if @closestPlanet == null or dist < @closestPlanetDist @closestPlanet = [x, y, z] @closestPlanetDist = dist # keep track of closest star (for autopilot stuff) starDist = Math.sqrt(dx*dx + dy*dy + dz*dz) if @closestStar == null or starDist < @closestStarDist @closestStar = [dx, dy, dz] @closestStarDist = starDist # sort the list of planets to render in depth order, since later we need to render farthest to nearest # because the depth buffer is not enabled yet (we're still rendering on massive scales, potentially) if @meshPlanets and @meshPlanets.length > 0 @meshPlanets.sort( ([ax,ay,az,aw,ak], [cx,cy,cz,cw,ck]) -> (ax*ax + ay*ay + az*az) - (cx*cx + cy*cy + cz*cz) ) calculateLightSource: -> if @starList.length < 1 then return # calculate weighted sum of up to three near stars within +-50% distance # to generate a approximate light source position to use in lighting calculations @lightCenter = vec3.fromValues(@starList[0][0], @starList[0][1], @starList[0][2]) for i in [1..2] star = @starList[i] if not star? then break lightPos = vec3.fromValues(star[0], star[1], star[2]) if Math.abs(1.0 - (vec3.distance(lightPos, @lightCenter) / vec3.length(@lightCenter))) < 0.5 vec3.scale(@lightCenter, @lightCenter, 0.75) vec3.scale(lightPos, lightPos, 0.25) vec3.add(@lightCenter, @lightCenter, lightPos) renderFarMeshes: (camera, originOffset) -> if not @meshPlanets or @meshPlanets.length == 0 or @starList.length == 0 then return # update camera depth range camera.far = @farMeshRange * 5.0 camera.near = @nearMeshRange * 0.00001 camera.update() @farMesh.startRender() nearDistSq = @nearMeshRange*@nearMeshRange [localPos, globalPos, lightVec] = [vec3.create(), vec3.create(), vec3.create()] for i in [@meshPlanets.length-1 .. 0] [x, y, z, w, alpha] = @meshPlanets[i] seed = Math.floor(w * 1000000000) # far planet is visible if it's beyond the near planet range or if it's not the closest planet distSq = x*x + y*y + z*z visible = (distSq >= nearDistSq) or (i != 0) # however if the near planet isn't done loading, draw the far planet instead if not visible nearTextureMap = @nearMapCache.getContent(seed) if not nearTextureMap then visible = true if visible localPos = vec3.fromValues(x, y, z) vec3.add(globalPos, localPos, camera.position) vec3.subtract(lightVec, @lightCenter, localPos) vec3.normalize(lightVec, lightVec) textureMap = @farMapCache.getContent(seed) if textureMap colorIndex = seed % planetColors.length [planetColor1, planetColor2] = planetColors[colorIndex] @farMesh.renderInstance(camera, globalPos, lightVec, alpha, textureMap, planetColor1, planetColor2) @farMesh.finishRender() renderNearMeshes: (camera, originOffset) -> if not @meshPlanets or @meshPlanets.length == 0 or @starList.length == 0 then return @nearMesh.startRender() nearDistSq = @nearMeshRange*@nearMeshRange [localPos, globalPos, lightVec] = [vec3.create(), vec3.create(), vec3.create()] # for now we just allow one planet rendered high res at any given time, because we need to adjust # the z buffer range specifically for each planet (and it's preferred to not clear the z buffer multiple times) for i in [0] #[0 .. @meshPlanets.length-1] [x, y, z, w, alpha] = @meshPlanets[i] distSq = x*x + y*y + z*z if distSq < nearDistSq and i == 0 # update camera depth range to perfectly accommodate the planet # NOTE: scaling by 1.733=sqrt(3) accounts for the fact that depths are frustum depths rather # than actual distances from the camera, and therefore the corners of the screen (frustum) # will be off by a factor as much as sqrt(3) dist = Math.sqrt(distSq) camera.far = dist * 1.733 + 1.0 camera.near = dist / 1.733 - 1.0 minNear = 0.000001 + Math.max(dist - 1.0, 0.0) * 0.1 if camera.near <= minNear then camera.near = minNear camera.update() localPos = vec3.fromValues(x, y, z) vec3.add(globalPos, localPos, camera.position) vec3.subtract(lightVec, @lightCenter, localPos) vec3.normalize(lightVec, lightVec) seed = Math.floor(w * 1000000000) textureMap = @nearMapCache.getContent(seed) if textureMap colorIndex = seed % planetColors.length [planetColor1, planetColor2] = planetColors[colorIndex] @nearMesh.renderInstance(camera, globalPos, lightVec, alpha, textureMap, @detailMapTex, planetColor1, planetColor2) # in case the user linked directly to a high-res planet view, we want to cache the # low res representation as well so there's no stutter when backing away from the planet dummy = @farMapCache.getContent(seed) @nearMesh.finishRender() renderSprites: (camera, originOffset, blur) -> # return if nothing to render if @numPlanets <= 0 then return # update camera depth range camera.far = @spriteRange * 1.1 camera.near = @spriteNearRange * 0.9 camera.update() # push render state @_startRenderSprites() # upload planet sprite vertices gl.bufferData(gl.ARRAY_BUFFER, @buff, gl.DYNAMIC_DRAW) # basic setup @vBuff.usedItems = Math.floor(@vBuff.usedItems) if @vBuff.usedItems <= 0 then return seed = Math.floor(Math.abs(seed)) # planet sprite positions in the vertex buffer are relative to camera position, so the model matrix adds back # the camera position. the view matrix will then be composed which then reverses this, producing the expected resulting # view-space positions in the vertex shader. this may seem a little roundabout but the alternate would be to implement # a "camera.viewMatrixButRotationOnlyBecauseIWantToDoViewTranslationInMyDynamicVertexBufferInstead". modelViewMat = mat4.create() mat4.translate(modelViewMat, modelViewMat, camera.position) mat4.mul(modelViewMat, camera.viewMat, modelViewMat) # set shader uniforms gl.uniformMatrix4fv(@shader.uniforms.projMat, false, camera.projMat) gl.uniformMatrix4fv(@shader.uniforms.modelViewMat, false, modelViewMat) gl.uniform4f(@shader.uniforms.spriteSizeAndViewRangeAndBlur, @planetSize * 10.0, @spriteNearRange, @spriteRange, blur) # NOTE: Size is multiplied by 10 because the whole sprite needs to be bigger because only the center area appears filled # issue draw operation gl.drawElements(gl.TRIANGLES, @numPlanets*6, gl.UNSIGNED_SHORT, 0) # pop render state @_finishRenderSprites() _startRenderSprites: -> gl.disable(gl.DEPTH_TEST) gl.disable(gl.CULL_FACE) gl.depthMask(false) gl.enable(gl.BLEND) gl.blendFunc(gl.ONE, gl.ONE) gl.useProgram(@shader) gl.bindBuffer(gl.ARRAY_BUFFER, @vBuff) gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, @iBuff) gl.enableVertexAttribArray(@shader.attribs.aPos) gl.vertexAttribPointer(@shader.attribs.aPos, 3, gl.FLOAT, false, @vBuff.itemSize*4, 0) gl.enableVertexAttribArray(@shader.attribs.aUV) gl.vertexAttribPointer(@shader.attribs.aUV, 3, gl.FLOAT, false, @vBuff.itemSize*4, 4 *3) _finishRenderSprites: -> gl.disableVertexAttribArray(@shader.attribs.aPos) gl.disableVertexAttribArray(@shader.attribs.aUV) gl.bindBuffer(gl.ARRAY_BUFFER, null) gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null) gl.useProgram(null) gl.disable(gl.BLEND) gl.depthMask(true) gl.enable(gl.DEPTH_TEST) gl.enable(gl.CULL_FACE)
46923
# Copyright (C) 2013 <NAME> # Released under The MIT License - see "LICENSE" file for details. root = exports ? this root.planetBufferSize = 100 root.planetColors = [ [[0.9, 0.7, 0.4], [0.6, 0.4, 0.2]], # dry, hot, boring desert [[0.7, 0.4, 0.0], [0.5, 0.0, 0.0]], # red mars light [[0.2, 0.6, 0.3], [0.4, 0.3, 0.1]], # green jungles [[0.562, 0.225, 0.0], [0.375, 0.0, 0.0]], # red mars dark [[1.2, 1.2, 1.5], [0.4, 0.4, 0.7]], # ice planet [[0.90, 0.95, 1.0], [0.5, 0.5, 0.5]], # gray moon [[0.0, -50.0, -50.0], [0.0, 10.0, 10.0]], # lava!! (red) [[0.2, 0.05, 0.2], [0.7, 0.1, 0.7]], # dark purple gas ] class root.Planetfield constructor: ({starfield, maxPlanetsPerSystem, minOrbitScale, maxOrbitScale, planetSize, nearMeshRange, farMeshRange, spriteRange}) -> @_starfield = starfield @_planetBufferSize = root.planetBufferSize @nearMeshRange = nearMeshRange @farMeshRange = farMeshRange @spriteRange = spriteRange @spriteNearRange = nearMeshRange * 0.25 @planetSize = planetSize @maxPlanetsPerSystem = maxPlanetsPerSystem @minOrbitScale = minOrbitScale @maxOrbitScale = maxOrbitScale @closestPlanetDist = null @closestPlanet = null @closestStarDist = null @closestStar = null randomStream = new RandomStream(universeSeed) # load planet shader @shader = xgl.loadProgram("planetfield") @shader.uniforms = xgl.getProgramUniforms(@shader, ["modelViewMat", "projMat", "spriteSizeAndViewRangeAndBlur"]) @shader.attribs = xgl.getProgramAttribs(@shader, ["aPos", "aUV"]) # we just re-use the index buffer from the starfield because the sprites are indexed the same @iBuff = @_starfield.iBuff if @_planetBufferSize*6 > @iBuff.numItems console.log("Warning: planetBufferSize should not be larger than starBufferSize. Setting planetBufferSize = starBufferSize.") @_planetBufferSize = @iBuff.numItems # prepare vertex buffer @buff = new Float32Array(@_planetBufferSize * 4 * 6) j = 0 for i in [0 .. @_planetBufferSize-1] randAngle = randomStream.range(0, Math.PI*2) for vi in [0..3] angle = ((vi - 0.5) / 2.0) * Math.PI + randAngle u = Math.sin(angle) * Math.sqrt(2) * 0.5 v = Math.cos(angle) * Math.sqrt(2) * 0.5 marker = if vi <= 1 then 1 else -1 @buff[j+3] = u @buff[j+4] = v @buff[j+5] = marker j += 6 @vBuff = gl.createBuffer() @vBuff.itemSize = 6 @vBuff.numItems = @_planetBufferSize * 4 # prepare to render geometric planet representations as well @farMesh = new PlanetFarMesh(8) @farMapGen = new FarMapGenerator(256) # low resolution maps for far planet meshes generateCallback = do (t = this) -> (seed, partial) -> return t.farGenerateCallback(seed, partial) @farMapCache = new ContentCache(16, generateCallback) @nearMesh = new PlanetNearMesh(64, 4096) @nearMapGen = new NearMapGenerator(4096) generateCallback = do (t = this) -> (seed, partial) -> return t.nearGenerateCallback(seed, partial) @nearMapCache = new ContentCache(4, generateCallback) # set up the detail map texture to load after the first few frames # this is because if we load immediately, too much initial loading lag makes loading time seem slow # instead, we want a basic render up and running ASAP so the Kosmos intro can be shown immediately @detailMapTex = null @detailMapTime = 5 # perform this many partial load steps per cube face map # larger means less load stutter, but longer load latency @progressiveLoadSteps = 128.0 @loadingHurryFactor = 1.0; farGenerateCallback: (seed, partial) -> return [true, @farMapGen.generate(seed)] nearGenerateCallback: (seed, partial) -> if partial == null progress = 0.0 maps = @nearMapGen.createMaps() face = 0 console.log("Loading high res maps for planet #{seed}") else progress = partial.progress maps = partial.maps face = partial.face if progress < 1.0-0.0000001 progressPlusOne = progress + (2.0 / @progressiveLoadSteps) * @loadingHurryFactor if progressPlusOne > 1.0 then progressPlusOne = 1.0 @nearMapGen.generateSubMap(maps, seed, face, progress, progressPlusOne) else progressPlusOne = progress + 16 * (2.0 / @progressiveLoadSteps) * @loadingHurryFactor if progressPlusOne > 2.0 then progressPlusOne = 2.0 @nearMapGen.generateSubFinalMap(maps, seed, face, progress-1.0, progressPlusOne-1.0) if progressPlusOne >= 2.0-0.0000001 # we're done with this face face++ progress = 0 else # still more loading to do on this face progress = progressPlusOne if face >= 6 @nearMapGen.finalizeMaps(maps) # all faces have been loaded! time to return the final maps console.log("Done loading high res maps for planet #{seed}!") return [true, maps] else # still more faces to load, so return a partial result return [false, {maps: maps, progress: progress, face: face}] isLoadingComplete: -> return @nearMapCache.isUpToDate() and @farMapCache.isUpToDate() and @detailMapTex != null setPlanetSprite: (index, position) -> j = index * 6*4 for vi in [0..3] @buff[j] = position[0] @buff[j+1] = position[1] @buff[j+2] = position[2] j += 6 render: (camera, originOffset, blur) -> # get list of nearby stars, sorted from nearest to farthest @starList = @_starfield.queryStars(camera.position, originOffset, @spriteRange) @starList.sort( ([ax,ay,az,aw], [cx,cy,cz,cw]) -> (ax*ax + ay*ay + az*az) - (cx*cx + cy*cy + cz*cz) ) # populate vertex buffer with planet positions, and track positions of mesh-range planets @generatePlanetPositions() # determine where the nearest light source is, for planet shader lighting calculations @calculateLightSource() # draw distant planets as sprite dots on the screen @renderSprites(camera, originOffset, blur) # draw medium range planets as a low res sphere @renderFarMeshes(camera, originOffset) # draw the full resolution planets when really close @renderNearMeshes(camera, originOffset) # configure loading speed based on proximity to planet nearestPlanetDist = @getDistanceToClosestPlanet() @_oldHurry = @loadingHurryFactor if nearestPlanetDist < 2.0 then @loadingHurryFactor = 4.0 else if nearestPlanetDist < 5.0 then @loadingHurryFactor = 2.0 else @loadingHurryFactor = 1.0 # load maps that were requested from the cache @farMapGen.start() @farMapCache.update(1) @farMapGen.finish() @nearMapGen.start() @nearMapCache.update(1) @nearMapGen.finish() # generate planet detail map after the first few frames have been rendered, since this creates the perception # of too much loading lag if we load it before displaying anything at all if @detailMapTex == null if @detailMapTime <= 0 console.log("Generating detail maps") detailMapGen = new DetailMapGenerator(512) @detailMapTex = detailMapGen.generate() console.log("Done generating detail maps") else @detailMapTime-- # these functions return the closest distance, or null if no such object is populated getDistanceToClosestPlanet: -> Math.max(@closestPlanetDist - 0.985, 0.0) or @_starfield.viewRange getDistanceToClosestStar: -> Math.max(@closestStarDist - 100.0, 100) or @_starfield.viewRange getDistanceToClosestObject: -> Math.min(@getDistanceToClosestPlanet(), @getDistanceToClosestStar()) getClosestStar: -> @closestStar getClosestPlanet: -> @closestPlanet generatePlanetPositions: -> randomStream = new RandomStream() @numPlanets = 0 @meshPlanets = [] numMeshPlanets = 0 @closestPlanetDist = null @closestPlanet = null @closestStarDist = null @closestStar = null for [dx, dy, dz, w] in @starList randomStream.seed = Math.floor(w * 1000000) systemPlanets = randomStream.intRange(0, @maxPlanetsPerSystem) if @numPlanets + systemPlanets > @_planetBufferSize then break for i in [1 .. systemPlanets] radius = @_starfield.starSize * randomStream.range(@minOrbitScale, @maxOrbitScale) angle = randomStream.radianAngle() [x, y, z] = [dx + radius * Math.sin(angle), dy + radius * Math.cos(angle), dz + w * Math.sin(angle)] # store in @meshPlanets if this is close enough that it will be rendered as a mesh dist = Math.sqrt(x*x + y*y + z*z) alpha = 2.0 - (dist / @farMeshRange) * 0.5 pw = randomStream.unit() if alpha > 0.001 @meshPlanets[numMeshPlanets] = [x, y, z, pw, alpha] numMeshPlanets++ # add this to the vertex buffer to render as a sprite @setPlanetSprite(@numPlanets, [x, y, z]) @numPlanets++ # keep track of closest planet (for autopilot stuff) if @closestPlanet == null or dist < @closestPlanetDist @closestPlanet = [x, y, z] @closestPlanetDist = dist # keep track of closest star (for autopilot stuff) starDist = Math.sqrt(dx*dx + dy*dy + dz*dz) if @closestStar == null or starDist < @closestStarDist @closestStar = [dx, dy, dz] @closestStarDist = starDist # sort the list of planets to render in depth order, since later we need to render farthest to nearest # because the depth buffer is not enabled yet (we're still rendering on massive scales, potentially) if @meshPlanets and @meshPlanets.length > 0 @meshPlanets.sort( ([ax,ay,az,aw,ak], [cx,cy,cz,cw,ck]) -> (ax*ax + ay*ay + az*az) - (cx*cx + cy*cy + cz*cz) ) calculateLightSource: -> if @starList.length < 1 then return # calculate weighted sum of up to three near stars within +-50% distance # to generate a approximate light source position to use in lighting calculations @lightCenter = vec3.fromValues(@starList[0][0], @starList[0][1], @starList[0][2]) for i in [1..2] star = @starList[i] if not star? then break lightPos = vec3.fromValues(star[0], star[1], star[2]) if Math.abs(1.0 - (vec3.distance(lightPos, @lightCenter) / vec3.length(@lightCenter))) < 0.5 vec3.scale(@lightCenter, @lightCenter, 0.75) vec3.scale(lightPos, lightPos, 0.25) vec3.add(@lightCenter, @lightCenter, lightPos) renderFarMeshes: (camera, originOffset) -> if not @meshPlanets or @meshPlanets.length == 0 or @starList.length == 0 then return # update camera depth range camera.far = @farMeshRange * 5.0 camera.near = @nearMeshRange * 0.00001 camera.update() @farMesh.startRender() nearDistSq = @nearMeshRange*@nearMeshRange [localPos, globalPos, lightVec] = [vec3.create(), vec3.create(), vec3.create()] for i in [@meshPlanets.length-1 .. 0] [x, y, z, w, alpha] = @meshPlanets[i] seed = Math.floor(w * 1000000000) # far planet is visible if it's beyond the near planet range or if it's not the closest planet distSq = x*x + y*y + z*z visible = (distSq >= nearDistSq) or (i != 0) # however if the near planet isn't done loading, draw the far planet instead if not visible nearTextureMap = @nearMapCache.getContent(seed) if not nearTextureMap then visible = true if visible localPos = vec3.fromValues(x, y, z) vec3.add(globalPos, localPos, camera.position) vec3.subtract(lightVec, @lightCenter, localPos) vec3.normalize(lightVec, lightVec) textureMap = @farMapCache.getContent(seed) if textureMap colorIndex = seed % planetColors.length [planetColor1, planetColor2] = planetColors[colorIndex] @farMesh.renderInstance(camera, globalPos, lightVec, alpha, textureMap, planetColor1, planetColor2) @farMesh.finishRender() renderNearMeshes: (camera, originOffset) -> if not @meshPlanets or @meshPlanets.length == 0 or @starList.length == 0 then return @nearMesh.startRender() nearDistSq = @nearMeshRange*@nearMeshRange [localPos, globalPos, lightVec] = [vec3.create(), vec3.create(), vec3.create()] # for now we just allow one planet rendered high res at any given time, because we need to adjust # the z buffer range specifically for each planet (and it's preferred to not clear the z buffer multiple times) for i in [0] #[0 .. @meshPlanets.length-1] [x, y, z, w, alpha] = @meshPlanets[i] distSq = x*x + y*y + z*z if distSq < nearDistSq and i == 0 # update camera depth range to perfectly accommodate the planet # NOTE: scaling by 1.733=sqrt(3) accounts for the fact that depths are frustum depths rather # than actual distances from the camera, and therefore the corners of the screen (frustum) # will be off by a factor as much as sqrt(3) dist = Math.sqrt(distSq) camera.far = dist * 1.733 + 1.0 camera.near = dist / 1.733 - 1.0 minNear = 0.000001 + Math.max(dist - 1.0, 0.0) * 0.1 if camera.near <= minNear then camera.near = minNear camera.update() localPos = vec3.fromValues(x, y, z) vec3.add(globalPos, localPos, camera.position) vec3.subtract(lightVec, @lightCenter, localPos) vec3.normalize(lightVec, lightVec) seed = Math.floor(w * 1000000000) textureMap = @nearMapCache.getContent(seed) if textureMap colorIndex = seed % planetColors.length [planetColor1, planetColor2] = planetColors[colorIndex] @nearMesh.renderInstance(camera, globalPos, lightVec, alpha, textureMap, @detailMapTex, planetColor1, planetColor2) # in case the user linked directly to a high-res planet view, we want to cache the # low res representation as well so there's no stutter when backing away from the planet dummy = @farMapCache.getContent(seed) @nearMesh.finishRender() renderSprites: (camera, originOffset, blur) -> # return if nothing to render if @numPlanets <= 0 then return # update camera depth range camera.far = @spriteRange * 1.1 camera.near = @spriteNearRange * 0.9 camera.update() # push render state @_startRenderSprites() # upload planet sprite vertices gl.bufferData(gl.ARRAY_BUFFER, @buff, gl.DYNAMIC_DRAW) # basic setup @vBuff.usedItems = Math.floor(@vBuff.usedItems) if @vBuff.usedItems <= 0 then return seed = Math.floor(Math.abs(seed)) # planet sprite positions in the vertex buffer are relative to camera position, so the model matrix adds back # the camera position. the view matrix will then be composed which then reverses this, producing the expected resulting # view-space positions in the vertex shader. this may seem a little roundabout but the alternate would be to implement # a "camera.viewMatrixButRotationOnlyBecauseIWantToDoViewTranslationInMyDynamicVertexBufferInstead". modelViewMat = mat4.create() mat4.translate(modelViewMat, modelViewMat, camera.position) mat4.mul(modelViewMat, camera.viewMat, modelViewMat) # set shader uniforms gl.uniformMatrix4fv(@shader.uniforms.projMat, false, camera.projMat) gl.uniformMatrix4fv(@shader.uniforms.modelViewMat, false, modelViewMat) gl.uniform4f(@shader.uniforms.spriteSizeAndViewRangeAndBlur, @planetSize * 10.0, @spriteNearRange, @spriteRange, blur) # NOTE: Size is multiplied by 10 because the whole sprite needs to be bigger because only the center area appears filled # issue draw operation gl.drawElements(gl.TRIANGLES, @numPlanets*6, gl.UNSIGNED_SHORT, 0) # pop render state @_finishRenderSprites() _startRenderSprites: -> gl.disable(gl.DEPTH_TEST) gl.disable(gl.CULL_FACE) gl.depthMask(false) gl.enable(gl.BLEND) gl.blendFunc(gl.ONE, gl.ONE) gl.useProgram(@shader) gl.bindBuffer(gl.ARRAY_BUFFER, @vBuff) gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, @iBuff) gl.enableVertexAttribArray(@shader.attribs.aPos) gl.vertexAttribPointer(@shader.attribs.aPos, 3, gl.FLOAT, false, @vBuff.itemSize*4, 0) gl.enableVertexAttribArray(@shader.attribs.aUV) gl.vertexAttribPointer(@shader.attribs.aUV, 3, gl.FLOAT, false, @vBuff.itemSize*4, 4 *3) _finishRenderSprites: -> gl.disableVertexAttribArray(@shader.attribs.aPos) gl.disableVertexAttribArray(@shader.attribs.aUV) gl.bindBuffer(gl.ARRAY_BUFFER, null) gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null) gl.useProgram(null) gl.disable(gl.BLEND) gl.depthMask(true) gl.enable(gl.DEPTH_TEST) gl.enable(gl.CULL_FACE)
true
# Copyright (C) 2013 PI:NAME:<NAME>END_PI # Released under The MIT License - see "LICENSE" file for details. root = exports ? this root.planetBufferSize = 100 root.planetColors = [ [[0.9, 0.7, 0.4], [0.6, 0.4, 0.2]], # dry, hot, boring desert [[0.7, 0.4, 0.0], [0.5, 0.0, 0.0]], # red mars light [[0.2, 0.6, 0.3], [0.4, 0.3, 0.1]], # green jungles [[0.562, 0.225, 0.0], [0.375, 0.0, 0.0]], # red mars dark [[1.2, 1.2, 1.5], [0.4, 0.4, 0.7]], # ice planet [[0.90, 0.95, 1.0], [0.5, 0.5, 0.5]], # gray moon [[0.0, -50.0, -50.0], [0.0, 10.0, 10.0]], # lava!! (red) [[0.2, 0.05, 0.2], [0.7, 0.1, 0.7]], # dark purple gas ] class root.Planetfield constructor: ({starfield, maxPlanetsPerSystem, minOrbitScale, maxOrbitScale, planetSize, nearMeshRange, farMeshRange, spriteRange}) -> @_starfield = starfield @_planetBufferSize = root.planetBufferSize @nearMeshRange = nearMeshRange @farMeshRange = farMeshRange @spriteRange = spriteRange @spriteNearRange = nearMeshRange * 0.25 @planetSize = planetSize @maxPlanetsPerSystem = maxPlanetsPerSystem @minOrbitScale = minOrbitScale @maxOrbitScale = maxOrbitScale @closestPlanetDist = null @closestPlanet = null @closestStarDist = null @closestStar = null randomStream = new RandomStream(universeSeed) # load planet shader @shader = xgl.loadProgram("planetfield") @shader.uniforms = xgl.getProgramUniforms(@shader, ["modelViewMat", "projMat", "spriteSizeAndViewRangeAndBlur"]) @shader.attribs = xgl.getProgramAttribs(@shader, ["aPos", "aUV"]) # we just re-use the index buffer from the starfield because the sprites are indexed the same @iBuff = @_starfield.iBuff if @_planetBufferSize*6 > @iBuff.numItems console.log("Warning: planetBufferSize should not be larger than starBufferSize. Setting planetBufferSize = starBufferSize.") @_planetBufferSize = @iBuff.numItems # prepare vertex buffer @buff = new Float32Array(@_planetBufferSize * 4 * 6) j = 0 for i in [0 .. @_planetBufferSize-1] randAngle = randomStream.range(0, Math.PI*2) for vi in [0..3] angle = ((vi - 0.5) / 2.0) * Math.PI + randAngle u = Math.sin(angle) * Math.sqrt(2) * 0.5 v = Math.cos(angle) * Math.sqrt(2) * 0.5 marker = if vi <= 1 then 1 else -1 @buff[j+3] = u @buff[j+4] = v @buff[j+5] = marker j += 6 @vBuff = gl.createBuffer() @vBuff.itemSize = 6 @vBuff.numItems = @_planetBufferSize * 4 # prepare to render geometric planet representations as well @farMesh = new PlanetFarMesh(8) @farMapGen = new FarMapGenerator(256) # low resolution maps for far planet meshes generateCallback = do (t = this) -> (seed, partial) -> return t.farGenerateCallback(seed, partial) @farMapCache = new ContentCache(16, generateCallback) @nearMesh = new PlanetNearMesh(64, 4096) @nearMapGen = new NearMapGenerator(4096) generateCallback = do (t = this) -> (seed, partial) -> return t.nearGenerateCallback(seed, partial) @nearMapCache = new ContentCache(4, generateCallback) # set up the detail map texture to load after the first few frames # this is because if we load immediately, too much initial loading lag makes loading time seem slow # instead, we want a basic render up and running ASAP so the Kosmos intro can be shown immediately @detailMapTex = null @detailMapTime = 5 # perform this many partial load steps per cube face map # larger means less load stutter, but longer load latency @progressiveLoadSteps = 128.0 @loadingHurryFactor = 1.0; farGenerateCallback: (seed, partial) -> return [true, @farMapGen.generate(seed)] nearGenerateCallback: (seed, partial) -> if partial == null progress = 0.0 maps = @nearMapGen.createMaps() face = 0 console.log("Loading high res maps for planet #{seed}") else progress = partial.progress maps = partial.maps face = partial.face if progress < 1.0-0.0000001 progressPlusOne = progress + (2.0 / @progressiveLoadSteps) * @loadingHurryFactor if progressPlusOne > 1.0 then progressPlusOne = 1.0 @nearMapGen.generateSubMap(maps, seed, face, progress, progressPlusOne) else progressPlusOne = progress + 16 * (2.0 / @progressiveLoadSteps) * @loadingHurryFactor if progressPlusOne > 2.0 then progressPlusOne = 2.0 @nearMapGen.generateSubFinalMap(maps, seed, face, progress-1.0, progressPlusOne-1.0) if progressPlusOne >= 2.0-0.0000001 # we're done with this face face++ progress = 0 else # still more loading to do on this face progress = progressPlusOne if face >= 6 @nearMapGen.finalizeMaps(maps) # all faces have been loaded! time to return the final maps console.log("Done loading high res maps for planet #{seed}!") return [true, maps] else # still more faces to load, so return a partial result return [false, {maps: maps, progress: progress, face: face}] isLoadingComplete: -> return @nearMapCache.isUpToDate() and @farMapCache.isUpToDate() and @detailMapTex != null setPlanetSprite: (index, position) -> j = index * 6*4 for vi in [0..3] @buff[j] = position[0] @buff[j+1] = position[1] @buff[j+2] = position[2] j += 6 render: (camera, originOffset, blur) -> # get list of nearby stars, sorted from nearest to farthest @starList = @_starfield.queryStars(camera.position, originOffset, @spriteRange) @starList.sort( ([ax,ay,az,aw], [cx,cy,cz,cw]) -> (ax*ax + ay*ay + az*az) - (cx*cx + cy*cy + cz*cz) ) # populate vertex buffer with planet positions, and track positions of mesh-range planets @generatePlanetPositions() # determine where the nearest light source is, for planet shader lighting calculations @calculateLightSource() # draw distant planets as sprite dots on the screen @renderSprites(camera, originOffset, blur) # draw medium range planets as a low res sphere @renderFarMeshes(camera, originOffset) # draw the full resolution planets when really close @renderNearMeshes(camera, originOffset) # configure loading speed based on proximity to planet nearestPlanetDist = @getDistanceToClosestPlanet() @_oldHurry = @loadingHurryFactor if nearestPlanetDist < 2.0 then @loadingHurryFactor = 4.0 else if nearestPlanetDist < 5.0 then @loadingHurryFactor = 2.0 else @loadingHurryFactor = 1.0 # load maps that were requested from the cache @farMapGen.start() @farMapCache.update(1) @farMapGen.finish() @nearMapGen.start() @nearMapCache.update(1) @nearMapGen.finish() # generate planet detail map after the first few frames have been rendered, since this creates the perception # of too much loading lag if we load it before displaying anything at all if @detailMapTex == null if @detailMapTime <= 0 console.log("Generating detail maps") detailMapGen = new DetailMapGenerator(512) @detailMapTex = detailMapGen.generate() console.log("Done generating detail maps") else @detailMapTime-- # these functions return the closest distance, or null if no such object is populated getDistanceToClosestPlanet: -> Math.max(@closestPlanetDist - 0.985, 0.0) or @_starfield.viewRange getDistanceToClosestStar: -> Math.max(@closestStarDist - 100.0, 100) or @_starfield.viewRange getDistanceToClosestObject: -> Math.min(@getDistanceToClosestPlanet(), @getDistanceToClosestStar()) getClosestStar: -> @closestStar getClosestPlanet: -> @closestPlanet generatePlanetPositions: -> randomStream = new RandomStream() @numPlanets = 0 @meshPlanets = [] numMeshPlanets = 0 @closestPlanetDist = null @closestPlanet = null @closestStarDist = null @closestStar = null for [dx, dy, dz, w] in @starList randomStream.seed = Math.floor(w * 1000000) systemPlanets = randomStream.intRange(0, @maxPlanetsPerSystem) if @numPlanets + systemPlanets > @_planetBufferSize then break for i in [1 .. systemPlanets] radius = @_starfield.starSize * randomStream.range(@minOrbitScale, @maxOrbitScale) angle = randomStream.radianAngle() [x, y, z] = [dx + radius * Math.sin(angle), dy + radius * Math.cos(angle), dz + w * Math.sin(angle)] # store in @meshPlanets if this is close enough that it will be rendered as a mesh dist = Math.sqrt(x*x + y*y + z*z) alpha = 2.0 - (dist / @farMeshRange) * 0.5 pw = randomStream.unit() if alpha > 0.001 @meshPlanets[numMeshPlanets] = [x, y, z, pw, alpha] numMeshPlanets++ # add this to the vertex buffer to render as a sprite @setPlanetSprite(@numPlanets, [x, y, z]) @numPlanets++ # keep track of closest planet (for autopilot stuff) if @closestPlanet == null or dist < @closestPlanetDist @closestPlanet = [x, y, z] @closestPlanetDist = dist # keep track of closest star (for autopilot stuff) starDist = Math.sqrt(dx*dx + dy*dy + dz*dz) if @closestStar == null or starDist < @closestStarDist @closestStar = [dx, dy, dz] @closestStarDist = starDist # sort the list of planets to render in depth order, since later we need to render farthest to nearest # because the depth buffer is not enabled yet (we're still rendering on massive scales, potentially) if @meshPlanets and @meshPlanets.length > 0 @meshPlanets.sort( ([ax,ay,az,aw,ak], [cx,cy,cz,cw,ck]) -> (ax*ax + ay*ay + az*az) - (cx*cx + cy*cy + cz*cz) ) calculateLightSource: -> if @starList.length < 1 then return # calculate weighted sum of up to three near stars within +-50% distance # to generate a approximate light source position to use in lighting calculations @lightCenter = vec3.fromValues(@starList[0][0], @starList[0][1], @starList[0][2]) for i in [1..2] star = @starList[i] if not star? then break lightPos = vec3.fromValues(star[0], star[1], star[2]) if Math.abs(1.0 - (vec3.distance(lightPos, @lightCenter) / vec3.length(@lightCenter))) < 0.5 vec3.scale(@lightCenter, @lightCenter, 0.75) vec3.scale(lightPos, lightPos, 0.25) vec3.add(@lightCenter, @lightCenter, lightPos) renderFarMeshes: (camera, originOffset) -> if not @meshPlanets or @meshPlanets.length == 0 or @starList.length == 0 then return # update camera depth range camera.far = @farMeshRange * 5.0 camera.near = @nearMeshRange * 0.00001 camera.update() @farMesh.startRender() nearDistSq = @nearMeshRange*@nearMeshRange [localPos, globalPos, lightVec] = [vec3.create(), vec3.create(), vec3.create()] for i in [@meshPlanets.length-1 .. 0] [x, y, z, w, alpha] = @meshPlanets[i] seed = Math.floor(w * 1000000000) # far planet is visible if it's beyond the near planet range or if it's not the closest planet distSq = x*x + y*y + z*z visible = (distSq >= nearDistSq) or (i != 0) # however if the near planet isn't done loading, draw the far planet instead if not visible nearTextureMap = @nearMapCache.getContent(seed) if not nearTextureMap then visible = true if visible localPos = vec3.fromValues(x, y, z) vec3.add(globalPos, localPos, camera.position) vec3.subtract(lightVec, @lightCenter, localPos) vec3.normalize(lightVec, lightVec) textureMap = @farMapCache.getContent(seed) if textureMap colorIndex = seed % planetColors.length [planetColor1, planetColor2] = planetColors[colorIndex] @farMesh.renderInstance(camera, globalPos, lightVec, alpha, textureMap, planetColor1, planetColor2) @farMesh.finishRender() renderNearMeshes: (camera, originOffset) -> if not @meshPlanets or @meshPlanets.length == 0 or @starList.length == 0 then return @nearMesh.startRender() nearDistSq = @nearMeshRange*@nearMeshRange [localPos, globalPos, lightVec] = [vec3.create(), vec3.create(), vec3.create()] # for now we just allow one planet rendered high res at any given time, because we need to adjust # the z buffer range specifically for each planet (and it's preferred to not clear the z buffer multiple times) for i in [0] #[0 .. @meshPlanets.length-1] [x, y, z, w, alpha] = @meshPlanets[i] distSq = x*x + y*y + z*z if distSq < nearDistSq and i == 0 # update camera depth range to perfectly accommodate the planet # NOTE: scaling by 1.733=sqrt(3) accounts for the fact that depths are frustum depths rather # than actual distances from the camera, and therefore the corners of the screen (frustum) # will be off by a factor as much as sqrt(3) dist = Math.sqrt(distSq) camera.far = dist * 1.733 + 1.0 camera.near = dist / 1.733 - 1.0 minNear = 0.000001 + Math.max(dist - 1.0, 0.0) * 0.1 if camera.near <= minNear then camera.near = minNear camera.update() localPos = vec3.fromValues(x, y, z) vec3.add(globalPos, localPos, camera.position) vec3.subtract(lightVec, @lightCenter, localPos) vec3.normalize(lightVec, lightVec) seed = Math.floor(w * 1000000000) textureMap = @nearMapCache.getContent(seed) if textureMap colorIndex = seed % planetColors.length [planetColor1, planetColor2] = planetColors[colorIndex] @nearMesh.renderInstance(camera, globalPos, lightVec, alpha, textureMap, @detailMapTex, planetColor1, planetColor2) # in case the user linked directly to a high-res planet view, we want to cache the # low res representation as well so there's no stutter when backing away from the planet dummy = @farMapCache.getContent(seed) @nearMesh.finishRender() renderSprites: (camera, originOffset, blur) -> # return if nothing to render if @numPlanets <= 0 then return # update camera depth range camera.far = @spriteRange * 1.1 camera.near = @spriteNearRange * 0.9 camera.update() # push render state @_startRenderSprites() # upload planet sprite vertices gl.bufferData(gl.ARRAY_BUFFER, @buff, gl.DYNAMIC_DRAW) # basic setup @vBuff.usedItems = Math.floor(@vBuff.usedItems) if @vBuff.usedItems <= 0 then return seed = Math.floor(Math.abs(seed)) # planet sprite positions in the vertex buffer are relative to camera position, so the model matrix adds back # the camera position. the view matrix will then be composed which then reverses this, producing the expected resulting # view-space positions in the vertex shader. this may seem a little roundabout but the alternate would be to implement # a "camera.viewMatrixButRotationOnlyBecauseIWantToDoViewTranslationInMyDynamicVertexBufferInstead". modelViewMat = mat4.create() mat4.translate(modelViewMat, modelViewMat, camera.position) mat4.mul(modelViewMat, camera.viewMat, modelViewMat) # set shader uniforms gl.uniformMatrix4fv(@shader.uniforms.projMat, false, camera.projMat) gl.uniformMatrix4fv(@shader.uniforms.modelViewMat, false, modelViewMat) gl.uniform4f(@shader.uniforms.spriteSizeAndViewRangeAndBlur, @planetSize * 10.0, @spriteNearRange, @spriteRange, blur) # NOTE: Size is multiplied by 10 because the whole sprite needs to be bigger because only the center area appears filled # issue draw operation gl.drawElements(gl.TRIANGLES, @numPlanets*6, gl.UNSIGNED_SHORT, 0) # pop render state @_finishRenderSprites() _startRenderSprites: -> gl.disable(gl.DEPTH_TEST) gl.disable(gl.CULL_FACE) gl.depthMask(false) gl.enable(gl.BLEND) gl.blendFunc(gl.ONE, gl.ONE) gl.useProgram(@shader) gl.bindBuffer(gl.ARRAY_BUFFER, @vBuff) gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, @iBuff) gl.enableVertexAttribArray(@shader.attribs.aPos) gl.vertexAttribPointer(@shader.attribs.aPos, 3, gl.FLOAT, false, @vBuff.itemSize*4, 0) gl.enableVertexAttribArray(@shader.attribs.aUV) gl.vertexAttribPointer(@shader.attribs.aUV, 3, gl.FLOAT, false, @vBuff.itemSize*4, 4 *3) _finishRenderSprites: -> gl.disableVertexAttribArray(@shader.attribs.aPos) gl.disableVertexAttribArray(@shader.attribs.aUV) gl.bindBuffer(gl.ARRAY_BUFFER, null) gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null) gl.useProgram(null) gl.disable(gl.BLEND) gl.depthMask(true) gl.enable(gl.DEPTH_TEST) gl.enable(gl.CULL_FACE)
[ { "context": "9\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\n\t,\n\t\tosis: [\"John\"]\n\t\tregexp: ///(^|#{bcv_parser::regexps.pre_book}", "end": 15997, "score": 0.7538095712661743, "start": 15993, "tag": "NAME", "value": "John" } ]
lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/nl/regexps.coffee
saiba-mais/bible-lessons
149
bcv_parser::regexps.space = "[\\s\\xa0]" bcv_parser::regexps.escaped_passage = /// (?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3` ( # Start inverted book/chapter (cb) (?: (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: \d+ (?: th | nd | st ) \s* ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter (?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* ) )? # End inverted book/chapter (cb) \x1f(\d+)(?:/\d+)?\x1f #book (?: /\d+\x1f #special Psalm chapters | [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014] | opschrift (?! [a-z] ) #could be followed by a number | en#{bcv_parser::regexps.space}+volgende#{bcv_parser::regexps.space}+verzen | zie#{bcv_parser::regexps.space}+ook | hoofdstukken | hoofdstuk | verzen | vers | vgl | en | vs | - | v | [a-e] (?! \w ) #a-e allows 1:1a | $ #or the end of the string )+ ) ///gi # These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff. bcv_parser::regexps.match_end_split = /// \d \W* opschrift | \d \W* en#{bcv_parser::regexps.space}+volgende#{bcv_parser::regexps.space}+verzen (?: [\s\xa0*]* \.)? | \d [\s\xa0*]* [a-e] (?! \w ) | \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis | [\d\x1f] ///gi bcv_parser::regexps.control = /[\x1e\x1f]/g bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]" bcv_parser::regexps.first = "(?:Eerste|1e|I|1)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.second = "(?:Tweede|2e|II|2)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.third = "(?:Derde|3e|III|3)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:en|vgl|zie#{bcv_parser::regexps.space}+ook)|-)" bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|-)" # Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself. bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) -> books = [ osis: ["Ps"] apocrypha: true extra: "2" regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit. Ps151 # Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own. )(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS. , osis: ["Gen"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:Genesis)|(?:(?:1e?|I)[\s\xa0]*Mozes|Beresjiet|Ge?n|(?:1e?|I)\.[\s\xa0]*Mozes|Eerste[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Exod"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:Exodus)|(?:(?:2e?|II)[\s\xa0]*Mozes|Sjemot|Exod|Ex|(?:2e?|II)\.[\s\xa0]*Mozes|Tweede[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bel"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bel(?:[\s\xa0]*en[\s\xa0]*de[\s\xa0]*draak)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lev"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:Leviticus)|(?:(?:3e?|III)[\s\xa0]*Mozes|[VW]ajikra|Le?v|(?:3e?|III)\.[\s\xa0]*Mozes|Derde[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Num"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:B[ae]midbar|Numb?eri|Num?|(?:IV|4)[\s\xa0]*Mozes|(?:IV|4)\.[\s\xa0]*Mozes|Vierde[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sir"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sirach)|(?:Wijsheid[\s\xa0]*van[\s\xa0]*(?:J(?:ozua[\s\xa0]*Ben|ezus)|Ben)[\s\xa0]*Sirach|Ecclesiasticus|Sir|Jezus[\s\xa0]*Sirach) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Wis"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Wijsheid[\s\xa0]*van[\s\xa0]*Salomo)|(?:Het[\s\xa0]*boek[\s\xa0]*der[\s\xa0]*wijsheid|Wi(?:jsheid|s)|De[\s\xa0]*wijsheid[\s\xa0]*van[\s\xa0]*Salomo) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lam"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Kl(?:aagl(?:iederen)?)?|Lam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["EpJer"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Brief[\s\xa0]*van[\s\xa0]*Jeremia|EpJer) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Op(?:enb(?:aring(?:[\s\xa0]*van[\s\xa0]*Johannes|en)?)?)?|Ap[ck]|Rev|Apocalyps) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrMan"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Man(?:asse)?|PrMan) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Deut"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:D(?:e(?:ut(?:eronomium)?|wariem)|t)|(?:V(?:ijfde|\.)?|5\.?)[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Josh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jo(?:z(?:ua)?|sh)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Judg"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:R(?:i(?:cht(?:eren?)?)?|e(?:chters|cht)?)|Judg) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ruth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:R(?:uth|t)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:[13]e|[13]|I(?:II)?)[\s\xa0]*E(?:sdras|zra)|1Esd|(?:[13]e|[13]|I(?:II)?)\.[\s\xa0]*E(?:sdras|zra)|Derde[\s\xa0]*E(?:sdras|zra)|Eerste[\s\xa0]*E(?:sdras|zra)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:I[IV]|4|2e?)[\s\xa0]*E(?:sdras|zra)|2Esd|(?:I[IV]|4|2e?)\.[\s\xa0]*E(?:sdras|zra)|Vierde[\s\xa0]*E(?:sdras|zra)|Tweede[\s\xa0]*E(?:sdras|zra)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Isa"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:es(?:aja)?|s)|Isa) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Sam(?:u[e\xEB]l)?|Samuel[\s\xa0]*II|2Sam|2[\s\xa0]*S|(?:2e|II)[\s\xa0]*Sam(?:u[e\xEB]l)?|(?:2e?|II)\.[\s\xa0]*Sam(?:u[e\xEB]l)?|Tweede[\s\xa0]*Sam(?:u[e\xEB]l)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Sam(?:u[e\xEB]l)?|Samuel[\s\xa0]*I|1Sam|1[\s\xa0]*S|(?:1e|I)[\s\xa0]*Sam(?:u[e\xEB]l)?|(?:1e?|I)\.[\s\xa0]*Sam(?:u[e\xEB]l)?|Eerste[\s\xa0]*Sam(?:u[e\xEB]l)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e?|II)[\s\xa0]*Ko(?:n(?:ingen)?)?|2Kgs|(?:2e?|II)\.[\s\xa0]*Ko(?:n(?:ingen)?)?|Tweede[\s\xa0]*Ko(?:n(?:ingen)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e?|I)[\s\xa0]*Ko(?:n(?:ingen)?)?|1Kgs|(?:1e?|I)\.[\s\xa0]*Ko(?:n(?:ingen)?)?|Eerste[\s\xa0]*Ko(?:n(?:ingen)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Kron(?:ieken)?|(?:[\s\xa0]*K|Ch)r)|(?:2e|II)[\s\xa0]*Kron(?:ieken)?|(?:2e?|II)\.[\s\xa0]*Kron(?:ieken)?|Tweede[\s\xa0]*Kron(?:ieken)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Kron(?:ieken)?|(?:[\s\xa0]*K|Ch)r)|(?:1e|I)[\s\xa0]*Kron(?:ieken)?|(?:1e?|I)\.[\s\xa0]*Kron(?:ieken)?|Eerste[\s\xa0]*Kron(?:ieken)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ezra?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Neh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Neh(?:emia)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["GkEsth"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Est(?:er[\s\xa0]*\(Gr(?:ieks|\.)?\)|[\s\xa0]*gr)|GkEsth) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Esth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Est(?:h(?:er)?|er)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Job"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Job) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ps"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ps(?:alm(?:en)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrAzar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Gebed[\s\xa0]*van[\s\xa0]*Azarja|PrAzar) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Prov"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Spr(?:euken)?|Prov) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eccl"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Prediker|Eccl|Pr(?:ed)?|[KQ]oheleth?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["SgThree"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lied[\s\xa0]*van[\s\xa0]*de[\s\xa0]*drie[\s\xa0]*jongemannen|SgThree|Gezang[\s\xa0]*der[\s\xa0]*drie[\s\xa0]*mannen[\s\xa0]*in[\s\xa0]*het[\s\xa0]*vuur) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Song"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:H(?:ooglied|l)|Song|Hoogl|Canticum[\s\xa0]*canticorum) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jer"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:er(?:emia)?|r)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Eze(?:ch(?:i[e\xEB]l)?|k)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Dan"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Da(?:n(?:i[e\xEB]l)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hos(?:ea)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Joel"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:o[e\xEB])?l) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Amos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Am(?:os)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Obad"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ob(?:ad(?:ja)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jonah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jon(?:ah?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mic"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mi(?:c(?:ha|a)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Nah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Nah(?:um)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hab"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hab(?:akuk)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zeph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ze(?:f(?:anja)?|ph)|Sef(?:anja)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hag"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hag(?:g(?:a[i\xEF])?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zech"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Z(?:ach(?:aria)?|ech)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mal(?:eachi)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Matt"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:M(?:att(?:h[e\xE9]|e)[u\xFC]s|at(?:th?)?|t)|Evangelie[\s\xa0]*volgens[\s\xa0]*Matte[u\xFC]s) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mark"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mar[ck]us)|(?:Evangelie[\s\xa0]*volgens[\s\xa0]*Mar[ck]us|M(?:ar[ck]|[ckr])) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Luke"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lu[ck]as)|(?:Evangelie[\s\xa0]*volgens[\s\xa0]*Lu[ck]as|L(?:u(?:ke|c)|[ck]|uk)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1John)|(?:(?:1e?|I)\.[\s\xa0]*Joh(?:annes)?|(?:1e?|I)[\s\xa0]*Joh(?:annes)?|Eerste[\s\xa0]*Joh(?:annes)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2John)|(?:(?:2e?|II)\.[\s\xa0]*Joh(?:annes)?|(?:2e?|II)[\s\xa0]*Joh(?:annes)?|Tweede[\s\xa0]*Joh(?:annes)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3John)|(?:(?:3e?|III)\.[\s\xa0]*Joh(?:annes)?|(?:3e?|III)[\s\xa0]*Joh(?:annes)?|Derde[\s\xa0]*Joh(?:annes)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["John"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Evangelie[\s\xa0]*volgens[\s\xa0]*Johannes|Joh(?:annes|n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Acts"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:H(?:and(?:elingen(?:[\s\xa0]*(?:van[\s\xa0]*de|der)[\s\xa0]*apostelen)?)?|nd)|Acts) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rom"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Rom(?:einen(?:brief)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e?|II)[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))|2Cor|(?:2e?|II)\.[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))|Tweede[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e?|I)[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))|1Cor|(?:1e?|I)\.[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))|Eerste[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Gal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Gal(?:aten(?:brief)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:E(?:f(?:ez(?:i[e\xEB]rs)?)?|ph)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phil"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Fil(?:ip(?:penzen)?)?|Phil) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Col"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:[CK]ol(?:ossenzen)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e|II)[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)|2(?:[\s\xa0]*Th?ess(?:alonicenzen)?|(?:[\s\xa0]*Th?e|Thes)s)|(?:2e?|II)\.[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)|Tweede[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e|I)[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)|1(?:[\s\xa0]*Th?ess(?:alonicenzen)?|(?:[\s\xa0]*Th?e|Thes)s)|(?:1e?|I)\.[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)|Eerste[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e?|II)[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?|2Tim|(?:2e?|II)\.[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?|Tweede[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e?|I)[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?|1Tim|(?:1e?|I)\.[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?|Eerste[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Titus"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Tit(?:us)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phlm"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Fil(?:em(?:on)?|\xE9mon|m)|Phlm) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Heb"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Heb(?:r(?:ee[e\xEB]n)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jas"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ja(?:k(?:obus)?|s)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Pet(?:r(?:us)?)?|[\s\xa0]*Pe|Pet)|(?:2e|II)[\s\xa0]*Pet(?:r(?:us)?)?|(?:2e?|II)\.[\s\xa0]*Pet(?:r(?:us)?)?|Tweede[\s\xa0]*Pet(?:r(?:us)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Pet(?:r(?:us)?)?|[\s\xa0]*Pe|Pet)|(?:1e|I)[\s\xa0]*Pet(?:r(?:us)?)?|(?:1e?|I)\.[\s\xa0]*Pet(?:r(?:us)?)?|Eerste[\s\xa0]*Pet(?:r(?:us)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jude"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jud(?:as|e)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Tob"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Tob(?:i(?:as?|t)|\xEDas?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jdt"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:udith?|dt)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bar(?:uch)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sus"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sus(?:anna)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e?|II)[\s\xa0]*Mak(?:kabee[e\xEB]n)?|2Macc|(?:2e?|II)\.[\s\xa0]*Mak(?:kabee[e\xEB]n)?|Tweede[\s\xa0]*Mak(?:kabee[e\xEB]n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:3e?|III)[\s\xa0]*Mak(?:kabee[e\xEB]n)?|3Macc|(?:3e?|III)\.[\s\xa0]*Mak(?:kabee[e\xEB]n)?|Derde[\s\xa0]*Mak(?:kabee[e\xEB]n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["4Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:IV|4)[\s\xa0]*Mak(?:kabee[e\xEB]n)?|4Macc|(?:IV|4)\.[\s\xa0]*Mak(?:kabee[e\xEB]n)?|Vierde[\s\xa0]*Mak(?:kabee[e\xEB]n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e?|I)[\s\xa0]*Mak(?:kabee[e\xEB]n)?|1Macc|(?:1e?|I)\.[\s\xa0]*Mak(?:kabee[e\xEB]n)?|Eerste[\s\xa0]*Mak(?:kabee[e\xEB]n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek", "Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ez) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi ] # Short-circuit the look if we know we want all the books. return books if include_apocrypha is true and case_sensitive is "none" # Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9. out = [] for book in books continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true if case_sensitive is "books" book.regexp = new RegExp book.regexp.source, "g" out.push book out # Default to not using the Apocrypha bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
199019
bcv_parser::regexps.space = "[\\s\\xa0]" bcv_parser::regexps.escaped_passage = /// (?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3` ( # Start inverted book/chapter (cb) (?: (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: \d+ (?: th | nd | st ) \s* ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter (?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* ) )? # End inverted book/chapter (cb) \x1f(\d+)(?:/\d+)?\x1f #book (?: /\d+\x1f #special Psalm chapters | [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014] | opschrift (?! [a-z] ) #could be followed by a number | en#{bcv_parser::regexps.space}+volgende#{bcv_parser::regexps.space}+verzen | zie#{bcv_parser::regexps.space}+ook | hoofdstukken | hoofdstuk | verzen | vers | vgl | en | vs | - | v | [a-e] (?! \w ) #a-e allows 1:1a | $ #or the end of the string )+ ) ///gi # These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff. bcv_parser::regexps.match_end_split = /// \d \W* opschrift | \d \W* en#{bcv_parser::regexps.space}+volgende#{bcv_parser::regexps.space}+verzen (?: [\s\xa0*]* \.)? | \d [\s\xa0*]* [a-e] (?! \w ) | \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis | [\d\x1f] ///gi bcv_parser::regexps.control = /[\x1e\x1f]/g bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]" bcv_parser::regexps.first = "(?:Eerste|1e|I|1)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.second = "(?:Tweede|2e|II|2)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.third = "(?:Derde|3e|III|3)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:en|vgl|zie#{bcv_parser::regexps.space}+ook)|-)" bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|-)" # Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself. bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) -> books = [ osis: ["Ps"] apocrypha: true extra: "2" regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit. Ps151 # Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own. )(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS. , osis: ["Gen"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:Genesis)|(?:(?:1e?|I)[\s\xa0]*Mozes|Beresjiet|Ge?n|(?:1e?|I)\.[\s\xa0]*Mozes|Eerste[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Exod"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:Exodus)|(?:(?:2e?|II)[\s\xa0]*Mozes|Sjemot|Exod|Ex|(?:2e?|II)\.[\s\xa0]*Mozes|Tweede[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bel"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bel(?:[\s\xa0]*en[\s\xa0]*de[\s\xa0]*draak)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lev"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:Leviticus)|(?:(?:3e?|III)[\s\xa0]*Mozes|[VW]ajikra|Le?v|(?:3e?|III)\.[\s\xa0]*Mozes|Derde[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Num"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:B[ae]midbar|Numb?eri|Num?|(?:IV|4)[\s\xa0]*Mozes|(?:IV|4)\.[\s\xa0]*Mozes|Vierde[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sir"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sirach)|(?:Wijsheid[\s\xa0]*van[\s\xa0]*(?:J(?:ozua[\s\xa0]*Ben|ezus)|Ben)[\s\xa0]*Sirach|Ecclesiasticus|Sir|Jezus[\s\xa0]*Sirach) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Wis"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Wijsheid[\s\xa0]*van[\s\xa0]*Salomo)|(?:Het[\s\xa0]*boek[\s\xa0]*der[\s\xa0]*wijsheid|Wi(?:jsheid|s)|De[\s\xa0]*wijsheid[\s\xa0]*van[\s\xa0]*Salomo) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lam"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Kl(?:aagl(?:iederen)?)?|Lam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["EpJer"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Brief[\s\xa0]*van[\s\xa0]*Jeremia|EpJer) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Op(?:enb(?:aring(?:[\s\xa0]*van[\s\xa0]*Johannes|en)?)?)?|Ap[ck]|Rev|Apocalyps) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrMan"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Man(?:asse)?|PrMan) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Deut"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:D(?:e(?:ut(?:eronomium)?|wariem)|t)|(?:V(?:ijfde|\.)?|5\.?)[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Josh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jo(?:z(?:ua)?|sh)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Judg"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:R(?:i(?:cht(?:eren?)?)?|e(?:chters|cht)?)|Judg) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ruth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:R(?:uth|t)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:[13]e|[13]|I(?:II)?)[\s\xa0]*E(?:sdras|zra)|1Esd|(?:[13]e|[13]|I(?:II)?)\.[\s\xa0]*E(?:sdras|zra)|Derde[\s\xa0]*E(?:sdras|zra)|Eerste[\s\xa0]*E(?:sdras|zra)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:I[IV]|4|2e?)[\s\xa0]*E(?:sdras|zra)|2Esd|(?:I[IV]|4|2e?)\.[\s\xa0]*E(?:sdras|zra)|Vierde[\s\xa0]*E(?:sdras|zra)|Tweede[\s\xa0]*E(?:sdras|zra)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Isa"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:es(?:aja)?|s)|Isa) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Sam(?:u[e\xEB]l)?|Samuel[\s\xa0]*II|2Sam|2[\s\xa0]*S|(?:2e|II)[\s\xa0]*Sam(?:u[e\xEB]l)?|(?:2e?|II)\.[\s\xa0]*Sam(?:u[e\xEB]l)?|Tweede[\s\xa0]*Sam(?:u[e\xEB]l)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Sam(?:u[e\xEB]l)?|Samuel[\s\xa0]*I|1Sam|1[\s\xa0]*S|(?:1e|I)[\s\xa0]*Sam(?:u[e\xEB]l)?|(?:1e?|I)\.[\s\xa0]*Sam(?:u[e\xEB]l)?|Eerste[\s\xa0]*Sam(?:u[e\xEB]l)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e?|II)[\s\xa0]*Ko(?:n(?:ingen)?)?|2Kgs|(?:2e?|II)\.[\s\xa0]*Ko(?:n(?:ingen)?)?|Tweede[\s\xa0]*Ko(?:n(?:ingen)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e?|I)[\s\xa0]*Ko(?:n(?:ingen)?)?|1Kgs|(?:1e?|I)\.[\s\xa0]*Ko(?:n(?:ingen)?)?|Eerste[\s\xa0]*Ko(?:n(?:ingen)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Kron(?:ieken)?|(?:[\s\xa0]*K|Ch)r)|(?:2e|II)[\s\xa0]*Kron(?:ieken)?|(?:2e?|II)\.[\s\xa0]*Kron(?:ieken)?|Tweede[\s\xa0]*Kron(?:ieken)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Kron(?:ieken)?|(?:[\s\xa0]*K|Ch)r)|(?:1e|I)[\s\xa0]*Kron(?:ieken)?|(?:1e?|I)\.[\s\xa0]*Kron(?:ieken)?|Eerste[\s\xa0]*Kron(?:ieken)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ezra?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Neh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Neh(?:emia)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["GkEsth"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Est(?:er[\s\xa0]*\(Gr(?:ieks|\.)?\)|[\s\xa0]*gr)|GkEsth) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Esth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Est(?:h(?:er)?|er)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Job"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Job) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ps"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ps(?:alm(?:en)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrAzar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Gebed[\s\xa0]*van[\s\xa0]*Azarja|PrAzar) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Prov"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Spr(?:euken)?|Prov) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eccl"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Prediker|Eccl|Pr(?:ed)?|[KQ]oheleth?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["SgThree"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lied[\s\xa0]*van[\s\xa0]*de[\s\xa0]*drie[\s\xa0]*jongemannen|SgThree|Gezang[\s\xa0]*der[\s\xa0]*drie[\s\xa0]*mannen[\s\xa0]*in[\s\xa0]*het[\s\xa0]*vuur) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Song"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:H(?:ooglied|l)|Song|Hoogl|Canticum[\s\xa0]*canticorum) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jer"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:er(?:emia)?|r)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Eze(?:ch(?:i[e\xEB]l)?|k)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Dan"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Da(?:n(?:i[e\xEB]l)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hos(?:ea)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Joel"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:o[e\xEB])?l) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Amos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Am(?:os)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Obad"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ob(?:ad(?:ja)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jonah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jon(?:ah?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mic"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mi(?:c(?:ha|a)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Nah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Nah(?:um)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hab"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hab(?:akuk)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zeph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ze(?:f(?:anja)?|ph)|Sef(?:anja)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hag"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hag(?:g(?:a[i\xEF])?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zech"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Z(?:ach(?:aria)?|ech)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mal(?:eachi)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Matt"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:M(?:att(?:h[e\xE9]|e)[u\xFC]s|at(?:th?)?|t)|Evangelie[\s\xa0]*volgens[\s\xa0]*Matte[u\xFC]s) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mark"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mar[ck]us)|(?:Evangelie[\s\xa0]*volgens[\s\xa0]*Mar[ck]us|M(?:ar[ck]|[ckr])) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Luke"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lu[ck]as)|(?:Evangelie[\s\xa0]*volgens[\s\xa0]*Lu[ck]as|L(?:u(?:ke|c)|[ck]|uk)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1John)|(?:(?:1e?|I)\.[\s\xa0]*Joh(?:annes)?|(?:1e?|I)[\s\xa0]*Joh(?:annes)?|Eerste[\s\xa0]*Joh(?:annes)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2John)|(?:(?:2e?|II)\.[\s\xa0]*Joh(?:annes)?|(?:2e?|II)[\s\xa0]*Joh(?:annes)?|Tweede[\s\xa0]*Joh(?:annes)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3John)|(?:(?:3e?|III)\.[\s\xa0]*Joh(?:annes)?|(?:3e?|III)[\s\xa0]*Joh(?:annes)?|Derde[\s\xa0]*Joh(?:annes)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["<NAME>"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Evangelie[\s\xa0]*volgens[\s\xa0]*Johannes|Joh(?:annes|n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Acts"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:H(?:and(?:elingen(?:[\s\xa0]*(?:van[\s\xa0]*de|der)[\s\xa0]*apostelen)?)?|nd)|Acts) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rom"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Rom(?:einen(?:brief)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e?|II)[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))|2Cor|(?:2e?|II)\.[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))|Tweede[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e?|I)[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))|1Cor|(?:1e?|I)\.[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))|Eerste[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Gal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Gal(?:aten(?:brief)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:E(?:f(?:ez(?:i[e\xEB]rs)?)?|ph)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phil"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Fil(?:ip(?:penzen)?)?|Phil) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Col"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:[CK]ol(?:ossenzen)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e|II)[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)|2(?:[\s\xa0]*Th?ess(?:alonicenzen)?|(?:[\s\xa0]*Th?e|Thes)s)|(?:2e?|II)\.[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)|Tweede[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e|I)[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)|1(?:[\s\xa0]*Th?ess(?:alonicenzen)?|(?:[\s\xa0]*Th?e|Thes)s)|(?:1e?|I)\.[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)|Eerste[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e?|II)[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?|2Tim|(?:2e?|II)\.[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?|Tweede[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e?|I)[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?|1Tim|(?:1e?|I)\.[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?|Eerste[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Titus"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Tit(?:us)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phlm"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Fil(?:em(?:on)?|\xE9mon|m)|Phlm) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Heb"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Heb(?:r(?:ee[e\xEB]n)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jas"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ja(?:k(?:obus)?|s)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Pet(?:r(?:us)?)?|[\s\xa0]*Pe|Pet)|(?:2e|II)[\s\xa0]*Pet(?:r(?:us)?)?|(?:2e?|II)\.[\s\xa0]*Pet(?:r(?:us)?)?|Tweede[\s\xa0]*Pet(?:r(?:us)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Pet(?:r(?:us)?)?|[\s\xa0]*Pe|Pet)|(?:1e|I)[\s\xa0]*Pet(?:r(?:us)?)?|(?:1e?|I)\.[\s\xa0]*Pet(?:r(?:us)?)?|Eerste[\s\xa0]*Pet(?:r(?:us)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jude"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jud(?:as|e)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Tob"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Tob(?:i(?:as?|t)|\xEDas?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jdt"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:udith?|dt)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bar(?:uch)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sus"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sus(?:anna)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e?|II)[\s\xa0]*Mak(?:kabee[e\xEB]n)?|2Macc|(?:2e?|II)\.[\s\xa0]*Mak(?:kabee[e\xEB]n)?|Tweede[\s\xa0]*Mak(?:kabee[e\xEB]n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:3e?|III)[\s\xa0]*Mak(?:kabee[e\xEB]n)?|3Macc|(?:3e?|III)\.[\s\xa0]*Mak(?:kabee[e\xEB]n)?|Derde[\s\xa0]*Mak(?:kabee[e\xEB]n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["4Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:IV|4)[\s\xa0]*Mak(?:kabee[e\xEB]n)?|4Macc|(?:IV|4)\.[\s\xa0]*Mak(?:kabee[e\xEB]n)?|Vierde[\s\xa0]*Mak(?:kabee[e\xEB]n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e?|I)[\s\xa0]*Mak(?:kabee[e\xEB]n)?|1Macc|(?:1e?|I)\.[\s\xa0]*Mak(?:kabee[e\xEB]n)?|Eerste[\s\xa0]*Mak(?:kabee[e\xEB]n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek", "Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ez) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi ] # Short-circuit the look if we know we want all the books. return books if include_apocrypha is true and case_sensitive is "none" # Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9. out = [] for book in books continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true if case_sensitive is "books" book.regexp = new RegExp book.regexp.source, "g" out.push book out # Default to not using the Apocrypha bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
true
bcv_parser::regexps.space = "[\\s\\xa0]" bcv_parser::regexps.escaped_passage = /// (?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3` ( # Start inverted book/chapter (cb) (?: (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: \d+ (?: th | nd | st ) \s* ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter (?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* ) )? # End inverted book/chapter (cb) \x1f(\d+)(?:/\d+)?\x1f #book (?: /\d+\x1f #special Psalm chapters | [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014] | opschrift (?! [a-z] ) #could be followed by a number | en#{bcv_parser::regexps.space}+volgende#{bcv_parser::regexps.space}+verzen | zie#{bcv_parser::regexps.space}+ook | hoofdstukken | hoofdstuk | verzen | vers | vgl | en | vs | - | v | [a-e] (?! \w ) #a-e allows 1:1a | $ #or the end of the string )+ ) ///gi # These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff. bcv_parser::regexps.match_end_split = /// \d \W* opschrift | \d \W* en#{bcv_parser::regexps.space}+volgende#{bcv_parser::regexps.space}+verzen (?: [\s\xa0*]* \.)? | \d [\s\xa0*]* [a-e] (?! \w ) | \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis | [\d\x1f] ///gi bcv_parser::regexps.control = /[\x1e\x1f]/g bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]" bcv_parser::regexps.first = "(?:Eerste|1e|I|1)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.second = "(?:Tweede|2e|II|2)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.third = "(?:Derde|3e|III|3)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:en|vgl|zie#{bcv_parser::regexps.space}+ook)|-)" bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|-)" # Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself. bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) -> books = [ osis: ["Ps"] apocrypha: true extra: "2" regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit. Ps151 # Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own. )(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS. , osis: ["Gen"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:Genesis)|(?:(?:1e?|I)[\s\xa0]*Mozes|Beresjiet|Ge?n|(?:1e?|I)\.[\s\xa0]*Mozes|Eerste[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Exod"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:Exodus)|(?:(?:2e?|II)[\s\xa0]*Mozes|Sjemot|Exod|Ex|(?:2e?|II)\.[\s\xa0]*Mozes|Tweede[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bel"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bel(?:[\s\xa0]*en[\s\xa0]*de[\s\xa0]*draak)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lev"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:Leviticus)|(?:(?:3e?|III)[\s\xa0]*Mozes|[VW]ajikra|Le?v|(?:3e?|III)\.[\s\xa0]*Mozes|Derde[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Num"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:B[ae]midbar|Numb?eri|Num?|(?:IV|4)[\s\xa0]*Mozes|(?:IV|4)\.[\s\xa0]*Mozes|Vierde[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sir"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sirach)|(?:Wijsheid[\s\xa0]*van[\s\xa0]*(?:J(?:ozua[\s\xa0]*Ben|ezus)|Ben)[\s\xa0]*Sirach|Ecclesiasticus|Sir|Jezus[\s\xa0]*Sirach) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Wis"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Wijsheid[\s\xa0]*van[\s\xa0]*Salomo)|(?:Het[\s\xa0]*boek[\s\xa0]*der[\s\xa0]*wijsheid|Wi(?:jsheid|s)|De[\s\xa0]*wijsheid[\s\xa0]*van[\s\xa0]*Salomo) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lam"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Kl(?:aagl(?:iederen)?)?|Lam) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["EpJer"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Brief[\s\xa0]*van[\s\xa0]*Jeremia|EpJer) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Op(?:enb(?:aring(?:[\s\xa0]*van[\s\xa0]*Johannes|en)?)?)?|Ap[ck]|Rev|Apocalyps) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrMan"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Man(?:asse)?|PrMan) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Deut"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:D(?:e(?:ut(?:eronomium)?|wariem)|t)|(?:V(?:ijfde|\.)?|5\.?)[\s\xa0]*Mozes) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Josh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jo(?:z(?:ua)?|sh)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Judg"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:R(?:i(?:cht(?:eren?)?)?|e(?:chters|cht)?)|Judg) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ruth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:R(?:uth|t)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:[13]e|[13]|I(?:II)?)[\s\xa0]*E(?:sdras|zra)|1Esd|(?:[13]e|[13]|I(?:II)?)\.[\s\xa0]*E(?:sdras|zra)|Derde[\s\xa0]*E(?:sdras|zra)|Eerste[\s\xa0]*E(?:sdras|zra)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:I[IV]|4|2e?)[\s\xa0]*E(?:sdras|zra)|2Esd|(?:I[IV]|4|2e?)\.[\s\xa0]*E(?:sdras|zra)|Vierde[\s\xa0]*E(?:sdras|zra)|Tweede[\s\xa0]*E(?:sdras|zra)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Isa"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:es(?:aja)?|s)|Isa) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Sam(?:u[e\xEB]l)?|Samuel[\s\xa0]*II|2Sam|2[\s\xa0]*S|(?:2e|II)[\s\xa0]*Sam(?:u[e\xEB]l)?|(?:2e?|II)\.[\s\xa0]*Sam(?:u[e\xEB]l)?|Tweede[\s\xa0]*Sam(?:u[e\xEB]l)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Sam(?:u[e\xEB]l)?|Samuel[\s\xa0]*I|1Sam|1[\s\xa0]*S|(?:1e|I)[\s\xa0]*Sam(?:u[e\xEB]l)?|(?:1e?|I)\.[\s\xa0]*Sam(?:u[e\xEB]l)?|Eerste[\s\xa0]*Sam(?:u[e\xEB]l)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e?|II)[\s\xa0]*Ko(?:n(?:ingen)?)?|2Kgs|(?:2e?|II)\.[\s\xa0]*Ko(?:n(?:ingen)?)?|Tweede[\s\xa0]*Ko(?:n(?:ingen)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e?|I)[\s\xa0]*Ko(?:n(?:ingen)?)?|1Kgs|(?:1e?|I)\.[\s\xa0]*Ko(?:n(?:ingen)?)?|Eerste[\s\xa0]*Ko(?:n(?:ingen)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Kron(?:ieken)?|(?:[\s\xa0]*K|Ch)r)|(?:2e|II)[\s\xa0]*Kron(?:ieken)?|(?:2e?|II)\.[\s\xa0]*Kron(?:ieken)?|Tweede[\s\xa0]*Kron(?:ieken)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Kron(?:ieken)?|(?:[\s\xa0]*K|Ch)r)|(?:1e|I)[\s\xa0]*Kron(?:ieken)?|(?:1e?|I)\.[\s\xa0]*Kron(?:ieken)?|Eerste[\s\xa0]*Kron(?:ieken)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ezra?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Neh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Neh(?:emia)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["GkEsth"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Est(?:er[\s\xa0]*\(Gr(?:ieks|\.)?\)|[\s\xa0]*gr)|GkEsth) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Esth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Est(?:h(?:er)?|er)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Job"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Job) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ps"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ps(?:alm(?:en)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrAzar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Gebed[\s\xa0]*van[\s\xa0]*Azarja|PrAzar) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Prov"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Spr(?:euken)?|Prov) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eccl"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Prediker|Eccl|Pr(?:ed)?|[KQ]oheleth?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["SgThree"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lied[\s\xa0]*van[\s\xa0]*de[\s\xa0]*drie[\s\xa0]*jongemannen|SgThree|Gezang[\s\xa0]*der[\s\xa0]*drie[\s\xa0]*mannen[\s\xa0]*in[\s\xa0]*het[\s\xa0]*vuur) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Song"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:H(?:ooglied|l)|Song|Hoogl|Canticum[\s\xa0]*canticorum) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jer"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:er(?:emia)?|r)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Eze(?:ch(?:i[e\xEB]l)?|k)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Dan"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Da(?:n(?:i[e\xEB]l)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hos(?:ea)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Joel"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:o[e\xEB])?l) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Amos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Am(?:os)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Obad"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ob(?:ad(?:ja)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jonah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jon(?:ah?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mic"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mi(?:c(?:ha|a)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Nah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Nah(?:um)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hab"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hab(?:akuk)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zeph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ze(?:f(?:anja)?|ph)|Sef(?:anja)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hag"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Hag(?:g(?:a[i\xEF])?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zech"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Z(?:ach(?:aria)?|ech)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mal(?:eachi)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Matt"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:M(?:att(?:h[e\xE9]|e)[u\xFC]s|at(?:th?)?|t)|Evangelie[\s\xa0]*volgens[\s\xa0]*Matte[u\xFC]s) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mark"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mar[ck]us)|(?:Evangelie[\s\xa0]*volgens[\s\xa0]*Mar[ck]us|M(?:ar[ck]|[ckr])) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Luke"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lu[ck]as)|(?:Evangelie[\s\xa0]*volgens[\s\xa0]*Lu[ck]as|L(?:u(?:ke|c)|[ck]|uk)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1John)|(?:(?:1e?|I)\.[\s\xa0]*Joh(?:annes)?|(?:1e?|I)[\s\xa0]*Joh(?:annes)?|Eerste[\s\xa0]*Joh(?:annes)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2John)|(?:(?:2e?|II)\.[\s\xa0]*Joh(?:annes)?|(?:2e?|II)[\s\xa0]*Joh(?:annes)?|Tweede[\s\xa0]*Joh(?:annes)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3John)|(?:(?:3e?|III)\.[\s\xa0]*Joh(?:annes)?|(?:3e?|III)[\s\xa0]*Joh(?:annes)?|Derde[\s\xa0]*Joh(?:annes)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PI:NAME:<NAME>END_PI"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Evangelie[\s\xa0]*volgens[\s\xa0]*Johannes|Joh(?:annes|n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Acts"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:H(?:and(?:elingen(?:[\s\xa0]*(?:van[\s\xa0]*de|der)[\s\xa0]*apostelen)?)?|nd)|Acts) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rom"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Rom(?:einen(?:brief)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e?|II)[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))|2Cor|(?:2e?|II)\.[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))|Tweede[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e?|I)[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))|1Cor|(?:1e?|I)\.[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))|Eerste[\s\xa0]*(?:Kor(?:int(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))?|Corint(?:h(?:i[e\xEB]rs?|e)|i[e\xEB]rs?))) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Gal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Gal(?:aten(?:brief)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:E(?:f(?:ez(?:i[e\xEB]rs)?)?|ph)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phil"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Fil(?:ip(?:penzen)?)?|Phil) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Col"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:[CK]ol(?:ossenzen)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e|II)[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)|2(?:[\s\xa0]*Th?ess(?:alonicenzen)?|(?:[\s\xa0]*Th?e|Thes)s)|(?:2e?|II)\.[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)|Tweede[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e|I)[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)|1(?:[\s\xa0]*Th?ess(?:alonicenzen)?|(?:[\s\xa0]*Th?e|Thes)s)|(?:1e?|I)\.[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)|Eerste[\s\xa0]*T(?:es(?:s(?:alonicenzen)?)?|hess(?:alonicenzen)?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e?|II)[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?|2Tim|(?:2e?|II)\.[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?|Tweede[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e?|I)[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?|1Tim|(?:1e?|I)\.[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?|Eerste[\s\xa0]*Tim(?:ot(?:he[u\xFC]|e[u\xFC])s)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Titus"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Tit(?:us)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phlm"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Fil(?:em(?:on)?|\xE9mon|m)|Phlm) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Heb"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Heb(?:r(?:ee[e\xEB]n)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jas"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ja(?:k(?:obus)?|s)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Pet(?:r(?:us)?)?|[\s\xa0]*Pe|Pet)|(?:2e|II)[\s\xa0]*Pet(?:r(?:us)?)?|(?:2e?|II)\.[\s\xa0]*Pet(?:r(?:us)?)?|Tweede[\s\xa0]*Pet(?:r(?:us)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Pet(?:r(?:us)?)?|[\s\xa0]*Pe|Pet)|(?:1e|I)[\s\xa0]*Pet(?:r(?:us)?)?|(?:1e?|I)\.[\s\xa0]*Pet(?:r(?:us)?)?|Eerste[\s\xa0]*Pet(?:r(?:us)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jude"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Jud(?:as|e)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Tob"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Tob(?:i(?:as?|t)|\xEDas?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jdt"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:J(?:udith?|dt)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bar(?:uch)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sus"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sus(?:anna)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:2e?|II)[\s\xa0]*Mak(?:kabee[e\xEB]n)?|2Macc|(?:2e?|II)\.[\s\xa0]*Mak(?:kabee[e\xEB]n)?|Tweede[\s\xa0]*Mak(?:kabee[e\xEB]n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:3e?|III)[\s\xa0]*Mak(?:kabee[e\xEB]n)?|3Macc|(?:3e?|III)\.[\s\xa0]*Mak(?:kabee[e\xEB]n)?|Derde[\s\xa0]*Mak(?:kabee[e\xEB]n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["4Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:IV|4)[\s\xa0]*Mak(?:kabee[e\xEB]n)?|4Macc|(?:IV|4)\.[\s\xa0]*Mak(?:kabee[e\xEB]n)?|Vierde[\s\xa0]*Mak(?:kabee[e\xEB]n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:(?:1e?|I)[\s\xa0]*Mak(?:kabee[e\xEB]n)?|1Macc|(?:1e?|I)\.[\s\xa0]*Mak(?:kabee[e\xEB]n)?|Eerste[\s\xa0]*Mak(?:kabee[e\xEB]n)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek", "Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ez) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi ] # Short-circuit the look if we know we want all the books. return books if include_apocrypha is true and case_sensitive is "none" # Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9. out = [] for book in books continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true if case_sensitive is "books" book.regexp = new RegExp book.regexp.source, "g" out.push book out # Default to not using the Apocrypha bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
[ { "context": "lement: 'process_chart'\n data: data\n xkey: 'created_at'\n ykeys: [$('#process_chart').attr('label')", "end": 140, "score": 0.7213798761367798, "start": 133, "tag": "NAME", "value": "created" }, { "context": " 'process_chart'\n data: data\n xkey: 'create...
app/assets/javascripts/stat_chart.js.coffee
lukecampbell/process-monitor-rails
0
# For rendering morris # @initializeChart = (data) -> @morris = Morris.Line element: 'process_chart' data: data xkey: 'created_at' ykeys: [$('#process_chart').attr('label')] labels: ['Value'] @updateChart = (data) -> morris.setData data
86385
# For rendering morris # @initializeChart = (data) -> @morris = Morris.Line element: 'process_chart' data: data xkey: '<NAME>_at' ykeys: [$('#process_chart').attr('label')] labels: ['Value'] @updateChart = (data) -> morris.setData data
true
# For rendering morris # @initializeChart = (data) -> @morris = Morris.Line element: 'process_chart' data: data xkey: 'PI:NAME:<NAME>END_PI_at' ykeys: [$('#process_chart').attr('label')] labels: ['Value'] @updateChart = (data) -> morris.setData data
[ { "context": "# @author mr.doob / http://mrdoob.com/\n# @author aladjev.andre", "end": 12, "score": 0.786019504070282, "start": 10, "tag": "USERNAME", "value": "mr" }, { "context": "# @author mr.doob / http://mrdoob.com/\n# @author aladjev.andrew@gma", "end": 17, "score": 0.7...
source/javascripts/new_src/core/uv.coffee
andrew-aladev/three.js
0
# @author mr.doob / http://mrdoob.com/ # @author aladjev.andrew@gmail.com class UV constructor: (u, v) -> @u = u or 0 @v = v or 0 set: (u, v) -> @u = u @v = v this copy: (uv) -> @u = uv.u @v = uv.v this lerpSelf: (uv, alpha) -> @u += (uv.u - @u) * alpha @v += (uv.v - @v) * alpha this clone: -> new UV @u, @v namespace "THREE", (exports) -> exports.UV = UV
216165
# @author mr.<NAME> / http://mrdoob.com/ # @author <EMAIL> class UV constructor: (u, v) -> @u = u or 0 @v = v or 0 set: (u, v) -> @u = u @v = v this copy: (uv) -> @u = uv.u @v = uv.v this lerpSelf: (uv, alpha) -> @u += (uv.u - @u) * alpha @v += (uv.v - @v) * alpha this clone: -> new UV @u, @v namespace "THREE", (exports) -> exports.UV = UV
true
# @author mr.PI:NAME:<NAME>END_PI / http://mrdoob.com/ # @author PI:EMAIL:<EMAIL>END_PI class UV constructor: (u, v) -> @u = u or 0 @v = v or 0 set: (u, v) -> @u = u @v = v this copy: (uv) -> @u = uv.u @v = uv.v this lerpSelf: (uv, alpha) -> @u += (uv.u - @u) * alpha @v += (uv.v - @v) * alpha this clone: -> new UV @u, @v namespace "THREE", (exports) -> exports.UV = UV
[ { "context": "obot-name>/nowplaying?user=<user>\n#\n# Authors:\n# Kevin L <kevin@stealsyour.pw>\n\nsongs = [\n \"Shakira - Hip", "end": 227, "score": 0.9998517632484436, "start": 220, "tag": "NAME", "value": "Kevin L" }, { "context": "/nowplaying?user=<user>\n#\n# Authors:\n# Ke...
src/usernowplaying.coffee
thatarchguy/hubot-usernowplaying
0
# See what people are listening to in chat # # Configuration: # None # # Commands: # hubot nowplaying "user" - Show what they are listening to # # URLS: # POST /<robot-name>/nowplaying?user=<user> # # Authors: # Kevin L <kevin@stealsyour.pw> songs = [ "Shakira - Hips Don't Lie", "R. Kelly - Trapped in the Closet", "Spice Girls - Wannabe", "Backstreet Boys - I Want It That Way" ] module.exports = (robot) -> robot.router.post "/hubot/nowplaying", (req, res) -> user = req.query.user unless user? res.status(400).send("Bad Request").end() return console.log req.query.user console.log req.body data = req.body robot.brain.set "#{user}_nowplaying", data.song if (data.url?) robot.brain.set "#{user}_nowplaying_url", data.url song = robot.brain.get("#{user}_nowplaying") res.status(202).send("#{song}").end() return robot.respond /nowplaying (.*)/, (msg) -> user = msg.match[1].trim() song = robot.brain.get("#{user}_nowplaying") or 0 url = robot.brain.get("#{user}_nowplaying_url") or 0 if song == 0 song = msg.random songs msg.send song if url != 0 msg.send url
74104
# See what people are listening to in chat # # Configuration: # None # # Commands: # hubot nowplaying "user" - Show what they are listening to # # URLS: # POST /<robot-name>/nowplaying?user=<user> # # Authors: # <NAME> <<EMAIL>> songs = [ "Shakira - Hips Don't Lie", "<NAME> - Trapped in the Closet", "Spice Girls - Wannabe", "Backstreet Boys - I Want It That Way" ] module.exports = (robot) -> robot.router.post "/hubot/nowplaying", (req, res) -> user = req.query.user unless user? res.status(400).send("Bad Request").end() return console.log req.query.user console.log req.body data = req.body robot.brain.set "#{user}_nowplaying", data.song if (data.url?) robot.brain.set "#{user}_nowplaying_url", data.url song = robot.brain.get("#{user}_nowplaying") res.status(202).send("#{song}").end() return robot.respond /nowplaying (.*)/, (msg) -> user = msg.match[1].trim() song = robot.brain.get("#{user}_nowplaying") or 0 url = robot.brain.get("#{user}_nowplaying_url") or 0 if song == 0 song = msg.random songs msg.send song if url != 0 msg.send url
true
# See what people are listening to in chat # # Configuration: # None # # Commands: # hubot nowplaying "user" - Show what they are listening to # # URLS: # POST /<robot-name>/nowplaying?user=<user> # # Authors: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> songs = [ "Shakira - Hips Don't Lie", "PI:NAME:<NAME>END_PI - Trapped in the Closet", "Spice Girls - Wannabe", "Backstreet Boys - I Want It That Way" ] module.exports = (robot) -> robot.router.post "/hubot/nowplaying", (req, res) -> user = req.query.user unless user? res.status(400).send("Bad Request").end() return console.log req.query.user console.log req.body data = req.body robot.brain.set "#{user}_nowplaying", data.song if (data.url?) robot.brain.set "#{user}_nowplaying_url", data.url song = robot.brain.get("#{user}_nowplaying") res.status(202).send("#{song}").end() return robot.respond /nowplaying (.*)/, (msg) -> user = msg.match[1].trim() song = robot.brain.get("#{user}_nowplaying") or 0 url = robot.brain.get("#{user}_nowplaying_url") or 0 if song == 0 song = msg.random songs msg.send song if url != 0 msg.send url
[ { "context": "\n listing = new Listing( \n uid: 4\n name: \"Gordon Weeks\"\n title: req.body.title\n description: req.b", "end": 743, "score": 0.9996577501296997, "start": 731, "tag": "NAME", "value": "Gordon Weeks" } ]
controllers/mobile.coffee
gcweeks/SnapSale-API
1
_ = require("underscore") async = require("async") Area = require("../models/Area") Comment = require("../models/Comment") Listing = require("../models/Listing") Mobile = require("../models/Message") User = require("../models/User") ### POST / Reset ### exports.postReset = (req, res) -> Listing.remove {}, (err) -> if err res.json return: 0 res.json return: 1 res.json return: 0 ### GET / Areas ### exports.getAreas = (req, res) -> arr = {"UCLA"} res.json areas: arr ### GET / Listings ### exports.getListings = (req, res) -> Listing.find {}, (err, listings) -> res.json listings: listings ### POST / Listing ### exports.postListing = (req, res) -> listing = new Listing( uid: 4 name: "Gordon Weeks" title: req.body.title description: req.body.description picture: "" messages: [] bought: false ) listing.save (err) -> if err res.json return: 0 res.json return: 1 ### POST / Buy ### exports.postBuy = (req, res) -> Listing.findById req.body.id, (err, listing) -> listing.bought = true listing.save (err) -> if err res.json return: 0 res.json return: 1 ### POST / Relist ### exports.postRelist = (req, res) -> Listing.findById req.body.id, (err, listing) -> return next(err) if err listing.bought = false listing.save (err) -> if err res.json return: 0 res.json return: 1 ### POST / Message ### exports.postMessage = (req, res) -> Listing.findById req.body.id, (err, listing) -> return next(err) if err message = new Message( text: req.body.text, user: req.body.user, # Twitter ID timestamp: new Date() ) message.save (err) -> if err res.json return: 0 messages = listing.messages messages.push message listing.set messages: req.body.one listing.save (err) -> if err res.json return: 0 res.json return: 1 ### POST / Comment ### exports.postComment = (req, res) -> # listing = find Listing # comment = new Comment( # one: req.body.one # two: req.body.two # ) # comment.save (err) -> # if err # res.json return: 0 # res.json return: 1 # listing.set # one: req.body.one # two: req.body.two # listing.save (err) -> # if err # res.json return: 0 # res.json return: 1
132310
_ = require("underscore") async = require("async") Area = require("../models/Area") Comment = require("../models/Comment") Listing = require("../models/Listing") Mobile = require("../models/Message") User = require("../models/User") ### POST / Reset ### exports.postReset = (req, res) -> Listing.remove {}, (err) -> if err res.json return: 0 res.json return: 1 res.json return: 0 ### GET / Areas ### exports.getAreas = (req, res) -> arr = {"UCLA"} res.json areas: arr ### GET / Listings ### exports.getListings = (req, res) -> Listing.find {}, (err, listings) -> res.json listings: listings ### POST / Listing ### exports.postListing = (req, res) -> listing = new Listing( uid: 4 name: "<NAME>" title: req.body.title description: req.body.description picture: "" messages: [] bought: false ) listing.save (err) -> if err res.json return: 0 res.json return: 1 ### POST / Buy ### exports.postBuy = (req, res) -> Listing.findById req.body.id, (err, listing) -> listing.bought = true listing.save (err) -> if err res.json return: 0 res.json return: 1 ### POST / Relist ### exports.postRelist = (req, res) -> Listing.findById req.body.id, (err, listing) -> return next(err) if err listing.bought = false listing.save (err) -> if err res.json return: 0 res.json return: 1 ### POST / Message ### exports.postMessage = (req, res) -> Listing.findById req.body.id, (err, listing) -> return next(err) if err message = new Message( text: req.body.text, user: req.body.user, # Twitter ID timestamp: new Date() ) message.save (err) -> if err res.json return: 0 messages = listing.messages messages.push message listing.set messages: req.body.one listing.save (err) -> if err res.json return: 0 res.json return: 1 ### POST / Comment ### exports.postComment = (req, res) -> # listing = find Listing # comment = new Comment( # one: req.body.one # two: req.body.two # ) # comment.save (err) -> # if err # res.json return: 0 # res.json return: 1 # listing.set # one: req.body.one # two: req.body.two # listing.save (err) -> # if err # res.json return: 0 # res.json return: 1
true
_ = require("underscore") async = require("async") Area = require("../models/Area") Comment = require("../models/Comment") Listing = require("../models/Listing") Mobile = require("../models/Message") User = require("../models/User") ### POST / Reset ### exports.postReset = (req, res) -> Listing.remove {}, (err) -> if err res.json return: 0 res.json return: 1 res.json return: 0 ### GET / Areas ### exports.getAreas = (req, res) -> arr = {"UCLA"} res.json areas: arr ### GET / Listings ### exports.getListings = (req, res) -> Listing.find {}, (err, listings) -> res.json listings: listings ### POST / Listing ### exports.postListing = (req, res) -> listing = new Listing( uid: 4 name: "PI:NAME:<NAME>END_PI" title: req.body.title description: req.body.description picture: "" messages: [] bought: false ) listing.save (err) -> if err res.json return: 0 res.json return: 1 ### POST / Buy ### exports.postBuy = (req, res) -> Listing.findById req.body.id, (err, listing) -> listing.bought = true listing.save (err) -> if err res.json return: 0 res.json return: 1 ### POST / Relist ### exports.postRelist = (req, res) -> Listing.findById req.body.id, (err, listing) -> return next(err) if err listing.bought = false listing.save (err) -> if err res.json return: 0 res.json return: 1 ### POST / Message ### exports.postMessage = (req, res) -> Listing.findById req.body.id, (err, listing) -> return next(err) if err message = new Message( text: req.body.text, user: req.body.user, # Twitter ID timestamp: new Date() ) message.save (err) -> if err res.json return: 0 messages = listing.messages messages.push message listing.set messages: req.body.one listing.save (err) -> if err res.json return: 0 res.json return: 1 ### POST / Comment ### exports.postComment = (req, res) -> # listing = find Listing # comment = new Comment( # one: req.body.one # two: req.body.two # ) # comment.save (err) -> # if err # res.json return: 0 # res.json return: 1 # listing.set # one: req.body.one # two: req.body.two # listing.save (err) -> # if err # res.json return: 0 # res.json return: 1
[ { "context": "on.ejj.misc = winston.loggers.get('misc')\n\n# TODO(Alex.Hokanson): send an email when winston catches errors\nwinst", "end": 1444, "score": 0.9998739361763, "start": 1431, "tag": "NAME", "value": "Alex.Hokanson" } ]
src/logger.coffee
ingshtrom/easy-jenkins-jobs
1
winston = require 'winston' Loggly = require('winston-loggly').Loggly Logentries = require('winston-logentries') config = require './config' # remove the default Console logger winston.remove winston.transports.Console # add our custom transports for all loggers consoleConfig = level: config.logLevel handleExceptions: true colorize: true timestamp: true fileConfig = filename: config.defaultLogFile level: config.logLevel maxsize: 102400 handleExceptions: true winston.loggers.options.transports = [ new (winston.transports.Console) (consoleConfig), new (winston.transports.File) (fileConfig) ] # config loggly if told to do so if config.useLoggly logglyConfig = level: config.logLevel subdomain: config.logglySubdomain inputToken: config.logglyToken json: true winston.loggers.options.transports.push(new (Loggly) (logglyConfig)) # config logentries if told to do so if config.useLogentries logentriesConfig = level: config.logLevel token: config.logentriesToken winston.loggers.options.transports.push(new (winston.transports.Logentries) (logentriesConfig)) # define different loggers... aka categories # by providing this custom namespace, we have # easy accessors to all of our custom loggers! winston.ejj = {} winston.loggers.add('api') winston.ejj.api = winston.loggers.get('api') winston.loggers.add('misc') winston.ejj.misc = winston.loggers.get('misc') # TODO(Alex.Hokanson): send an email when winston catches errors winston.exitOnError = false module.exports = winston
178573
winston = require 'winston' Loggly = require('winston-loggly').Loggly Logentries = require('winston-logentries') config = require './config' # remove the default Console logger winston.remove winston.transports.Console # add our custom transports for all loggers consoleConfig = level: config.logLevel handleExceptions: true colorize: true timestamp: true fileConfig = filename: config.defaultLogFile level: config.logLevel maxsize: 102400 handleExceptions: true winston.loggers.options.transports = [ new (winston.transports.Console) (consoleConfig), new (winston.transports.File) (fileConfig) ] # config loggly if told to do so if config.useLoggly logglyConfig = level: config.logLevel subdomain: config.logglySubdomain inputToken: config.logglyToken json: true winston.loggers.options.transports.push(new (Loggly) (logglyConfig)) # config logentries if told to do so if config.useLogentries logentriesConfig = level: config.logLevel token: config.logentriesToken winston.loggers.options.transports.push(new (winston.transports.Logentries) (logentriesConfig)) # define different loggers... aka categories # by providing this custom namespace, we have # easy accessors to all of our custom loggers! winston.ejj = {} winston.loggers.add('api') winston.ejj.api = winston.loggers.get('api') winston.loggers.add('misc') winston.ejj.misc = winston.loggers.get('misc') # TODO(<NAME>): send an email when winston catches errors winston.exitOnError = false module.exports = winston
true
winston = require 'winston' Loggly = require('winston-loggly').Loggly Logentries = require('winston-logentries') config = require './config' # remove the default Console logger winston.remove winston.transports.Console # add our custom transports for all loggers consoleConfig = level: config.logLevel handleExceptions: true colorize: true timestamp: true fileConfig = filename: config.defaultLogFile level: config.logLevel maxsize: 102400 handleExceptions: true winston.loggers.options.transports = [ new (winston.transports.Console) (consoleConfig), new (winston.transports.File) (fileConfig) ] # config loggly if told to do so if config.useLoggly logglyConfig = level: config.logLevel subdomain: config.logglySubdomain inputToken: config.logglyToken json: true winston.loggers.options.transports.push(new (Loggly) (logglyConfig)) # config logentries if told to do so if config.useLogentries logentriesConfig = level: config.logLevel token: config.logentriesToken winston.loggers.options.transports.push(new (winston.transports.Logentries) (logentriesConfig)) # define different loggers... aka categories # by providing this custom namespace, we have # easy accessors to all of our custom loggers! winston.ejj = {} winston.loggers.add('api') winston.ejj.api = winston.loggers.get('api') winston.loggers.add('misc') winston.ejj.misc = winston.loggers.get('misc') # TODO(PI:NAME:<NAME>END_PI): send an email when winston catches errors winston.exitOnError = false module.exports = winston
[ { "context": "e: Account Login (assets)\nProject: Waaave\nAuthors: Julien Le Coupanec, Valerian Saliou\nCopyright: 2014, Waaave\n###\n\n__ ", "end": 78, "score": 0.9998679757118225, "start": 60, "tag": "NAME", "value": "Julien Le Coupanec" }, { "context": "sets)\nProject: Waaave\nAut...
static/src/assets/account/javascripts/account_login.coffee
valeriansaliou/waaave-web
1
### Bundle: Account Login (assets) Project: Waaave Authors: Julien Le Coupanec, Valerian Saliou Copyright: 2014, Waaave ### __ = window class AccountLogin init: -> try # Selectors @_emblem_bounce_sel = $ '.emblem-img.ef_bounce' @_input_email = $ '.credentials .email' @_avatar = $ '.avatar-header .picture' # Values @_host_avatar = $('html').attr 'data-url-avatar' catch error Console.error 'AccountLogin.init', error bounce_info_emblem: -> try @_emblem_bounce_sel.effect( 'bounce', times: 2, 350 ) catch error Console.error 'AccountLogin.bounce_info_emblem', error avatar_checking: -> try self = @ email = @_input_email.val() @_avatar_email_checking email @_input_email.keyup -> self._avatar_email_checking $(this).val() catch error Console.error 'AccountLogin.avatar_checking', error _avatar_email_checking: (email) -> status = false try if @_validate_email(email) @_avatar.attr( 'src', @_get_avatar email, 'normal' ) status = true catch error Console.error 'AccountLogin._avatar_email_checking', error finally return status _validate_email: (email) -> try re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{1,}))$/ return re.test email catch error Console.error 'AccountLogin._validate_email', error _get_avatar: (email, size) -> try url_base = "#{@_host_avatar}#{email}" url_size = (if size then ('/' + size + '/') else '') return "#{url_base}#{url_size}" catch error Console.error 'AccountLogin._get_avatar', error @AccountLogin = new AccountLogin $(document).ready -> __.AccountLogin.init() __.AccountLogin.bounce_info_emblem() __.AccountLogin.avatar_checking() LayoutRegistry.register_bundle 'AccountLogin'
12292
### Bundle: Account Login (assets) Project: Waaave Authors: <NAME>, <NAME> Copyright: 2014, Waaave ### __ = window class AccountLogin init: -> try # Selectors @_emblem_bounce_sel = $ '.emblem-img.ef_bounce' @_input_email = $ '.credentials .email' @_avatar = $ '.avatar-header .picture' # Values @_host_avatar = $('html').attr 'data-url-avatar' catch error Console.error 'AccountLogin.init', error bounce_info_emblem: -> try @_emblem_bounce_sel.effect( 'bounce', times: 2, 350 ) catch error Console.error 'AccountLogin.bounce_info_emblem', error avatar_checking: -> try self = @ email = @_input_email.val() @_avatar_email_checking email @_input_email.keyup -> self._avatar_email_checking $(this).val() catch error Console.error 'AccountLogin.avatar_checking', error _avatar_email_checking: (email) -> status = false try if @_validate_email(email) @_avatar.attr( 'src', @_get_avatar email, 'normal' ) status = true catch error Console.error 'AccountLogin._avatar_email_checking', error finally return status _validate_email: (email) -> try re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{1,}))$/ return re.test email catch error Console.error 'AccountLogin._validate_email', error _get_avatar: (email, size) -> try url_base = "#{@_host_avatar}#{email}" url_size = (if size then ('/' + size + '/') else '') return "#{url_base}#{url_size}" catch error Console.error 'AccountLogin._get_avatar', error @AccountLogin = new AccountLogin $(document).ready -> __.AccountLogin.init() __.AccountLogin.bounce_info_emblem() __.AccountLogin.avatar_checking() LayoutRegistry.register_bundle 'AccountLogin'
true
### Bundle: Account Login (assets) Project: Waaave Authors: PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI Copyright: 2014, Waaave ### __ = window class AccountLogin init: -> try # Selectors @_emblem_bounce_sel = $ '.emblem-img.ef_bounce' @_input_email = $ '.credentials .email' @_avatar = $ '.avatar-header .picture' # Values @_host_avatar = $('html').attr 'data-url-avatar' catch error Console.error 'AccountLogin.init', error bounce_info_emblem: -> try @_emblem_bounce_sel.effect( 'bounce', times: 2, 350 ) catch error Console.error 'AccountLogin.bounce_info_emblem', error avatar_checking: -> try self = @ email = @_input_email.val() @_avatar_email_checking email @_input_email.keyup -> self._avatar_email_checking $(this).val() catch error Console.error 'AccountLogin.avatar_checking', error _avatar_email_checking: (email) -> status = false try if @_validate_email(email) @_avatar.attr( 'src', @_get_avatar email, 'normal' ) status = true catch error Console.error 'AccountLogin._avatar_email_checking', error finally return status _validate_email: (email) -> try re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{1,}))$/ return re.test email catch error Console.error 'AccountLogin._validate_email', error _get_avatar: (email, size) -> try url_base = "#{@_host_avatar}#{email}" url_size = (if size then ('/' + size + '/') else '') return "#{url_base}#{url_size}" catch error Console.error 'AccountLogin._get_avatar', error @AccountLogin = new AccountLogin $(document).ready -> __.AccountLogin.init() __.AccountLogin.bounce_info_emblem() __.AccountLogin.avatar_checking() LayoutRegistry.register_bundle 'AccountLogin'
[ { "context": "`import Ember from 'ember'`\n\nEllen =\n name: \"Ellen Degeneres\"\n style: \"Observation", "end": 34, "score": 0.9793948531150818, "start": 29, "tag": "NAME", "value": "Ellen" }, { "context": "`import Ember from 'ember'`\n\nEllen =\n name: \"Ellen Degeneres\"\n sty...
tests/dummy/app/routes/cards.coffee
simwms/simwms-assets
0
`import Ember from 'ember'` Ellen = name: "Ellen Degeneres" style: "Observational nostalgic" image: "http://i.imgur.com/yEpekDy.jpg" Jerry = name: "Jerry Seinfeld" style: "Pure observational" image: "http://i.imgur.com/yEpekDy.jpg" Louis = name: "Louis CK" style: "Lifestyle stream-of-consciousness" image: "http://i.imgur.com/yEpekDy.jpg" Ray = name: "Ray Romano" style: "Family cool-dad" image: "http://i.imgur.com/yEpekDy.jpg" CardsController = Ember.Route.extend model: -> Ember.A [Ellen, Jerry, Louis, Ray] `export default CardsController`
139187
`import Ember from 'ember'` <NAME> = name: "<NAME>" style: "Observational nostalgic" image: "http://i.imgur.com/yEpekDy.jpg" <NAME> = name: "<NAME>" style: "Pure observational" image: "http://i.imgur.com/yEpekDy.jpg" <NAME>ouis = name: "<NAME>" style: "Lifestyle stream-of-consciousness" image: "http://i.imgur.com/yEpekDy.jpg" Ray = name: "<NAME>" style: "Family cool-dad" image: "http://i.imgur.com/yEpekDy.jpg" CardsController = Ember.Route.extend model: -> Ember.A [Ellen, Jerry, Louis, Ray] `export default CardsController`
true
`import Ember from 'ember'` PI:NAME:<NAME>END_PI = name: "PI:NAME:<NAME>END_PI" style: "Observational nostalgic" image: "http://i.imgur.com/yEpekDy.jpg" PI:NAME:<NAME>END_PI = name: "PI:NAME:<NAME>END_PI" style: "Pure observational" image: "http://i.imgur.com/yEpekDy.jpg" PI:NAME:<NAME>END_PIouis = name: "PI:NAME:<NAME>END_PI" style: "Lifestyle stream-of-consciousness" image: "http://i.imgur.com/yEpekDy.jpg" Ray = name: "PI:NAME:<NAME>END_PI" style: "Family cool-dad" image: "http://i.imgur.com/yEpekDy.jpg" CardsController = Ember.Route.extend model: -> Ember.A [Ellen, Jerry, Louis, Ray] `export default CardsController`
[ { "context": "c805fcbf-3acf-4302-a97e-d82f9d7c897f\"\n email: \"jim.smith@gmail.com\"\n givenName: \"Jim\"\n familyName: \"Smith\"\n ", "end": 2227, "score": 0.9999229907989502, "start": 2208, "tag": "EMAIL", "value": "jim.smith@gmail.com" }, { "context": "\n email: \"j...
coffeescript/feedlyconsole.coffee
dougbeal/feedlyconsole
0
`var Josh = Josh || {}` if console _console = console _console.log "[feedlyconsole] using console." else if window.console _console = windows.console _console.log "[feedlyconsole] using window.console." else _console = log: () -> _console.log "[feedlyconsole] haha." types = ['debug', 'warn', 'error', 'dir'] for type in types unless _console[type] _console[type] = _console.log _josh_disable_console = log: () -> debug: () -> Josh.Debug = true Josh.config = history: new Josh.History() console: _console killring: new Josh.KillRing() readline: null shell: null pathhandler: null Josh.config.readline = new Josh.ReadLine(Josh.config) Josh.config.shell = new Josh.Shell(Josh.config) # `Josh.PathHandler` is attached to `Josh.Shell` to provide basic file # system navigation. Josh.config.pathhandler = new Josh.PathHandler(Josh.config.shell, console: Josh.config.console ) demo_data = tags: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/global.saved" , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/tech" label: "tech" , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/inspiration" label: "inspiration" ] subscriptions: [ id: "feed/http://feeds.feedburner.com/design-milk" title: "Design Milk" categories: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/design" label: "design" , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/global.must" label: "must reads" ] sortid: "26152F8F" updated: 1367539068016 website: "http://design-milk.com" , id: "feed/http://5secondrule.typepad.com/my_weblog/atom.xml" title: "5 second rule" categories: [] sortid: "26152F8F" updated: 1367539068016 website: "http://5secondrule.typepad.com/my_weblog/" , id: "feed/http://feed.500px.com/500px-editors" title: "500px: Editors' Choice" categories: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/photography" label: "photography" ] sortid: "26152F8F" updated: 1367539068016 website: "http://500px.com/editors" ] profile: id: "c805fcbf-3acf-4302-a97e-d82f9d7c897f" email: "jim.smith@gmail.com" givenName: "Jim" familyName: "Smith" picture: "img/download.jpeg" gender: "male" locale: "en" reader: "9080770707070700" google: "115562565652656565656" twitter: "jimsmith" facebook: "" wave: "2013.7" categories: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech" label: "tech" , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/design" label: "design" ] topics: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/topic/arduino" interest: "high" updated: 1367539068016 created: 1367539068016 , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/topic/rock climbing" interest: "low" updated: 1367539068016 created: 1367539068016 ] preferences: autoMarkAsReadOnSelect: "50" "category/reviews/entryOverviewSize": "0" "subscription/feed/http:// feeds.engadget.com/weblogsinc/engadget/entryOverviewSize": "4" "subscription/feed/http:// www.yatzer.com/feed/index.php/hideReadArticlesFilter": "off" "category/photography/entryOverviewSize": "6" "subscription/feed/http:// feeds.feedburner.com/venturebeat/entryOverviewSize.mobile": "1" streams: "" FEEDLY_API_VERSION = "v3" class ApiRequest constructor: (@url) -> url: -> @url _url_parameters: (args) -> "?" + _.map(args, (v, k) -> k + "=" + v ).join("&") get: (resource, args, callback) -> _console.debug "[feedlyconsole/apirequest] fetching %s.", resource unless chrome?.extension? # not embedded, demo mode demo = demo_data[resource] status = if demo then 'ok' else 'error' _console.debug "[feedlyconsole/apirequest] fetching %s %O, status %s.", resource, demo, status callback demo, status, null else url = [ @url, resource ].join('/') + @_url_parameters args _console.debug "[feedlyconsole/apirequest] fetching %s at %s.", resource, url request = @build_request url $.ajax(request).always (response, status, xhr) -> _console.debug "[feedlyconsole/apirequest] '%s' status '%s' response %O xhr %O.", resource, status, response, xhr return callback response, status, xhr build_request: (url) -> url: url dataType: "json" xhrFields: withCredentials: true class FeedlyApiRequest extends ApiRequest constructor: (@url, @api_version, @oauth) -> super([@url, @api_version].join('/')) @resources = [ "profile" "tags" "subscriptions" "preferences" "categories" "topics" "streams" ] build_request: (url) -> request = super(url) request.headers = Authorization: "OAuth #{@oauth}" return request validate_resource: (resource, args) -> return _.find @resources, (str) -> resource.indexOf(str) is 0 get: (resource, args, callback) -> _console.debug "[feedlyconsole/feedlyapirequest] validating %s.", resource unless @validate_resource resource, args _console.debug "[feedlyconsole/apirequest] failed to validate %s (%s).", resource, args return callback null, 'error', null return super resource, args, (response, status, xhr) -> if response? and not status? # Every response from the API includes rate limiting # headers, as well as an indicator injected by the API proxy # whether the request was done with authentication. Both are # used to display request rate information and a link to # authenticate, if required. ratelimit = remaining: parseInt xhr.getResponseHeader("X-RateLimit-Remaining") limit: parseInt xhr.getResponseHeader("X-RateLimit-Limit") authenticated: xhr.getResponseHeader("Authenticated") is "true" $("#ratelimit").html _self.shell.templates .rateLimitTemplate(ratelimit) if ratelimit.remaining is 0 alert "Whoops, you've hit the rate limit." _self.shell.deactivate() return null # For simplicity, this tutorial trivially deals with request # failures by just returning null from this function via the # callback. callback(response, status) else if response? and response return callback(response, status) else return callback() class FeedlyNode @_ROOT_COMMANDS: [ "profile" "tags" "subscriptions" "preferences" "categories" "topics" ] @_ROOT_PATH: '/' @_ROOT_NODE: null @_NODES: {} @_NODES[@_ROOT_PATH] = null constructor: (@name, @path, @type, @json_data) -> @children = null FeedlyNode._NODES[@path] = @ @type ?= 'node' _console.debug "[feedlyconsole/FeedlyNode] new '%s' %O.", @path, @ @reset: -> @_NODES = {} @_ROOT_NODE = null @_NODES[@_ROOT_PATH] = null @_initRootNode: => @_ROOT_NODE ?= new RootFeedlyNode() @_getPathParts: (path) -> parts = path.split("/") #remove empty trailing element return parts.slice(0, parts.length - 1) if parts[parts.length - 1] is "" return parts @_current: -> return Josh.config.pathhandler.current @_api: -> return Josh.FeedlyConsole.api # normalize path @_resolvePath: (path) => parts = @_getPathParts(path) # non-empty item 0 indicates relative path # when relative, prepend _current path parts = @_getPathParts(@_current().path).concat(parts) if parts[0] isnt "" # resolve `.` and `..` resolved = [] _.each parts, (x) -> return if x is "." if x is ".." resolved.pop() else resolved.push x return "/" if not resolved? or resolved.length is 1 return resolved.join("/") @getNode: (path, callback) => @_initRootNode() _console.debug "[feedlyconsole/FeedlyNode] looking for node at '%s'.", path return callback @_ROOT_NODE unless path? normalized = @_resolvePath path _console.debug "[feedlyconsole/FeedlyNode] normalized path '%s'", normalized return callback @_NODES[normalized] if normalized of @_NODES name = _.last normalized.split('/') @call_api_by_path normalized, (json, status) -> if status is 'error' callback null else node = new FeedlyNode(name, normalized, 'name', json) return callback node @call_api_by_path: (path, callback) -> parts = path.split('/') _console.debug "[feedlyconsole/FeedlyNode.call_api_by_path] depth %i, %O.", parts.length, parts if parts.length is 2 # [ "", "profile" ] @_api().get _.last(parts), [], (response, status) -> callback(response, status) else # [ "", "categories", "blackberry" ] # get parent node parent_path = parts[0...-1].join '/' name = _.last parts @getNode parent_path, (parent) => _console.debug "[feedlyconsole/FeedlyNode.call_api_by_path] parent %O @ %s.", parent, parent_path id = parent.getChildId(name) return callback("", "error") unless id? encoded_id = encodeURIComponent id @_api().get "streams/#{encoded_id}/contents", [], (response, status) -> callback(response, status) @getChildNodes: (node, callback) => @_initRootNode() node.getChildNodes callback call_api_by_path: (callback) -> FeedlyNode.call_api_by_path @path, (json, status) => @json_data = json callback(json) # match title or label to get id getChildId: (name) -> @call_api_by_path unless @json_data? if _.isArray(@json_data) item = _.find @json_data, (item) -> _.find ['title', 'label', 'id'], (field) -> item[field] is name return item.id if item? return null getChildNodes: (callback) -> if @type is 'leaf' @children = null return callback @children else unless @json_data? @call_api_by_path => @children ?= @makeJSONNodes() return callback @children else @children ?= @makeJSONNodes() return callback @children makeJSONNodes: (json) -> json ?= @json_data unless json? return [] json = json.items if 'items' of json if _.isArray(json) nodes = _.map json, (item) => name = item.title or item.label or item.id path = [@path, name].join '/' type = if 'id' of item then 'node' else 'leaf' json = if 'id' of item then null else item return new FeedlyNode name, path, type, json return nodes else # its a map, so all children are leaves _.map json, (value, key) => name = [ key value ].join(":") json = key: value return new FeedlyNode name, @path, 'leaf', json class RootFeedlyNode extends FeedlyNode constructor: () -> super FeedlyNode._ROOT_PATH, FeedlyNode._ROOT_PATH, { cmds: FeedlyNode._ROOT_COMMANDS } @type = 'root' getChildNodes: (callback) -> unless @children? @children =[] for name in FeedlyNode._ROOT_COMMANDS child_path = [@path, name].join('') if child_path of FeedlyNode._NODES @children.push FeedlyNode._NODES[child_path] else @children.push new FeedlyNode(name, child_path, 'node', null) return callback @children toString: -> return "#{@name} '#{@path}'" #////////////////////////////////////////////////////////// # based on josh.js:gh-pages githubconsole ((root, $, _) -> Josh.FeedlyConsole = ((root, $, _) -> # Enable console debugging, when Josh.Debug is set and there is a # console object on the document root. _console = (if (Josh.Debug and window.console) then window.console else log: -> debug: -> ) ### # Console State # ============= # # `_self` contains all state variables for the console's operation ### _self = shell: Josh.config.shell ui: {} root_commands: {} pathhandler: Josh.config.pathhandler api: null observer: null ### # Custom Templates # ================ # `Josh.Shell` uses *Underscore* templates for rendering output to # the shell. This console overrides some and adds a couple of new # ones for its own commands. ### ### # **templates.prompt** # Override of the default prompt to provide a multi-line prompt of # the current user, repo and path and branch. ### _self.shell.templates.prompt = _.template """ <strong> <%= node.path %> $ </strong> """ # **templates.ls** # Override of the pathhandler ls template to create a multi-column listing. _self.shell.templates.ls = _.template """ <ul class='widelist'> <% _.each(nodes, function(node) { %> <li><%- node.name %></li> <% }); %> </ul><div class='clear'/>""" # **templates.not_found** # Override of the pathhandler *not_found* template, since we will # throw *not_found* if you try to access a valid file. This is # done for the simplicity of the tutorial. _self.shell.templates.not_found = _.template """ <div><%=cmd%>: <%=path%>: No such directory</div> """ # **templates.not_ready** # Override of the pathhandler *not_found* template, since we will # throw *not_found* if you try to access a valid file. This is # done for the simplicity of the tutorial. _self.shell.templates.not_ready = _.template """ <div><%=cmd%>: <%=path%>: api is not ready</div> """ #**templates.rateLimitTemplate** # rate limiting will be added later to feedly api _self.shell.templates.rateLimitTemplate = _.template """ <%=remaining%>/<%=limit%> """ #**templates.profile** # user information _self.shell.templates.profile = _.template """ <div class='userinfo'> <img src='<%=profile.picture%>' style='float:right;'/> <table> <tr> <td><strong>Id:</strong></td> <td><%=profile.id %></td> </tr> <tr><td><strong>Email:</strong></td> <td><%=profile.email %></td></tr> <tr><td><strong>Name:</strong></td> <td><%=profile.fullName %></td></tr> </table></div>""" _self.node_pretty_json = 'node-pretty-json-' _self.node_pretty_json_count = 0 window.swap_node_pretty_json = (old_node, new_node) -> console.debug "[feedlyconsole] swap " o = $ "##{old_node}" n = $ "##{new_node}" l = o.parent() n.after o l.append n _self.shell.templates.json = do -> _json = _.template """ <span class='node node-pretty-json' id='<%= new_id %>'></span> <script id='script_<%= new_id %>'> window.swap_node_pretty_json( '<%= old_id %>', '<%= new_id %>' ); $("#script_<%= new_id %>").remove(); </script> """ (obj) -> # use previously created span # count = _self.node_pretty_json_count prefix = _self.node_pretty_json obj.old_id = "#{prefix}#{count}" _self.node_pretty_json_count = ++count obj.new_id = "#{prefix}#{count}" options = el: "##{obj.old_id}" data: obj.data new PrettyJSON.view.Node options return _json obj # **templates.default_template** # Use when specific template doesn't exist _self.shell.templates.default_template = _self.shell.templates.json # Adding Commands to the Console # ============================== buildExecCommandHandler = (command_name) -> # `exec` handles the execution of the command. exec: (cmd, args, callback) -> if _self.api _self.api.get command_name, null, (data) -> return err("api request failed to get data") unless data template = _self.shell.templates[command_name] template = template or _self.shell.templates.default_template template_args = {} template_args[command_name] = template_args["data"] = data _console.debug "[feedlyconsole/handler] data %O cmd %O args %O", data, cmd, args callback template(template_args) else path = _self.pathandler.current.path callback _self.shell.templates.not_ready({cmd, path}) simple_commands = [ "profile" "tags" "subscriptions" "preferences" "categories" "topics" ] addCommandHandler = (name, map) -> _self.shell.setCommandHandler name, map _self.root_commands[name] = map _.each simple_commands, (command) -> addCommandHandler command, buildExecCommandHandler(command) _self.root_commands.tags.help = "help here" addCommandHandler 'info' , exec: do -> options = {} parser = new optparse.OptionParser [ ['-h', '--help', "Command help"]] parser.on "help", -> options.help = true this.halt() parser.on 0, (subcommand)-> options.subcommand = subcommand this.halt() parser.on '*', -> options.error = true this.halt() #reset parser/state parser.reset = -> options = {} parser._halt = false (cmd, args, callback) -> parser.reset() parser.parse args _console.debug "[feedlconsole/info] args %s options %s", args.join(' '), JSON.stringify options if options.help return callback _self.shell.templates.options help_string: parser.toString() + '\n CMD Specify which node, or all' else if options.subcommand nodes = null switch options.subcommand when "all" return callback _self.shell.templates.json data: FeedlyNode._NODES else FeedlyNode.getNode options.subcommand, (node) -> if node return callback _self.shell.templates.json {data: node} else return callback _self.shell.templates.not_found cmd: 'info' path: options.subcommand else return callback _self.shell.templates.json data: _self.pathhandler.current help: "info on current path node" completion: Josh.config.pathhandler.pathCompletionHandler #<section id='onNewPrompt'/> # This attaches a custom prompt render to the shell. _self.shell.onNewPrompt (callback) -> callback _self.shell.templates.prompt self: _self node: _self.pathhandler.current ### # Wiring up PathHandler # ===================== #<section id='getNode'/> # getNode # ------- # `getNode` is required by `Josh.PathHandler` to provide # filesystem behavior. Given a path, it is expected to return a # pathnode or null; ### _self.pathhandler.getNode = FeedlyNode.getNode ### #<section id='getChildNodes'/> # getChildNodes # ------------- # `getChildNodes` is the second function implementation required # for `Josh.PathHandler`. Given a pathnode, it returns a list of # child pathnodes. This is used by `Tab` completion to resolve a # partial path, after first resolving the nearest parent node # using `getNode ### _self.pathhandler.getChildNodes = FeedlyNode.getChildNodes ### #<section id='initialize'/> # # initalize # -------------- ### # This function sets the node initialize = (evt) -> #err, callback) { insertShellUI() FeedlyNode.getNode "/", (node) -> return err("could not initialize root directory") unless node _self.pathhandler.current = node insertCSSLink = (name) -> _console.debug "[feedlyconsole/init] inserting css #{name}" # insert css into head $("head").append $ "<link/>", rel: "stylesheet" type: "text/css" href: chrome.extension.getURL(name) doInsertShellUI = -> _self.observer.disconnect() if _self.observer? file = "feedlyconsole.html" _console.debug "[feedlyconsole/init] injecting shell ui from %s.", file insertCSSLink "stylesheets/jquery-ui.css" insertCSSLink "stylesheets/feedlyconsole.css" insertCSSLink "stylesheets/pretty-json.css" feedlyconsole = $("<div/>", id: "feedlyconsole" ).load(chrome?.extension?.getURL(file), (resp, status, xmlrq) -> if status is 'error' _console.error "[feedlyconsole/init] failed to load #{file}, init failed." else _console.log "[feedlyconsole/init] loaded shell ui %s %O readline.attach %O. status %s", file, $("#feedlyconsole"), this, status Josh.config.readline.attach $("#shell-panel").get(0) initializeUI() ) $("body").prepend feedlyconsole insertShellUI = -> if $("#feedlyconsole").length is 0 target = document config = attributes: true subtree: true _console.debug "[feedlyconsole/init/observer] mutation observer start target %O config %O", target, config _self.observer.observe target, config if _self.observer else _console.debug "[feedlyconsole/init/shell] #feedlyconsole found." initializeUI() # watch body writing until its stable enough to doInsertShellUI mutationHandler = (mutationRecords) -> _found = false mutationRecords.forEach (mutation) -> target = mutation.target if target.id is "box" type = mutation.type name = mutation.attributeName attr = target.attributes.getNamedItem(name) value = "" value = attr.value if attr isnt null _console.debug "[feedlyconsole/init/observer] %s: [%s]=%s on %O", type, name, value, target # not sure if wide will always be set, so trigger on the next mod wide = name is "class" and value.indexOf("wide") isnt -1 narrow = name is "class" and value.indexOf("narrow") isnt -1 page = name is "_pageid" and value.indexOf("rot2") isnt -1 if not _found and (wide or page or narrow) _console.debug "[feedlyconsole/init/observer] mutation observer end %O", _self.observer _found = true doInsertShellUI() # found what we were looking for null # this function # initializes the UI state to allow the shell to be shown and # hidden. initializeUI = -> # We grab the `consoletab` and wire up hover behavior for it. # We also wire up a click handler to show the console to the `consoletab`. toggleActivateAndShow = -> if _self.shell.isActive() hideAndDeactivate() else activateAndShow() activateAndShow = -> $consoletab.slideUp() _self.shell.activate() $consolePanel.slideDown() $consolePanel.focus() hideAndDeactivate = -> _self.shell.deactivate() $consolePanel.slideUp() $consolePanel.blur() $consoletab.slideDown() _console.log "[feedlyconsole/init] initializeUI." $consoletab = $("#consoletab") if $consoletab.length is 0 console.error "failed to find %s", $consoletab.selector $consoletab.hover (-> $consoletab.addClass "consoletab-hover" $consoletab.removeClass "consoletab" ), -> $consoletab.removeClass "consoletab-hover" $consoletab.addClass "consoletab" $consoletab.click -> activateAndShow() $consolePanel = $("#shell-container") $consolePanel.resizable handles: "s" $(document).on "keypress", ((event) -> return if _self.shell.isActive() if event.keyCode is 126 event.preventDefault() activateAndShow() ) _self.shell.onEOT hideAndDeactivate _self.shell.onCancel hideAndDeactivate # export ui functions so they can be called by background page # via page action icon _self.ui.toggleActivateAndShow = toggleActivateAndShow _self.ui.activateAndShow = activateAndShow _self.ui.hideAndDeactivate = hideAndDeactivate if chrome?.runtime? # running in extension _console.log "[feedlyconsole/init] in extension contex, initializing." _console.debug "[feedlyconsole/init] mutationHandler installed." _self.observer = new MutationObserver(mutationHandler) initialize() # listener to messages from background page chrome.runtime.onMessage.addListener (request, sender, sendResponse) -> _console.debug "[feedlyconsole/msg] msg: %s.", request.msg if request.action is "icon_active" _console.debug "[feedlyconsole/msg/icon_active] ignore." else if request.action is "toggle_console" unless _self.ui.toggleActivateAndShow? window.console.warn "[feedlyconsole/msg] ui not ready." else _self.ui.toggleActivateAndShow() else if request.action is "cookie_feedlytoken" unless _self.api oauth = request.feedlytoken url_array = request.url.split "/" url = url_array[0] + "//" + url_array[2] _console.debug "[feedlyconsole/msg/cookie_feedlytoken] api init, url: %s oauth: %s.", url, oauth.slice 0, 8 _self.api = new FeedlyApiRequest(url, FEEDLY_API_VERSION, oauth) else oauth = request.feedlytoken.slice 0, 8 url = request.url _console.debug "[feedlyconsole/msg/cookie_feedlytoken] ignoring, api, url (%s), oauth (%s) already initialized.", url, oauth else _console.debug "[feedlyconsole/msg] unknown action %s request %O.", request.action, request sendResponse action: "ack" else # running in webpage $(document).ready -> _console.log "[feedlyconsole/init] webpage context, initialize." initialize() _self.api = new FeedlyApiRequest("", FEEDLY_API_VERSION, null) _self.ui.activateAndShow() _self )(root, $, _) ) this, $, _ console.log "[feedlyconsole] loaded Josh version %s.", Josh?.Version
70437
`var Josh = Josh || {}` if console _console = console _console.log "[feedlyconsole] using console." else if window.console _console = windows.console _console.log "[feedlyconsole] using window.console." else _console = log: () -> _console.log "[feedlyconsole] haha." types = ['debug', 'warn', 'error', 'dir'] for type in types unless _console[type] _console[type] = _console.log _josh_disable_console = log: () -> debug: () -> Josh.Debug = true Josh.config = history: new Josh.History() console: _console killring: new Josh.KillRing() readline: null shell: null pathhandler: null Josh.config.readline = new Josh.ReadLine(Josh.config) Josh.config.shell = new Josh.Shell(Josh.config) # `Josh.PathHandler` is attached to `Josh.Shell` to provide basic file # system navigation. Josh.config.pathhandler = new Josh.PathHandler(Josh.config.shell, console: Josh.config.console ) demo_data = tags: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/global.saved" , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/tech" label: "tech" , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/inspiration" label: "inspiration" ] subscriptions: [ id: "feed/http://feeds.feedburner.com/design-milk" title: "Design Milk" categories: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/design" label: "design" , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/global.must" label: "must reads" ] sortid: "26152F8F" updated: 1367539068016 website: "http://design-milk.com" , id: "feed/http://5secondrule.typepad.com/my_weblog/atom.xml" title: "5 second rule" categories: [] sortid: "26152F8F" updated: 1367539068016 website: "http://5secondrule.typepad.com/my_weblog/" , id: "feed/http://feed.500px.com/500px-editors" title: "500px: Editors' Choice" categories: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/photography" label: "photography" ] sortid: "26152F8F" updated: 1367539068016 website: "http://500px.com/editors" ] profile: id: "c805fcbf-3acf-4302-a97e-d82f9d7c897f" email: "<EMAIL>" givenName: "<NAME>" familyName: "<NAME>" picture: "img/download.jpeg" gender: "male" locale: "en" reader: "9080770707070700" google: "115562565652656565656" twitter: "jimsmith" facebook: "" wave: "2013.7" categories: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech" label: "tech" , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/design" label: "design" ] topics: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/topic/arduino" interest: "high" updated: 1367539068016 created: 1367539068016 , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/topic/rock climbing" interest: "low" updated: 1367539068016 created: 1367539068016 ] preferences: autoMarkAsReadOnSelect: "50" "category/reviews/entryOverviewSize": "0" "subscription/feed/http:// feeds.engadget.com/weblogsinc/engadget/entryOverviewSize": "4" "subscription/feed/http:// www.yatzer.com/feed/index.php/hideReadArticlesFilter": "off" "category/photography/entryOverviewSize": "6" "subscription/feed/http:// feeds.feedburner.com/venturebeat/entryOverviewSize.mobile": "1" streams: "" FEEDLY_API_VERSION = "v3" class ApiRequest constructor: (@url) -> url: -> @url _url_parameters: (args) -> "?" + _.map(args, (v, k) -> k + "=" + v ).join("&") get: (resource, args, callback) -> _console.debug "[feedlyconsole/apirequest] fetching %s.", resource unless chrome?.extension? # not embedded, demo mode demo = demo_data[resource] status = if demo then 'ok' else 'error' _console.debug "[feedlyconsole/apirequest] fetching %s %O, status %s.", resource, demo, status callback demo, status, null else url = [ @url, resource ].join('/') + @_url_parameters args _console.debug "[feedlyconsole/apirequest] fetching %s at %s.", resource, url request = @build_request url $.ajax(request).always (response, status, xhr) -> _console.debug "[feedlyconsole/apirequest] '%s' status '%s' response %O xhr %O.", resource, status, response, xhr return callback response, status, xhr build_request: (url) -> url: url dataType: "json" xhrFields: withCredentials: true class FeedlyApiRequest extends ApiRequest constructor: (@url, @api_version, @oauth) -> super([@url, @api_version].join('/')) @resources = [ "profile" "tags" "subscriptions" "preferences" "categories" "topics" "streams" ] build_request: (url) -> request = super(url) request.headers = Authorization: "OAuth #{@oauth}" return request validate_resource: (resource, args) -> return _.find @resources, (str) -> resource.indexOf(str) is 0 get: (resource, args, callback) -> _console.debug "[feedlyconsole/feedlyapirequest] validating %s.", resource unless @validate_resource resource, args _console.debug "[feedlyconsole/apirequest] failed to validate %s (%s).", resource, args return callback null, 'error', null return super resource, args, (response, status, xhr) -> if response? and not status? # Every response from the API includes rate limiting # headers, as well as an indicator injected by the API proxy # whether the request was done with authentication. Both are # used to display request rate information and a link to # authenticate, if required. ratelimit = remaining: parseInt xhr.getResponseHeader("X-RateLimit-Remaining") limit: parseInt xhr.getResponseHeader("X-RateLimit-Limit") authenticated: xhr.getResponseHeader("Authenticated") is "true" $("#ratelimit").html _self.shell.templates .rateLimitTemplate(ratelimit) if ratelimit.remaining is 0 alert "Whoops, you've hit the rate limit." _self.shell.deactivate() return null # For simplicity, this tutorial trivially deals with request # failures by just returning null from this function via the # callback. callback(response, status) else if response? and response return callback(response, status) else return callback() class FeedlyNode @_ROOT_COMMANDS: [ "profile" "tags" "subscriptions" "preferences" "categories" "topics" ] @_ROOT_PATH: '/' @_ROOT_NODE: null @_NODES: {} @_NODES[@_ROOT_PATH] = null constructor: (@name, @path, @type, @json_data) -> @children = null FeedlyNode._NODES[@path] = @ @type ?= 'node' _console.debug "[feedlyconsole/FeedlyNode] new '%s' %O.", @path, @ @reset: -> @_NODES = {} @_ROOT_NODE = null @_NODES[@_ROOT_PATH] = null @_initRootNode: => @_ROOT_NODE ?= new RootFeedlyNode() @_getPathParts: (path) -> parts = path.split("/") #remove empty trailing element return parts.slice(0, parts.length - 1) if parts[parts.length - 1] is "" return parts @_current: -> return Josh.config.pathhandler.current @_api: -> return Josh.FeedlyConsole.api # normalize path @_resolvePath: (path) => parts = @_getPathParts(path) # non-empty item 0 indicates relative path # when relative, prepend _current path parts = @_getPathParts(@_current().path).concat(parts) if parts[0] isnt "" # resolve `.` and `..` resolved = [] _.each parts, (x) -> return if x is "." if x is ".." resolved.pop() else resolved.push x return "/" if not resolved? or resolved.length is 1 return resolved.join("/") @getNode: (path, callback) => @_initRootNode() _console.debug "[feedlyconsole/FeedlyNode] looking for node at '%s'.", path return callback @_ROOT_NODE unless path? normalized = @_resolvePath path _console.debug "[feedlyconsole/FeedlyNode] normalized path '%s'", normalized return callback @_NODES[normalized] if normalized of @_NODES name = _.last normalized.split('/') @call_api_by_path normalized, (json, status) -> if status is 'error' callback null else node = new FeedlyNode(name, normalized, 'name', json) return callback node @call_api_by_path: (path, callback) -> parts = path.split('/') _console.debug "[feedlyconsole/FeedlyNode.call_api_by_path] depth %i, %O.", parts.length, parts if parts.length is 2 # [ "", "profile" ] @_api().get _.last(parts), [], (response, status) -> callback(response, status) else # [ "", "categories", "blackberry" ] # get parent node parent_path = parts[0...-1].join '/' name = _.last parts @getNode parent_path, (parent) => _console.debug "[feedlyconsole/FeedlyNode.call_api_by_path] parent %O @ %s.", parent, parent_path id = parent.getChildId(name) return callback("", "error") unless id? encoded_id = encodeURIComponent id @_api().get "streams/#{encoded_id}/contents", [], (response, status) -> callback(response, status) @getChildNodes: (node, callback) => @_initRootNode() node.getChildNodes callback call_api_by_path: (callback) -> FeedlyNode.call_api_by_path @path, (json, status) => @json_data = json callback(json) # match title or label to get id getChildId: (name) -> @call_api_by_path unless @json_data? if _.isArray(@json_data) item = _.find @json_data, (item) -> _.find ['title', 'label', 'id'], (field) -> item[field] is name return item.id if item? return null getChildNodes: (callback) -> if @type is 'leaf' @children = null return callback @children else unless @json_data? @call_api_by_path => @children ?= @makeJSONNodes() return callback @children else @children ?= @makeJSONNodes() return callback @children makeJSONNodes: (json) -> json ?= @json_data unless json? return [] json = json.items if 'items' of json if _.isArray(json) nodes = _.map json, (item) => name = item.title or item.label or item.id path = [@path, name].join '/' type = if 'id' of item then 'node' else 'leaf' json = if 'id' of item then null else item return new FeedlyNode name, path, type, json return nodes else # its a map, so all children are leaves _.map json, (value, key) => name = [ key value ].join(":") json = key: value return new FeedlyNode name, @path, 'leaf', json class RootFeedlyNode extends FeedlyNode constructor: () -> super FeedlyNode._ROOT_PATH, FeedlyNode._ROOT_PATH, { cmds: FeedlyNode._ROOT_COMMANDS } @type = 'root' getChildNodes: (callback) -> unless @children? @children =[] for name in FeedlyNode._ROOT_COMMANDS child_path = [@path, name].join('') if child_path of FeedlyNode._NODES @children.push FeedlyNode._NODES[child_path] else @children.push new FeedlyNode(name, child_path, 'node', null) return callback @children toString: -> return "#{@name} '#{@path}'" #////////////////////////////////////////////////////////// # based on josh.js:gh-pages githubconsole ((root, $, _) -> Josh.FeedlyConsole = ((root, $, _) -> # Enable console debugging, when Josh.Debug is set and there is a # console object on the document root. _console = (if (Josh.Debug and window.console) then window.console else log: -> debug: -> ) ### # Console State # ============= # # `_self` contains all state variables for the console's operation ### _self = shell: Josh.config.shell ui: {} root_commands: {} pathhandler: Josh.config.pathhandler api: null observer: null ### # Custom Templates # ================ # `Josh.Shell` uses *Underscore* templates for rendering output to # the shell. This console overrides some and adds a couple of new # ones for its own commands. ### ### # **templates.prompt** # Override of the default prompt to provide a multi-line prompt of # the current user, repo and path and branch. ### _self.shell.templates.prompt = _.template """ <strong> <%= node.path %> $ </strong> """ # **templates.ls** # Override of the pathhandler ls template to create a multi-column listing. _self.shell.templates.ls = _.template """ <ul class='widelist'> <% _.each(nodes, function(node) { %> <li><%- node.name %></li> <% }); %> </ul><div class='clear'/>""" # **templates.not_found** # Override of the pathhandler *not_found* template, since we will # throw *not_found* if you try to access a valid file. This is # done for the simplicity of the tutorial. _self.shell.templates.not_found = _.template """ <div><%=cmd%>: <%=path%>: No such directory</div> """ # **templates.not_ready** # Override of the pathhandler *not_found* template, since we will # throw *not_found* if you try to access a valid file. This is # done for the simplicity of the tutorial. _self.shell.templates.not_ready = _.template """ <div><%=cmd%>: <%=path%>: api is not ready</div> """ #**templates.rateLimitTemplate** # rate limiting will be added later to feedly api _self.shell.templates.rateLimitTemplate = _.template """ <%=remaining%>/<%=limit%> """ #**templates.profile** # user information _self.shell.templates.profile = _.template """ <div class='userinfo'> <img src='<%=profile.picture%>' style='float:right;'/> <table> <tr> <td><strong>Id:</strong></td> <td><%=profile.id %></td> </tr> <tr><td><strong>Email:</strong></td> <td><%=profile.email %></td></tr> <tr><td><strong>Name:</strong></td> <td><%=profile.fullName %></td></tr> </table></div>""" _self.node_pretty_json = 'node-pretty-json-' _self.node_pretty_json_count = 0 window.swap_node_pretty_json = (old_node, new_node) -> console.debug "[feedlyconsole] swap " o = $ "##{old_node}" n = $ "##{new_node}" l = o.parent() n.after o l.append n _self.shell.templates.json = do -> _json = _.template """ <span class='node node-pretty-json' id='<%= new_id %>'></span> <script id='script_<%= new_id %>'> window.swap_node_pretty_json( '<%= old_id %>', '<%= new_id %>' ); $("#script_<%= new_id %>").remove(); </script> """ (obj) -> # use previously created span # count = _self.node_pretty_json_count prefix = _self.node_pretty_json obj.old_id = "#{prefix}#{count}" _self.node_pretty_json_count = ++count obj.new_id = "#{prefix}#{count}" options = el: "##{obj.old_id}" data: obj.data new PrettyJSON.view.Node options return _json obj # **templates.default_template** # Use when specific template doesn't exist _self.shell.templates.default_template = _self.shell.templates.json # Adding Commands to the Console # ============================== buildExecCommandHandler = (command_name) -> # `exec` handles the execution of the command. exec: (cmd, args, callback) -> if _self.api _self.api.get command_name, null, (data) -> return err("api request failed to get data") unless data template = _self.shell.templates[command_name] template = template or _self.shell.templates.default_template template_args = {} template_args[command_name] = template_args["data"] = data _console.debug "[feedlyconsole/handler] data %O cmd %O args %O", data, cmd, args callback template(template_args) else path = _self.pathandler.current.path callback _self.shell.templates.not_ready({cmd, path}) simple_commands = [ "profile" "tags" "subscriptions" "preferences" "categories" "topics" ] addCommandHandler = (name, map) -> _self.shell.setCommandHandler name, map _self.root_commands[name] = map _.each simple_commands, (command) -> addCommandHandler command, buildExecCommandHandler(command) _self.root_commands.tags.help = "help here" addCommandHandler 'info' , exec: do -> options = {} parser = new optparse.OptionParser [ ['-h', '--help', "Command help"]] parser.on "help", -> options.help = true this.halt() parser.on 0, (subcommand)-> options.subcommand = subcommand this.halt() parser.on '*', -> options.error = true this.halt() #reset parser/state parser.reset = -> options = {} parser._halt = false (cmd, args, callback) -> parser.reset() parser.parse args _console.debug "[feedlconsole/info] args %s options %s", args.join(' '), JSON.stringify options if options.help return callback _self.shell.templates.options help_string: parser.toString() + '\n CMD Specify which node, or all' else if options.subcommand nodes = null switch options.subcommand when "all" return callback _self.shell.templates.json data: FeedlyNode._NODES else FeedlyNode.getNode options.subcommand, (node) -> if node return callback _self.shell.templates.json {data: node} else return callback _self.shell.templates.not_found cmd: 'info' path: options.subcommand else return callback _self.shell.templates.json data: _self.pathhandler.current help: "info on current path node" completion: Josh.config.pathhandler.pathCompletionHandler #<section id='onNewPrompt'/> # This attaches a custom prompt render to the shell. _self.shell.onNewPrompt (callback) -> callback _self.shell.templates.prompt self: _self node: _self.pathhandler.current ### # Wiring up PathHandler # ===================== #<section id='getNode'/> # getNode # ------- # `getNode` is required by `Josh.PathHandler` to provide # filesystem behavior. Given a path, it is expected to return a # pathnode or null; ### _self.pathhandler.getNode = FeedlyNode.getNode ### #<section id='getChildNodes'/> # getChildNodes # ------------- # `getChildNodes` is the second function implementation required # for `Josh.PathHandler`. Given a pathnode, it returns a list of # child pathnodes. This is used by `Tab` completion to resolve a # partial path, after first resolving the nearest parent node # using `getNode ### _self.pathhandler.getChildNodes = FeedlyNode.getChildNodes ### #<section id='initialize'/> # # initalize # -------------- ### # This function sets the node initialize = (evt) -> #err, callback) { insertShellUI() FeedlyNode.getNode "/", (node) -> return err("could not initialize root directory") unless node _self.pathhandler.current = node insertCSSLink = (name) -> _console.debug "[feedlyconsole/init] inserting css #{name}" # insert css into head $("head").append $ "<link/>", rel: "stylesheet" type: "text/css" href: chrome.extension.getURL(name) doInsertShellUI = -> _self.observer.disconnect() if _self.observer? file = "feedlyconsole.html" _console.debug "[feedlyconsole/init] injecting shell ui from %s.", file insertCSSLink "stylesheets/jquery-ui.css" insertCSSLink "stylesheets/feedlyconsole.css" insertCSSLink "stylesheets/pretty-json.css" feedlyconsole = $("<div/>", id: "feedlyconsole" ).load(chrome?.extension?.getURL(file), (resp, status, xmlrq) -> if status is 'error' _console.error "[feedlyconsole/init] failed to load #{file}, init failed." else _console.log "[feedlyconsole/init] loaded shell ui %s %O readline.attach %O. status %s", file, $("#feedlyconsole"), this, status Josh.config.readline.attach $("#shell-panel").get(0) initializeUI() ) $("body").prepend feedlyconsole insertShellUI = -> if $("#feedlyconsole").length is 0 target = document config = attributes: true subtree: true _console.debug "[feedlyconsole/init/observer] mutation observer start target %O config %O", target, config _self.observer.observe target, config if _self.observer else _console.debug "[feedlyconsole/init/shell] #feedlyconsole found." initializeUI() # watch body writing until its stable enough to doInsertShellUI mutationHandler = (mutationRecords) -> _found = false mutationRecords.forEach (mutation) -> target = mutation.target if target.id is "box" type = mutation.type name = mutation.attributeName attr = target.attributes.getNamedItem(name) value = "" value = attr.value if attr isnt null _console.debug "[feedlyconsole/init/observer] %s: [%s]=%s on %O", type, name, value, target # not sure if wide will always be set, so trigger on the next mod wide = name is "class" and value.indexOf("wide") isnt -1 narrow = name is "class" and value.indexOf("narrow") isnt -1 page = name is "_pageid" and value.indexOf("rot2") isnt -1 if not _found and (wide or page or narrow) _console.debug "[feedlyconsole/init/observer] mutation observer end %O", _self.observer _found = true doInsertShellUI() # found what we were looking for null # this function # initializes the UI state to allow the shell to be shown and # hidden. initializeUI = -> # We grab the `consoletab` and wire up hover behavior for it. # We also wire up a click handler to show the console to the `consoletab`. toggleActivateAndShow = -> if _self.shell.isActive() hideAndDeactivate() else activateAndShow() activateAndShow = -> $consoletab.slideUp() _self.shell.activate() $consolePanel.slideDown() $consolePanel.focus() hideAndDeactivate = -> _self.shell.deactivate() $consolePanel.slideUp() $consolePanel.blur() $consoletab.slideDown() _console.log "[feedlyconsole/init] initializeUI." $consoletab = $("#consoletab") if $consoletab.length is 0 console.error "failed to find %s", $consoletab.selector $consoletab.hover (-> $consoletab.addClass "consoletab-hover" $consoletab.removeClass "consoletab" ), -> $consoletab.removeClass "consoletab-hover" $consoletab.addClass "consoletab" $consoletab.click -> activateAndShow() $consolePanel = $("#shell-container") $consolePanel.resizable handles: "s" $(document).on "keypress", ((event) -> return if _self.shell.isActive() if event.keyCode is 126 event.preventDefault() activateAndShow() ) _self.shell.onEOT hideAndDeactivate _self.shell.onCancel hideAndDeactivate # export ui functions so they can be called by background page # via page action icon _self.ui.toggleActivateAndShow = toggleActivateAndShow _self.ui.activateAndShow = activateAndShow _self.ui.hideAndDeactivate = hideAndDeactivate if chrome?.runtime? # running in extension _console.log "[feedlyconsole/init] in extension contex, initializing." _console.debug "[feedlyconsole/init] mutationHandler installed." _self.observer = new MutationObserver(mutationHandler) initialize() # listener to messages from background page chrome.runtime.onMessage.addListener (request, sender, sendResponse) -> _console.debug "[feedlyconsole/msg] msg: %s.", request.msg if request.action is "icon_active" _console.debug "[feedlyconsole/msg/icon_active] ignore." else if request.action is "toggle_console" unless _self.ui.toggleActivateAndShow? window.console.warn "[feedlyconsole/msg] ui not ready." else _self.ui.toggleActivateAndShow() else if request.action is "cookie_feedlytoken" unless _self.api oauth = request.feedlytoken url_array = request.url.split "/" url = url_array[0] + "//" + url_array[2] _console.debug "[feedlyconsole/msg/cookie_feedlytoken] api init, url: %s oauth: %s.", url, oauth.slice 0, 8 _self.api = new FeedlyApiRequest(url, FEEDLY_API_VERSION, oauth) else oauth = request.feedlytoken.slice 0, 8 url = request.url _console.debug "[feedlyconsole/msg/cookie_feedlytoken] ignoring, api, url (%s), oauth (%s) already initialized.", url, oauth else _console.debug "[feedlyconsole/msg] unknown action %s request %O.", request.action, request sendResponse action: "ack" else # running in webpage $(document).ready -> _console.log "[feedlyconsole/init] webpage context, initialize." initialize() _self.api = new FeedlyApiRequest("", FEEDLY_API_VERSION, null) _self.ui.activateAndShow() _self )(root, $, _) ) this, $, _ console.log "[feedlyconsole] loaded Josh version %s.", Josh?.Version
true
`var Josh = Josh || {}` if console _console = console _console.log "[feedlyconsole] using console." else if window.console _console = windows.console _console.log "[feedlyconsole] using window.console." else _console = log: () -> _console.log "[feedlyconsole] haha." types = ['debug', 'warn', 'error', 'dir'] for type in types unless _console[type] _console[type] = _console.log _josh_disable_console = log: () -> debug: () -> Josh.Debug = true Josh.config = history: new Josh.History() console: _console killring: new Josh.KillRing() readline: null shell: null pathhandler: null Josh.config.readline = new Josh.ReadLine(Josh.config) Josh.config.shell = new Josh.Shell(Josh.config) # `Josh.PathHandler` is attached to `Josh.Shell` to provide basic file # system navigation. Josh.config.pathhandler = new Josh.PathHandler(Josh.config.shell, console: Josh.config.console ) demo_data = tags: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/global.saved" , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/tech" label: "tech" , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/inspiration" label: "inspiration" ] subscriptions: [ id: "feed/http://feeds.feedburner.com/design-milk" title: "Design Milk" categories: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/design" label: "design" , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/global.must" label: "must reads" ] sortid: "26152F8F" updated: 1367539068016 website: "http://design-milk.com" , id: "feed/http://5secondrule.typepad.com/my_weblog/atom.xml" title: "5 second rule" categories: [] sortid: "26152F8F" updated: 1367539068016 website: "http://5secondrule.typepad.com/my_weblog/" , id: "feed/http://feed.500px.com/500px-editors" title: "500px: Editors' Choice" categories: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/photography" label: "photography" ] sortid: "26152F8F" updated: 1367539068016 website: "http://500px.com/editors" ] profile: id: "c805fcbf-3acf-4302-a97e-d82f9d7c897f" email: "PI:EMAIL:<EMAIL>END_PI" givenName: "PI:NAME:<NAME>END_PI" familyName: "PI:NAME:<NAME>END_PI" picture: "img/download.jpeg" gender: "male" locale: "en" reader: "9080770707070700" google: "115562565652656565656" twitter: "jimsmith" facebook: "" wave: "2013.7" categories: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech" label: "tech" , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/design" label: "design" ] topics: [ id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/topic/arduino" interest: "high" updated: 1367539068016 created: 1367539068016 , id: "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/topic/rock climbing" interest: "low" updated: 1367539068016 created: 1367539068016 ] preferences: autoMarkAsReadOnSelect: "50" "category/reviews/entryOverviewSize": "0" "subscription/feed/http:// feeds.engadget.com/weblogsinc/engadget/entryOverviewSize": "4" "subscription/feed/http:// www.yatzer.com/feed/index.php/hideReadArticlesFilter": "off" "category/photography/entryOverviewSize": "6" "subscription/feed/http:// feeds.feedburner.com/venturebeat/entryOverviewSize.mobile": "1" streams: "" FEEDLY_API_VERSION = "v3" class ApiRequest constructor: (@url) -> url: -> @url _url_parameters: (args) -> "?" + _.map(args, (v, k) -> k + "=" + v ).join("&") get: (resource, args, callback) -> _console.debug "[feedlyconsole/apirequest] fetching %s.", resource unless chrome?.extension? # not embedded, demo mode demo = demo_data[resource] status = if demo then 'ok' else 'error' _console.debug "[feedlyconsole/apirequest] fetching %s %O, status %s.", resource, demo, status callback demo, status, null else url = [ @url, resource ].join('/') + @_url_parameters args _console.debug "[feedlyconsole/apirequest] fetching %s at %s.", resource, url request = @build_request url $.ajax(request).always (response, status, xhr) -> _console.debug "[feedlyconsole/apirequest] '%s' status '%s' response %O xhr %O.", resource, status, response, xhr return callback response, status, xhr build_request: (url) -> url: url dataType: "json" xhrFields: withCredentials: true class FeedlyApiRequest extends ApiRequest constructor: (@url, @api_version, @oauth) -> super([@url, @api_version].join('/')) @resources = [ "profile" "tags" "subscriptions" "preferences" "categories" "topics" "streams" ] build_request: (url) -> request = super(url) request.headers = Authorization: "OAuth #{@oauth}" return request validate_resource: (resource, args) -> return _.find @resources, (str) -> resource.indexOf(str) is 0 get: (resource, args, callback) -> _console.debug "[feedlyconsole/feedlyapirequest] validating %s.", resource unless @validate_resource resource, args _console.debug "[feedlyconsole/apirequest] failed to validate %s (%s).", resource, args return callback null, 'error', null return super resource, args, (response, status, xhr) -> if response? and not status? # Every response from the API includes rate limiting # headers, as well as an indicator injected by the API proxy # whether the request was done with authentication. Both are # used to display request rate information and a link to # authenticate, if required. ratelimit = remaining: parseInt xhr.getResponseHeader("X-RateLimit-Remaining") limit: parseInt xhr.getResponseHeader("X-RateLimit-Limit") authenticated: xhr.getResponseHeader("Authenticated") is "true" $("#ratelimit").html _self.shell.templates .rateLimitTemplate(ratelimit) if ratelimit.remaining is 0 alert "Whoops, you've hit the rate limit." _self.shell.deactivate() return null # For simplicity, this tutorial trivially deals with request # failures by just returning null from this function via the # callback. callback(response, status) else if response? and response return callback(response, status) else return callback() class FeedlyNode @_ROOT_COMMANDS: [ "profile" "tags" "subscriptions" "preferences" "categories" "topics" ] @_ROOT_PATH: '/' @_ROOT_NODE: null @_NODES: {} @_NODES[@_ROOT_PATH] = null constructor: (@name, @path, @type, @json_data) -> @children = null FeedlyNode._NODES[@path] = @ @type ?= 'node' _console.debug "[feedlyconsole/FeedlyNode] new '%s' %O.", @path, @ @reset: -> @_NODES = {} @_ROOT_NODE = null @_NODES[@_ROOT_PATH] = null @_initRootNode: => @_ROOT_NODE ?= new RootFeedlyNode() @_getPathParts: (path) -> parts = path.split("/") #remove empty trailing element return parts.slice(0, parts.length - 1) if parts[parts.length - 1] is "" return parts @_current: -> return Josh.config.pathhandler.current @_api: -> return Josh.FeedlyConsole.api # normalize path @_resolvePath: (path) => parts = @_getPathParts(path) # non-empty item 0 indicates relative path # when relative, prepend _current path parts = @_getPathParts(@_current().path).concat(parts) if parts[0] isnt "" # resolve `.` and `..` resolved = [] _.each parts, (x) -> return if x is "." if x is ".." resolved.pop() else resolved.push x return "/" if not resolved? or resolved.length is 1 return resolved.join("/") @getNode: (path, callback) => @_initRootNode() _console.debug "[feedlyconsole/FeedlyNode] looking for node at '%s'.", path return callback @_ROOT_NODE unless path? normalized = @_resolvePath path _console.debug "[feedlyconsole/FeedlyNode] normalized path '%s'", normalized return callback @_NODES[normalized] if normalized of @_NODES name = _.last normalized.split('/') @call_api_by_path normalized, (json, status) -> if status is 'error' callback null else node = new FeedlyNode(name, normalized, 'name', json) return callback node @call_api_by_path: (path, callback) -> parts = path.split('/') _console.debug "[feedlyconsole/FeedlyNode.call_api_by_path] depth %i, %O.", parts.length, parts if parts.length is 2 # [ "", "profile" ] @_api().get _.last(parts), [], (response, status) -> callback(response, status) else # [ "", "categories", "blackberry" ] # get parent node parent_path = parts[0...-1].join '/' name = _.last parts @getNode parent_path, (parent) => _console.debug "[feedlyconsole/FeedlyNode.call_api_by_path] parent %O @ %s.", parent, parent_path id = parent.getChildId(name) return callback("", "error") unless id? encoded_id = encodeURIComponent id @_api().get "streams/#{encoded_id}/contents", [], (response, status) -> callback(response, status) @getChildNodes: (node, callback) => @_initRootNode() node.getChildNodes callback call_api_by_path: (callback) -> FeedlyNode.call_api_by_path @path, (json, status) => @json_data = json callback(json) # match title or label to get id getChildId: (name) -> @call_api_by_path unless @json_data? if _.isArray(@json_data) item = _.find @json_data, (item) -> _.find ['title', 'label', 'id'], (field) -> item[field] is name return item.id if item? return null getChildNodes: (callback) -> if @type is 'leaf' @children = null return callback @children else unless @json_data? @call_api_by_path => @children ?= @makeJSONNodes() return callback @children else @children ?= @makeJSONNodes() return callback @children makeJSONNodes: (json) -> json ?= @json_data unless json? return [] json = json.items if 'items' of json if _.isArray(json) nodes = _.map json, (item) => name = item.title or item.label or item.id path = [@path, name].join '/' type = if 'id' of item then 'node' else 'leaf' json = if 'id' of item then null else item return new FeedlyNode name, path, type, json return nodes else # its a map, so all children are leaves _.map json, (value, key) => name = [ key value ].join(":") json = key: value return new FeedlyNode name, @path, 'leaf', json class RootFeedlyNode extends FeedlyNode constructor: () -> super FeedlyNode._ROOT_PATH, FeedlyNode._ROOT_PATH, { cmds: FeedlyNode._ROOT_COMMANDS } @type = 'root' getChildNodes: (callback) -> unless @children? @children =[] for name in FeedlyNode._ROOT_COMMANDS child_path = [@path, name].join('') if child_path of FeedlyNode._NODES @children.push FeedlyNode._NODES[child_path] else @children.push new FeedlyNode(name, child_path, 'node', null) return callback @children toString: -> return "#{@name} '#{@path}'" #////////////////////////////////////////////////////////// # based on josh.js:gh-pages githubconsole ((root, $, _) -> Josh.FeedlyConsole = ((root, $, _) -> # Enable console debugging, when Josh.Debug is set and there is a # console object on the document root. _console = (if (Josh.Debug and window.console) then window.console else log: -> debug: -> ) ### # Console State # ============= # # `_self` contains all state variables for the console's operation ### _self = shell: Josh.config.shell ui: {} root_commands: {} pathhandler: Josh.config.pathhandler api: null observer: null ### # Custom Templates # ================ # `Josh.Shell` uses *Underscore* templates for rendering output to # the shell. This console overrides some and adds a couple of new # ones for its own commands. ### ### # **templates.prompt** # Override of the default prompt to provide a multi-line prompt of # the current user, repo and path and branch. ### _self.shell.templates.prompt = _.template """ <strong> <%= node.path %> $ </strong> """ # **templates.ls** # Override of the pathhandler ls template to create a multi-column listing. _self.shell.templates.ls = _.template """ <ul class='widelist'> <% _.each(nodes, function(node) { %> <li><%- node.name %></li> <% }); %> </ul><div class='clear'/>""" # **templates.not_found** # Override of the pathhandler *not_found* template, since we will # throw *not_found* if you try to access a valid file. This is # done for the simplicity of the tutorial. _self.shell.templates.not_found = _.template """ <div><%=cmd%>: <%=path%>: No such directory</div> """ # **templates.not_ready** # Override of the pathhandler *not_found* template, since we will # throw *not_found* if you try to access a valid file. This is # done for the simplicity of the tutorial. _self.shell.templates.not_ready = _.template """ <div><%=cmd%>: <%=path%>: api is not ready</div> """ #**templates.rateLimitTemplate** # rate limiting will be added later to feedly api _self.shell.templates.rateLimitTemplate = _.template """ <%=remaining%>/<%=limit%> """ #**templates.profile** # user information _self.shell.templates.profile = _.template """ <div class='userinfo'> <img src='<%=profile.picture%>' style='float:right;'/> <table> <tr> <td><strong>Id:</strong></td> <td><%=profile.id %></td> </tr> <tr><td><strong>Email:</strong></td> <td><%=profile.email %></td></tr> <tr><td><strong>Name:</strong></td> <td><%=profile.fullName %></td></tr> </table></div>""" _self.node_pretty_json = 'node-pretty-json-' _self.node_pretty_json_count = 0 window.swap_node_pretty_json = (old_node, new_node) -> console.debug "[feedlyconsole] swap " o = $ "##{old_node}" n = $ "##{new_node}" l = o.parent() n.after o l.append n _self.shell.templates.json = do -> _json = _.template """ <span class='node node-pretty-json' id='<%= new_id %>'></span> <script id='script_<%= new_id %>'> window.swap_node_pretty_json( '<%= old_id %>', '<%= new_id %>' ); $("#script_<%= new_id %>").remove(); </script> """ (obj) -> # use previously created span # count = _self.node_pretty_json_count prefix = _self.node_pretty_json obj.old_id = "#{prefix}#{count}" _self.node_pretty_json_count = ++count obj.new_id = "#{prefix}#{count}" options = el: "##{obj.old_id}" data: obj.data new PrettyJSON.view.Node options return _json obj # **templates.default_template** # Use when specific template doesn't exist _self.shell.templates.default_template = _self.shell.templates.json # Adding Commands to the Console # ============================== buildExecCommandHandler = (command_name) -> # `exec` handles the execution of the command. exec: (cmd, args, callback) -> if _self.api _self.api.get command_name, null, (data) -> return err("api request failed to get data") unless data template = _self.shell.templates[command_name] template = template or _self.shell.templates.default_template template_args = {} template_args[command_name] = template_args["data"] = data _console.debug "[feedlyconsole/handler] data %O cmd %O args %O", data, cmd, args callback template(template_args) else path = _self.pathandler.current.path callback _self.shell.templates.not_ready({cmd, path}) simple_commands = [ "profile" "tags" "subscriptions" "preferences" "categories" "topics" ] addCommandHandler = (name, map) -> _self.shell.setCommandHandler name, map _self.root_commands[name] = map _.each simple_commands, (command) -> addCommandHandler command, buildExecCommandHandler(command) _self.root_commands.tags.help = "help here" addCommandHandler 'info' , exec: do -> options = {} parser = new optparse.OptionParser [ ['-h', '--help', "Command help"]] parser.on "help", -> options.help = true this.halt() parser.on 0, (subcommand)-> options.subcommand = subcommand this.halt() parser.on '*', -> options.error = true this.halt() #reset parser/state parser.reset = -> options = {} parser._halt = false (cmd, args, callback) -> parser.reset() parser.parse args _console.debug "[feedlconsole/info] args %s options %s", args.join(' '), JSON.stringify options if options.help return callback _self.shell.templates.options help_string: parser.toString() + '\n CMD Specify which node, or all' else if options.subcommand nodes = null switch options.subcommand when "all" return callback _self.shell.templates.json data: FeedlyNode._NODES else FeedlyNode.getNode options.subcommand, (node) -> if node return callback _self.shell.templates.json {data: node} else return callback _self.shell.templates.not_found cmd: 'info' path: options.subcommand else return callback _self.shell.templates.json data: _self.pathhandler.current help: "info on current path node" completion: Josh.config.pathhandler.pathCompletionHandler #<section id='onNewPrompt'/> # This attaches a custom prompt render to the shell. _self.shell.onNewPrompt (callback) -> callback _self.shell.templates.prompt self: _self node: _self.pathhandler.current ### # Wiring up PathHandler # ===================== #<section id='getNode'/> # getNode # ------- # `getNode` is required by `Josh.PathHandler` to provide # filesystem behavior. Given a path, it is expected to return a # pathnode or null; ### _self.pathhandler.getNode = FeedlyNode.getNode ### #<section id='getChildNodes'/> # getChildNodes # ------------- # `getChildNodes` is the second function implementation required # for `Josh.PathHandler`. Given a pathnode, it returns a list of # child pathnodes. This is used by `Tab` completion to resolve a # partial path, after first resolving the nearest parent node # using `getNode ### _self.pathhandler.getChildNodes = FeedlyNode.getChildNodes ### #<section id='initialize'/> # # initalize # -------------- ### # This function sets the node initialize = (evt) -> #err, callback) { insertShellUI() FeedlyNode.getNode "/", (node) -> return err("could not initialize root directory") unless node _self.pathhandler.current = node insertCSSLink = (name) -> _console.debug "[feedlyconsole/init] inserting css #{name}" # insert css into head $("head").append $ "<link/>", rel: "stylesheet" type: "text/css" href: chrome.extension.getURL(name) doInsertShellUI = -> _self.observer.disconnect() if _self.observer? file = "feedlyconsole.html" _console.debug "[feedlyconsole/init] injecting shell ui from %s.", file insertCSSLink "stylesheets/jquery-ui.css" insertCSSLink "stylesheets/feedlyconsole.css" insertCSSLink "stylesheets/pretty-json.css" feedlyconsole = $("<div/>", id: "feedlyconsole" ).load(chrome?.extension?.getURL(file), (resp, status, xmlrq) -> if status is 'error' _console.error "[feedlyconsole/init] failed to load #{file}, init failed." else _console.log "[feedlyconsole/init] loaded shell ui %s %O readline.attach %O. status %s", file, $("#feedlyconsole"), this, status Josh.config.readline.attach $("#shell-panel").get(0) initializeUI() ) $("body").prepend feedlyconsole insertShellUI = -> if $("#feedlyconsole").length is 0 target = document config = attributes: true subtree: true _console.debug "[feedlyconsole/init/observer] mutation observer start target %O config %O", target, config _self.observer.observe target, config if _self.observer else _console.debug "[feedlyconsole/init/shell] #feedlyconsole found." initializeUI() # watch body writing until its stable enough to doInsertShellUI mutationHandler = (mutationRecords) -> _found = false mutationRecords.forEach (mutation) -> target = mutation.target if target.id is "box" type = mutation.type name = mutation.attributeName attr = target.attributes.getNamedItem(name) value = "" value = attr.value if attr isnt null _console.debug "[feedlyconsole/init/observer] %s: [%s]=%s on %O", type, name, value, target # not sure if wide will always be set, so trigger on the next mod wide = name is "class" and value.indexOf("wide") isnt -1 narrow = name is "class" and value.indexOf("narrow") isnt -1 page = name is "_pageid" and value.indexOf("rot2") isnt -1 if not _found and (wide or page or narrow) _console.debug "[feedlyconsole/init/observer] mutation observer end %O", _self.observer _found = true doInsertShellUI() # found what we were looking for null # this function # initializes the UI state to allow the shell to be shown and # hidden. initializeUI = -> # We grab the `consoletab` and wire up hover behavior for it. # We also wire up a click handler to show the console to the `consoletab`. toggleActivateAndShow = -> if _self.shell.isActive() hideAndDeactivate() else activateAndShow() activateAndShow = -> $consoletab.slideUp() _self.shell.activate() $consolePanel.slideDown() $consolePanel.focus() hideAndDeactivate = -> _self.shell.deactivate() $consolePanel.slideUp() $consolePanel.blur() $consoletab.slideDown() _console.log "[feedlyconsole/init] initializeUI." $consoletab = $("#consoletab") if $consoletab.length is 0 console.error "failed to find %s", $consoletab.selector $consoletab.hover (-> $consoletab.addClass "consoletab-hover" $consoletab.removeClass "consoletab" ), -> $consoletab.removeClass "consoletab-hover" $consoletab.addClass "consoletab" $consoletab.click -> activateAndShow() $consolePanel = $("#shell-container") $consolePanel.resizable handles: "s" $(document).on "keypress", ((event) -> return if _self.shell.isActive() if event.keyCode is 126 event.preventDefault() activateAndShow() ) _self.shell.onEOT hideAndDeactivate _self.shell.onCancel hideAndDeactivate # export ui functions so they can be called by background page # via page action icon _self.ui.toggleActivateAndShow = toggleActivateAndShow _self.ui.activateAndShow = activateAndShow _self.ui.hideAndDeactivate = hideAndDeactivate if chrome?.runtime? # running in extension _console.log "[feedlyconsole/init] in extension contex, initializing." _console.debug "[feedlyconsole/init] mutationHandler installed." _self.observer = new MutationObserver(mutationHandler) initialize() # listener to messages from background page chrome.runtime.onMessage.addListener (request, sender, sendResponse) -> _console.debug "[feedlyconsole/msg] msg: %s.", request.msg if request.action is "icon_active" _console.debug "[feedlyconsole/msg/icon_active] ignore." else if request.action is "toggle_console" unless _self.ui.toggleActivateAndShow? window.console.warn "[feedlyconsole/msg] ui not ready." else _self.ui.toggleActivateAndShow() else if request.action is "cookie_feedlytoken" unless _self.api oauth = request.feedlytoken url_array = request.url.split "/" url = url_array[0] + "//" + url_array[2] _console.debug "[feedlyconsole/msg/cookie_feedlytoken] api init, url: %s oauth: %s.", url, oauth.slice 0, 8 _self.api = new FeedlyApiRequest(url, FEEDLY_API_VERSION, oauth) else oauth = request.feedlytoken.slice 0, 8 url = request.url _console.debug "[feedlyconsole/msg/cookie_feedlytoken] ignoring, api, url (%s), oauth (%s) already initialized.", url, oauth else _console.debug "[feedlyconsole/msg] unknown action %s request %O.", request.action, request sendResponse action: "ack" else # running in webpage $(document).ready -> _console.log "[feedlyconsole/init] webpage context, initialize." initialize() _self.api = new FeedlyApiRequest("", FEEDLY_API_VERSION, null) _self.ui.activateAndShow() _self )(root, $, _) ) this, $, _ console.log "[feedlyconsole] loaded Josh version %s.", Josh?.Version
[ { "context": " gitについては、インストールが必要かもしれないので補助すること。\n#\n# Author:\n# miura-simpline <miura.daisuke@simpline.co.jp>\n\nmodule.exports = ", "end": 631, "score": 0.9989142417907715, "start": 617, "tag": "USERNAME", "value": "miura-simpline" }, { "context": "必要かもしれないので補助すること。\n#\n# Author...
scripts/training1st.coffee
simpline/TrainingBotBoss
0
# Description: # The 1st week of Training - 研修1週目 # 1週目における課題は、OSインストールと基本的なOSの操作である。 # gitはもはや基本的といって差し支えないほどであるため含める。 # # Commands: # boss 1日目は何をしましょうか。 # boss 本日より配属されました{名前}と申します。{意気込み} # boss お客様にあいさつしてきました。 # boss サーバを立ててきました。{感想} # boss 2日目は何をしましょうか。 # boss NTPを導入してきました。{感想} # boss 3日目は何をしましょうか。 # boss メールサーバを立ててきました。{感想} # boss 4日目は何をしましょうか。 # boss スクリプトを作成してきました。{感想} # boss 5日目は何をしましょうか。 # boss サーバを調べてきました。{何を調べたか} # # Notes: # この内容はあえて言葉足らずにしてあるので、研修生に対してきちんとフォローすること。 # Vmware上に作ってもらうことになるが、外部と接続できるようにNATにしておくこと。 # gitについては、インストールが必要かもしれないので補助すること。 # # Author: # miura-simpline <miura.daisuke@simpline.co.jp> module.exports = (robot) -> robot.respond /1日目は何をしましょうか。/i, (res) -> namae = res.match[1] res.reply """ まずは、これからの意気込みについて語っていただけますでしょうか。 私に「本日より配属されました[名前]と申します。[意気込み]」とあいさつしてください。 """ robot.respond /本日より配属されました(.*)と申します。.*/i, (res) -> namae = res.match[1] res.reply """ はじめまして、#{namae}さん。これからよろしくお願いします。 ここに配属されたということは少なくともITパスポートの資格は取っていると考えます。 そして、ここでは実際に作業して、経験を積んでいってもらいます。 まずはお客様に「{名前}と申します。{これまでの経歴}」とあいさつにしにいってください。 終わったら、「お客様にあいさつしてきました。」と報告してください。 """ robot.respond /お客様にあいさつしてきました。/i, (res) -> res.reply """ それでは、ある案件で急にサーバが1台必要になったので、それを用意してください。 OSはCentOS7で お願いします。次のサイトを参考にして初期設定まで完了させてください。 https://www.server-world.info ユーザとグループを新たに作成して、sudoで作業するようにしてください。 終わったら、「サーバを立ててきました。{感想}」と報告してください。 """ robot.respond /サーバを立ててきました。.*/i, (res) -> res.reply "お疲れ様です。手順は残しておいてください。1日目はこれでおしまいです。" robot.respond /2日目は何をしましょうか。/i, (res) -> res.reply """ 昨日構築したサーバでNTPを導入してください。 自動起動されるように設定してください。 ランレベルを変えて、起動後の状況がどのように変わるか確認してください。 inittabに何か登録して、きちんと動作するか確認してください。 終わったら、「NTPを導入してきました。{苦労した点}」と報告してください。 """ robot.respond /NTPを導入してきました。.*/i, (res) -> res.reply "お疲れ様です。手順は残しておいてください。2日目はこれでおしまいです。" robot.respond /3日目は何をしましょうか。/i, (res) -> res.reply """ 急遽メールサーバが必要になったので、新たに構築してください。 時刻同期は前回構築したサーバを使用して設定されるようにしてください。 終わったら、「メールサーバを立ててきました。{感想}」と報告してください。 """ robot.respond /メールサーバを立ててきました。.*/i, (res) -> res.reply "お疲れ様です。手順は残しておいてください。3日目はこれでおしまいです。" robot.respond /4日目は何をしましょうか。/i, (res) -> res.reply """ 簡単なスクリプトを作成してください。 NTPの結果を受け取って、結果を判定するようなので構いません。 ログを出力させるようにしてください。ログはローテーションさせてください。 スクリプトはcronに登録して、定期的に実行されるようにしてください。 また、gitを使ってバージョン管理するようにしてください。 終わったら、「スクリプトを作成してきました。{感想}」と報告してください。 """ robot.respond /スクリプトを作成してきました。.*/i, (res) -> res.reply "お疲れ様です。手順は残しておいてください。4日目はこれでおしまいです。" robot.respond /5日目は何をしましょうか。/i, (res) -> res.reply """ これまで構築してきたサーバの動きがおかしくないか確認してください。 プロセスが動いているか、ログにエラーが吐かれてないか確認してください。 他にCPUやメモリ、ディスクなども調べてきてください。 ためしにファイルシステムの容量を増やしてください。 終わったら、「サーバを調べてきました。{何を調べたか}」と報告してください。 """ robot.respond /サーバを調べてきました。.*/i, (res) -> res.reply """ お疲れ様です。調べた結果はまとめてアップロードしておいてください。 5日日はこれでおしまいです。 今週実施したことについて復習しておいて、来週に臨んでください。 """
12244
# Description: # The 1st week of Training - 研修1週目 # 1週目における課題は、OSインストールと基本的なOSの操作である。 # gitはもはや基本的といって差し支えないほどであるため含める。 # # Commands: # boss 1日目は何をしましょうか。 # boss 本日より配属されました{名前}と申します。{意気込み} # boss お客様にあいさつしてきました。 # boss サーバを立ててきました。{感想} # boss 2日目は何をしましょうか。 # boss NTPを導入してきました。{感想} # boss 3日目は何をしましょうか。 # boss メールサーバを立ててきました。{感想} # boss 4日目は何をしましょうか。 # boss スクリプトを作成してきました。{感想} # boss 5日目は何をしましょうか。 # boss サーバを調べてきました。{何を調べたか} # # Notes: # この内容はあえて言葉足らずにしてあるので、研修生に対してきちんとフォローすること。 # Vmware上に作ってもらうことになるが、外部と接続できるようにNATにしておくこと。 # gitについては、インストールが必要かもしれないので補助すること。 # # Author: # miura-simpline <<EMAIL>> module.exports = (robot) -> robot.respond /1日目は何をしましょうか。/i, (res) -> namae = res.match[1] res.reply """ まずは、これからの意気込みについて語っていただけますでしょうか。 私に「本日より配属されました[名前]と申します。[意気込み]」とあいさつしてください。 """ robot.respond /本日より配属されました(.*)と申します。.*/i, (res) -> namae = res.match[1] res.reply """ はじめまして、#{namae}さん。これからよろしくお願いします。 ここに配属されたということは少なくともITパスポートの資格は取っていると考えます。 そして、ここでは実際に作業して、経験を積んでいってもらいます。 まずはお客様に「{名前}と申します。{これまでの経歴}」とあいさつにしにいってください。 終わったら、「お客様にあいさつしてきました。」と報告してください。 """ robot.respond /お客様にあいさつしてきました。/i, (res) -> res.reply """ それでは、ある案件で急にサーバが1台必要になったので、それを用意してください。 OSはCentOS7で お願いします。次のサイトを参考にして初期設定まで完了させてください。 https://www.server-world.info ユーザとグループを新たに作成して、sudoで作業するようにしてください。 終わったら、「サーバを立ててきました。{感想}」と報告してください。 """ robot.respond /サーバを立ててきました。.*/i, (res) -> res.reply "お疲れ様です。手順は残しておいてください。1日目はこれでおしまいです。" robot.respond /2日目は何をしましょうか。/i, (res) -> res.reply """ 昨日構築したサーバでNTPを導入してください。 自動起動されるように設定してください。 ランレベルを変えて、起動後の状況がどのように変わるか確認してください。 inittabに何か登録して、きちんと動作するか確認してください。 終わったら、「NTPを導入してきました。{苦労した点}」と報告してください。 """ robot.respond /NTPを導入してきました。.*/i, (res) -> res.reply "お疲れ様です。手順は残しておいてください。2日目はこれでおしまいです。" robot.respond /3日目は何をしましょうか。/i, (res) -> res.reply """ 急遽メールサーバが必要になったので、新たに構築してください。 時刻同期は前回構築したサーバを使用して設定されるようにしてください。 終わったら、「メールサーバを立ててきました。{感想}」と報告してください。 """ robot.respond /メールサーバを立ててきました。.*/i, (res) -> res.reply "お疲れ様です。手順は残しておいてください。3日目はこれでおしまいです。" robot.respond /4日目は何をしましょうか。/i, (res) -> res.reply """ 簡単なスクリプトを作成してください。 NTPの結果を受け取って、結果を判定するようなので構いません。 ログを出力させるようにしてください。ログはローテーションさせてください。 スクリプトはcronに登録して、定期的に実行されるようにしてください。 また、gitを使ってバージョン管理するようにしてください。 終わったら、「スクリプトを作成してきました。{感想}」と報告してください。 """ robot.respond /スクリプトを作成してきました。.*/i, (res) -> res.reply "お疲れ様です。手順は残しておいてください。4日目はこれでおしまいです。" robot.respond /5日目は何をしましょうか。/i, (res) -> res.reply """ これまで構築してきたサーバの動きがおかしくないか確認してください。 プロセスが動いているか、ログにエラーが吐かれてないか確認してください。 他にCPUやメモリ、ディスクなども調べてきてください。 ためしにファイルシステムの容量を増やしてください。 終わったら、「サーバを調べてきました。{何を調べたか}」と報告してください。 """ robot.respond /サーバを調べてきました。.*/i, (res) -> res.reply """ お疲れ様です。調べた結果はまとめてアップロードしておいてください。 5日日はこれでおしまいです。 今週実施したことについて復習しておいて、来週に臨んでください。 """
true
# Description: # The 1st week of Training - 研修1週目 # 1週目における課題は、OSインストールと基本的なOSの操作である。 # gitはもはや基本的といって差し支えないほどであるため含める。 # # Commands: # boss 1日目は何をしましょうか。 # boss 本日より配属されました{名前}と申します。{意気込み} # boss お客様にあいさつしてきました。 # boss サーバを立ててきました。{感想} # boss 2日目は何をしましょうか。 # boss NTPを導入してきました。{感想} # boss 3日目は何をしましょうか。 # boss メールサーバを立ててきました。{感想} # boss 4日目は何をしましょうか。 # boss スクリプトを作成してきました。{感想} # boss 5日目は何をしましょうか。 # boss サーバを調べてきました。{何を調べたか} # # Notes: # この内容はあえて言葉足らずにしてあるので、研修生に対してきちんとフォローすること。 # Vmware上に作ってもらうことになるが、外部と接続できるようにNATにしておくこと。 # gitについては、インストールが必要かもしれないので補助すること。 # # Author: # miura-simpline <PI:EMAIL:<EMAIL>END_PI> module.exports = (robot) -> robot.respond /1日目は何をしましょうか。/i, (res) -> namae = res.match[1] res.reply """ まずは、これからの意気込みについて語っていただけますでしょうか。 私に「本日より配属されました[名前]と申します。[意気込み]」とあいさつしてください。 """ robot.respond /本日より配属されました(.*)と申します。.*/i, (res) -> namae = res.match[1] res.reply """ はじめまして、#{namae}さん。これからよろしくお願いします。 ここに配属されたということは少なくともITパスポートの資格は取っていると考えます。 そして、ここでは実際に作業して、経験を積んでいってもらいます。 まずはお客様に「{名前}と申します。{これまでの経歴}」とあいさつにしにいってください。 終わったら、「お客様にあいさつしてきました。」と報告してください。 """ robot.respond /お客様にあいさつしてきました。/i, (res) -> res.reply """ それでは、ある案件で急にサーバが1台必要になったので、それを用意してください。 OSはCentOS7で お願いします。次のサイトを参考にして初期設定まで完了させてください。 https://www.server-world.info ユーザとグループを新たに作成して、sudoで作業するようにしてください。 終わったら、「サーバを立ててきました。{感想}」と報告してください。 """ robot.respond /サーバを立ててきました。.*/i, (res) -> res.reply "お疲れ様です。手順は残しておいてください。1日目はこれでおしまいです。" robot.respond /2日目は何をしましょうか。/i, (res) -> res.reply """ 昨日構築したサーバでNTPを導入してください。 自動起動されるように設定してください。 ランレベルを変えて、起動後の状況がどのように変わるか確認してください。 inittabに何か登録して、きちんと動作するか確認してください。 終わったら、「NTPを導入してきました。{苦労した点}」と報告してください。 """ robot.respond /NTPを導入してきました。.*/i, (res) -> res.reply "お疲れ様です。手順は残しておいてください。2日目はこれでおしまいです。" robot.respond /3日目は何をしましょうか。/i, (res) -> res.reply """ 急遽メールサーバが必要になったので、新たに構築してください。 時刻同期は前回構築したサーバを使用して設定されるようにしてください。 終わったら、「メールサーバを立ててきました。{感想}」と報告してください。 """ robot.respond /メールサーバを立ててきました。.*/i, (res) -> res.reply "お疲れ様です。手順は残しておいてください。3日目はこれでおしまいです。" robot.respond /4日目は何をしましょうか。/i, (res) -> res.reply """ 簡単なスクリプトを作成してください。 NTPの結果を受け取って、結果を判定するようなので構いません。 ログを出力させるようにしてください。ログはローテーションさせてください。 スクリプトはcronに登録して、定期的に実行されるようにしてください。 また、gitを使ってバージョン管理するようにしてください。 終わったら、「スクリプトを作成してきました。{感想}」と報告してください。 """ robot.respond /スクリプトを作成してきました。.*/i, (res) -> res.reply "お疲れ様です。手順は残しておいてください。4日目はこれでおしまいです。" robot.respond /5日目は何をしましょうか。/i, (res) -> res.reply """ これまで構築してきたサーバの動きがおかしくないか確認してください。 プロセスが動いているか、ログにエラーが吐かれてないか確認してください。 他にCPUやメモリ、ディスクなども調べてきてください。 ためしにファイルシステムの容量を増やしてください。 終わったら、「サーバを調べてきました。{何を調べたか}」と報告してください。 """ robot.respond /サーバを調べてきました。.*/i, (res) -> res.reply """ お疲れ様です。調べた結果はまとめてアップロードしておいてください。 5日日はこれでおしまいです。 今週実施したことについて復習しておいて、来週に臨んでください。 """
[ { "context": "###\n\tcrumbnav.js 0.1\n\n Created by Juho Viitasalo\n\n\tBased on flexnav by Jason Weaver http://jasonwe", "end": 49, "score": 0.9999033808708191, "start": 35, "tag": "NAME", "value": "Juho Viitasalo" }, { "context": "\n Created by Juho Viitasalo\n\n\tBased on flexna...
src/jquery.crumbnav.coffee
jiv-e/crumbnav
0
### crumbnav.js 0.1 Created by Juho Viitasalo Based on flexnav by Jason Weaver http://jasonweaver.name Released under http://unlicense.org/ ### # TODO Hide contextual menu button (+) when there's only on child in the submenu require('./sass/crumbnav.scss') # Use local alias for $.noConflict() compatibility $ = jQuery $('html').removeClass('no-js').addClass('js') $ -> #attachFastClick = Origami.fastclick; #attachFastClick(document.body); $.fn.crumbnav = (options) -> settings = $.extend({ 'navClass': 'c-nav', 'titleClass': 'title', 'topModifier': '-top', 'itemClass': 'c-item', 'openClass': 'cn-open', 'closedClass': 'cn-close', 'rootsOpenClass': 'cn-open-roots', 'rootsClosedClass': 'cn-close-roots', 'firstLevelClass': 'crumbnav--first-level', 'rootClass': 'crumbnav__root', 'currentClass': 'active' 'moreMenuClass': 'c-more', 'popupClass': 'popup', 'breadcrumbClass': 'crumbnav-crumb', 'buttonClass': 'c-button', 'mainModifier': '-main', 'parentModifier': '-parent', 'moreModifier': '-more', 'rootsModifier': '-roots', 'largeModifier': '-large', 'hoverIntent': false, 'hoverIntentTimeout': 150, 'calcItemWidths': false, 'hover': false, 'titleText': 'Menu', }, options ) @.options = settings $nav = $(@) # TODO Add support for multiple menus? At the moment breaks javascript execution! $navUl = if $nav.children('ul').length == 1 then $nav.children('ul') else alert("Unsupported number of ul's inside the navigation!"); $current = $('li.'+settings.currentClass, $navUl) if $current.length > 1 then alert('Multiple active elements in the menu! There should be only one.') $root = $() $topParents = $() $parents = $() $breadcrumb = $() $breadcrumbLength = 0 $currentChildMenu = $() $topParentButtons = $() $parentButtons = $() $moreMenu = $() # TODO Should we use a button element? $button = $('<span class="'+settings.buttonClass+'"><i></i></span>') $moreMenu = $('<li class="'+settings.moreMenuClass+'"><ul class="'+settings.popupClass+'"></ul></li>').append($button.clone().addClass(settings.moreModifier)) # Add title if not present if $nav.children('.'+settings.titleClass).length == 0 $nav.prepend('<div class="'+settings.titleClass+'">'+settings.titleText+'</div>') addBreadcrumbClasses = -> # Breadcrumb trail $currentParents = $current.parentsUntil($navUl, 'li') $breadcrumb = $currentParents.add($current) $breadcrumbLength = $breadcrumb.length $breadcrumb .addClass(settings.breadcrumbClass) .each (index) -> $(@).addClass('-out-'+index+' -in-'+($breadcrumbLength - index - 1)) # Breadcrumb length modifier class. $nav.addClass('-length-'+$breadcrumbLength); # Root class # If current element exists and is not top level item. if $current.length && $breadcrumbLength > 1 then $root = $navUl.children('.'+settings.breadcrumbClass).addClass(settings.rootClass) else $root = $nav.addClass(settings.firstLevelClass) # Set item classes in the markup addItemClasses = -> $navUl.find("li").addClass(settings.itemClass) # Set parent classes in the markup addParentClasses = -> $navUl.find(">li").each -> if $(@).has("ul").length $(@).addClass(settings.topModifier) $topParents = $topParents.add($(@)) $navUl.find("ul li").each -> if $(@).has("ul").length $(@).addClass(settings.parentModifier) $parents = $parents.add($(@)) # Add in touch buttons addButtons = -> if $navUl.children('li').length > 1 $nav.addClass(settings.multipleRootsClass) $navUl.before($button.clone().addClass(settings.rootsModifier)) $navUl.after($button.clone().addClass(settings.mainModifier)) $topParentButtons = $button.clone().addClass(settings.topModifier).appendTo($topParents) $parentButtons = $button.clone().addClass(settings.parentModifier).appendTo($parents) getCloseElements = -> $nav.add($parents).add($topParents) getOpenElements = -> if $breadcrumbLength = 1 then $nav.add($breadcrumb) else $nav.add($breadcrumb).not($current) closeMenu = -> close(getCloseElements()) if $nav.hasClass(settings.largeModifier) addMoreMenu() calcWidth() openMenu = -> open(getOpenElements()) removeMoreMenu() open = (elements) -> elements.removeClass(settings.closedClass).addClass(settings.openClass) close = (elements) -> elements.removeClass(settings.openClass).addClass(settings.closedClass) closeRootsMenu = -> $nav.removeClass(settings.rootsOpenClass).addClass(settings.rootsClosedClass) $nav.find('.'+settings.rootsOpenClass).removeClass(settings.rootsOpenClass).addClass(settings.rootsClosedClass) openRootsMenu = -> $nav.removeClass(settings.rootsClosedClass).addClass(settings.rootsOpenClass) .children('ul').children('li').removeClass(settings.rootsClosedClass).addClass(settings.rootsOpenClass) $nav.children('.'+settings.rootsModifier).removeClass(settings.rootsClosedClass).addClass(settings.rootsOpenClass) addListeners = -> # Toggle touch for nav menu $('> .'+settings.mainModifier, $nav).on('click', (e) -> e.stopPropagation() e.preventDefault() if $nav.hasClass(settings.openClass) closeMenu() else closeRootsMenu() openMenu() ) # Toggle for top parent menus $topParentButtons.on('click', (e) -> e.stopPropagation() e.preventDefault() # remove openClass from all elements that are not current $parent = $(@).parent('li') if $parent.hasClass(settings.openClass) close($parent) else close($parent.siblings()) open($parent) ) # Toggle for parent menus $parentButtons.on('click', (e) -> e.stopPropagation() e.preventDefault() $parent = $(@).parent('li') if $parent.hasClass(settings.openClass) close($parent) else open($parent) ) # Toggle moreMenu $('.'+settings.moreModifier,$moreMenu).click((e) -> e.stopPropagation() e.preventDefault() if $moreMenu.hasClass(settings.openClass) close($moreMenu) else open($moreMenu) ) # Toggle touch for roots menu $nav.children('.'+settings.rootsModifier).on('click', (e) -> e.stopPropagation() e.preventDefault() if $nav.hasClass(settings.rootsOpenClass) is true closeRootsMenu() else closeMenu() openRootsMenu() ) addMoreMenu = -> $currentChildMenu = $($breadcrumb[$breadcrumb.length - 2]).find('> ul') if $currentChildMenu.length $currentChildMenu.append($moreMenu) removeMoreMenu = -> if $.contains(document.documentElement, $moreMenu[0]) $('> ul > li', $moreMenu).each(-> $(@).insertBefore($moreMenu) ) $moreMenu.detach() calcWidth = -> if $currentChildMenu.length navWidth = 0; moreMenuWidth = $moreMenu.outerWidth(true) $visibleMenuItems = $currentChildMenu.children('li').not($moreMenu) $visibleMenuItems.each(-> navWidth += $(@).outerWidth( true ) ) availableSpace = $currentChildMenu.outerWidth(true) - $('>li',$currentChildMenu)[0].offsetLeft - moreMenuWidth - 50; if (navWidth > availableSpace) lastItem = $visibleMenuItems.last() lastItem.attr('data-width', lastItem.outerWidth(true)) lastItem.prependTo($('> ul', $moreMenu)) calcWidth() else firstMoreElement = $('> ul > li', $moreMenu).first(); if navWidth + firstMoreElement.data('width') < availableSpace firstMoreElement.insertBefore($moreMenu) if $('> ul >li', $moreMenu).length $moreMenu.css('display','block') else $moreMenu.css('display','none') # Get the breakpoint set with data-breakpoint if $nav.data('breakpoint') then breakpoint = $nav.data('breakpoint') resizer = -> if $(window).width() <= breakpoint $nav.removeClass(settings.largeModifier) closeMenu() if $.contains(document.documentElement, $moreMenu[0]) removeMoreMenu() else $nav.addClass(settings.largeModifier) closeMenu() if not $.contains(document.documentElement, $moreMenu[0]) addMoreMenu() calcWidth() @.makeNav = -> $current = $('li.'+settings.currentClass, $navUl) addItemClasses() addParentClasses() addBreadcrumbClasses() addButtons() closeMenu() closeRootsMenu() # Call once to set resizer() addListeners() @.makeNav() # Call on browser resize $(window).on('resize', resizer) @
72324
### crumbnav.js 0.1 Created by <NAME> Based on flexnav by <NAME> http://jasonweaver.name Released under http://unlicense.org/ ### # TODO Hide contextual menu button (+) when there's only on child in the submenu require('./sass/crumbnav.scss') # Use local alias for $.noConflict() compatibility $ = jQuery $('html').removeClass('no-js').addClass('js') $ -> #attachFastClick = Origami.fastclick; #attachFastClick(document.body); $.fn.crumbnav = (options) -> settings = $.extend({ 'navClass': 'c-nav', 'titleClass': 'title', 'topModifier': '-top', 'itemClass': 'c-item', 'openClass': 'cn-open', 'closedClass': 'cn-close', 'rootsOpenClass': 'cn-open-roots', 'rootsClosedClass': 'cn-close-roots', 'firstLevelClass': 'crumbnav--first-level', 'rootClass': 'crumbnav__root', 'currentClass': 'active' 'moreMenuClass': 'c-more', 'popupClass': 'popup', 'breadcrumbClass': 'crumbnav-crumb', 'buttonClass': 'c-button', 'mainModifier': '-main', 'parentModifier': '-parent', 'moreModifier': '-more', 'rootsModifier': '-roots', 'largeModifier': '-large', 'hoverIntent': false, 'hoverIntentTimeout': 150, 'calcItemWidths': false, 'hover': false, 'titleText': 'Menu', }, options ) @.options = settings $nav = $(@) # TODO Add support for multiple menus? At the moment breaks javascript execution! $navUl = if $nav.children('ul').length == 1 then $nav.children('ul') else alert("Unsupported number of ul's inside the navigation!"); $current = $('li.'+settings.currentClass, $navUl) if $current.length > 1 then alert('Multiple active elements in the menu! There should be only one.') $root = $() $topParents = $() $parents = $() $breadcrumb = $() $breadcrumbLength = 0 $currentChildMenu = $() $topParentButtons = $() $parentButtons = $() $moreMenu = $() # TODO Should we use a button element? $button = $('<span class="'+settings.buttonClass+'"><i></i></span>') $moreMenu = $('<li class="'+settings.moreMenuClass+'"><ul class="'+settings.popupClass+'"></ul></li>').append($button.clone().addClass(settings.moreModifier)) # Add title if not present if $nav.children('.'+settings.titleClass).length == 0 $nav.prepend('<div class="'+settings.titleClass+'">'+settings.titleText+'</div>') addBreadcrumbClasses = -> # Breadcrumb trail $currentParents = $current.parentsUntil($navUl, 'li') $breadcrumb = $currentParents.add($current) $breadcrumbLength = $breadcrumb.length $breadcrumb .addClass(settings.breadcrumbClass) .each (index) -> $(@).addClass('-out-'+index+' -in-'+($breadcrumbLength - index - 1)) # Breadcrumb length modifier class. $nav.addClass('-length-'+$breadcrumbLength); # Root class # If current element exists and is not top level item. if $current.length && $breadcrumbLength > 1 then $root = $navUl.children('.'+settings.breadcrumbClass).addClass(settings.rootClass) else $root = $nav.addClass(settings.firstLevelClass) # Set item classes in the markup addItemClasses = -> $navUl.find("li").addClass(settings.itemClass) # Set parent classes in the markup addParentClasses = -> $navUl.find(">li").each -> if $(@).has("ul").length $(@).addClass(settings.topModifier) $topParents = $topParents.add($(@)) $navUl.find("ul li").each -> if $(@).has("ul").length $(@).addClass(settings.parentModifier) $parents = $parents.add($(@)) # Add in touch buttons addButtons = -> if $navUl.children('li').length > 1 $nav.addClass(settings.multipleRootsClass) $navUl.before($button.clone().addClass(settings.rootsModifier)) $navUl.after($button.clone().addClass(settings.mainModifier)) $topParentButtons = $button.clone().addClass(settings.topModifier).appendTo($topParents) $parentButtons = $button.clone().addClass(settings.parentModifier).appendTo($parents) getCloseElements = -> $nav.add($parents).add($topParents) getOpenElements = -> if $breadcrumbLength = 1 then $nav.add($breadcrumb) else $nav.add($breadcrumb).not($current) closeMenu = -> close(getCloseElements()) if $nav.hasClass(settings.largeModifier) addMoreMenu() calcWidth() openMenu = -> open(getOpenElements()) removeMoreMenu() open = (elements) -> elements.removeClass(settings.closedClass).addClass(settings.openClass) close = (elements) -> elements.removeClass(settings.openClass).addClass(settings.closedClass) closeRootsMenu = -> $nav.removeClass(settings.rootsOpenClass).addClass(settings.rootsClosedClass) $nav.find('.'+settings.rootsOpenClass).removeClass(settings.rootsOpenClass).addClass(settings.rootsClosedClass) openRootsMenu = -> $nav.removeClass(settings.rootsClosedClass).addClass(settings.rootsOpenClass) .children('ul').children('li').removeClass(settings.rootsClosedClass).addClass(settings.rootsOpenClass) $nav.children('.'+settings.rootsModifier).removeClass(settings.rootsClosedClass).addClass(settings.rootsOpenClass) addListeners = -> # Toggle touch for nav menu $('> .'+settings.mainModifier, $nav).on('click', (e) -> e.stopPropagation() e.preventDefault() if $nav.hasClass(settings.openClass) closeMenu() else closeRootsMenu() openMenu() ) # Toggle for top parent menus $topParentButtons.on('click', (e) -> e.stopPropagation() e.preventDefault() # remove openClass from all elements that are not current $parent = $(@).parent('li') if $parent.hasClass(settings.openClass) close($parent) else close($parent.siblings()) open($parent) ) # Toggle for parent menus $parentButtons.on('click', (e) -> e.stopPropagation() e.preventDefault() $parent = $(@).parent('li') if $parent.hasClass(settings.openClass) close($parent) else open($parent) ) # Toggle moreMenu $('.'+settings.moreModifier,$moreMenu).click((e) -> e.stopPropagation() e.preventDefault() if $moreMenu.hasClass(settings.openClass) close($moreMenu) else open($moreMenu) ) # Toggle touch for roots menu $nav.children('.'+settings.rootsModifier).on('click', (e) -> e.stopPropagation() e.preventDefault() if $nav.hasClass(settings.rootsOpenClass) is true closeRootsMenu() else closeMenu() openRootsMenu() ) addMoreMenu = -> $currentChildMenu = $($breadcrumb[$breadcrumb.length - 2]).find('> ul') if $currentChildMenu.length $currentChildMenu.append($moreMenu) removeMoreMenu = -> if $.contains(document.documentElement, $moreMenu[0]) $('> ul > li', $moreMenu).each(-> $(@).insertBefore($moreMenu) ) $moreMenu.detach() calcWidth = -> if $currentChildMenu.length navWidth = 0; moreMenuWidth = $moreMenu.outerWidth(true) $visibleMenuItems = $currentChildMenu.children('li').not($moreMenu) $visibleMenuItems.each(-> navWidth += $(@).outerWidth( true ) ) availableSpace = $currentChildMenu.outerWidth(true) - $('>li',$currentChildMenu)[0].offsetLeft - moreMenuWidth - 50; if (navWidth > availableSpace) lastItem = $visibleMenuItems.last() lastItem.attr('data-width', lastItem.outerWidth(true)) lastItem.prependTo($('> ul', $moreMenu)) calcWidth() else firstMoreElement = $('> ul > li', $moreMenu).first(); if navWidth + firstMoreElement.data('width') < availableSpace firstMoreElement.insertBefore($moreMenu) if $('> ul >li', $moreMenu).length $moreMenu.css('display','block') else $moreMenu.css('display','none') # Get the breakpoint set with data-breakpoint if $nav.data('breakpoint') then breakpoint = $nav.data('breakpoint') resizer = -> if $(window).width() <= breakpoint $nav.removeClass(settings.largeModifier) closeMenu() if $.contains(document.documentElement, $moreMenu[0]) removeMoreMenu() else $nav.addClass(settings.largeModifier) closeMenu() if not $.contains(document.documentElement, $moreMenu[0]) addMoreMenu() calcWidth() @.makeNav = -> $current = $('li.'+settings.currentClass, $navUl) addItemClasses() addParentClasses() addBreadcrumbClasses() addButtons() closeMenu() closeRootsMenu() # Call once to set resizer() addListeners() @.makeNav() # Call on browser resize $(window).on('resize', resizer) @
true
### crumbnav.js 0.1 Created by PI:NAME:<NAME>END_PI Based on flexnav by PI:NAME:<NAME>END_PI http://jasonweaver.name Released under http://unlicense.org/ ### # TODO Hide contextual menu button (+) when there's only on child in the submenu require('./sass/crumbnav.scss') # Use local alias for $.noConflict() compatibility $ = jQuery $('html').removeClass('no-js').addClass('js') $ -> #attachFastClick = Origami.fastclick; #attachFastClick(document.body); $.fn.crumbnav = (options) -> settings = $.extend({ 'navClass': 'c-nav', 'titleClass': 'title', 'topModifier': '-top', 'itemClass': 'c-item', 'openClass': 'cn-open', 'closedClass': 'cn-close', 'rootsOpenClass': 'cn-open-roots', 'rootsClosedClass': 'cn-close-roots', 'firstLevelClass': 'crumbnav--first-level', 'rootClass': 'crumbnav__root', 'currentClass': 'active' 'moreMenuClass': 'c-more', 'popupClass': 'popup', 'breadcrumbClass': 'crumbnav-crumb', 'buttonClass': 'c-button', 'mainModifier': '-main', 'parentModifier': '-parent', 'moreModifier': '-more', 'rootsModifier': '-roots', 'largeModifier': '-large', 'hoverIntent': false, 'hoverIntentTimeout': 150, 'calcItemWidths': false, 'hover': false, 'titleText': 'Menu', }, options ) @.options = settings $nav = $(@) # TODO Add support for multiple menus? At the moment breaks javascript execution! $navUl = if $nav.children('ul').length == 1 then $nav.children('ul') else alert("Unsupported number of ul's inside the navigation!"); $current = $('li.'+settings.currentClass, $navUl) if $current.length > 1 then alert('Multiple active elements in the menu! There should be only one.') $root = $() $topParents = $() $parents = $() $breadcrumb = $() $breadcrumbLength = 0 $currentChildMenu = $() $topParentButtons = $() $parentButtons = $() $moreMenu = $() # TODO Should we use a button element? $button = $('<span class="'+settings.buttonClass+'"><i></i></span>') $moreMenu = $('<li class="'+settings.moreMenuClass+'"><ul class="'+settings.popupClass+'"></ul></li>').append($button.clone().addClass(settings.moreModifier)) # Add title if not present if $nav.children('.'+settings.titleClass).length == 0 $nav.prepend('<div class="'+settings.titleClass+'">'+settings.titleText+'</div>') addBreadcrumbClasses = -> # Breadcrumb trail $currentParents = $current.parentsUntil($navUl, 'li') $breadcrumb = $currentParents.add($current) $breadcrumbLength = $breadcrumb.length $breadcrumb .addClass(settings.breadcrumbClass) .each (index) -> $(@).addClass('-out-'+index+' -in-'+($breadcrumbLength - index - 1)) # Breadcrumb length modifier class. $nav.addClass('-length-'+$breadcrumbLength); # Root class # If current element exists and is not top level item. if $current.length && $breadcrumbLength > 1 then $root = $navUl.children('.'+settings.breadcrumbClass).addClass(settings.rootClass) else $root = $nav.addClass(settings.firstLevelClass) # Set item classes in the markup addItemClasses = -> $navUl.find("li").addClass(settings.itemClass) # Set parent classes in the markup addParentClasses = -> $navUl.find(">li").each -> if $(@).has("ul").length $(@).addClass(settings.topModifier) $topParents = $topParents.add($(@)) $navUl.find("ul li").each -> if $(@).has("ul").length $(@).addClass(settings.parentModifier) $parents = $parents.add($(@)) # Add in touch buttons addButtons = -> if $navUl.children('li').length > 1 $nav.addClass(settings.multipleRootsClass) $navUl.before($button.clone().addClass(settings.rootsModifier)) $navUl.after($button.clone().addClass(settings.mainModifier)) $topParentButtons = $button.clone().addClass(settings.topModifier).appendTo($topParents) $parentButtons = $button.clone().addClass(settings.parentModifier).appendTo($parents) getCloseElements = -> $nav.add($parents).add($topParents) getOpenElements = -> if $breadcrumbLength = 1 then $nav.add($breadcrumb) else $nav.add($breadcrumb).not($current) closeMenu = -> close(getCloseElements()) if $nav.hasClass(settings.largeModifier) addMoreMenu() calcWidth() openMenu = -> open(getOpenElements()) removeMoreMenu() open = (elements) -> elements.removeClass(settings.closedClass).addClass(settings.openClass) close = (elements) -> elements.removeClass(settings.openClass).addClass(settings.closedClass) closeRootsMenu = -> $nav.removeClass(settings.rootsOpenClass).addClass(settings.rootsClosedClass) $nav.find('.'+settings.rootsOpenClass).removeClass(settings.rootsOpenClass).addClass(settings.rootsClosedClass) openRootsMenu = -> $nav.removeClass(settings.rootsClosedClass).addClass(settings.rootsOpenClass) .children('ul').children('li').removeClass(settings.rootsClosedClass).addClass(settings.rootsOpenClass) $nav.children('.'+settings.rootsModifier).removeClass(settings.rootsClosedClass).addClass(settings.rootsOpenClass) addListeners = -> # Toggle touch for nav menu $('> .'+settings.mainModifier, $nav).on('click', (e) -> e.stopPropagation() e.preventDefault() if $nav.hasClass(settings.openClass) closeMenu() else closeRootsMenu() openMenu() ) # Toggle for top parent menus $topParentButtons.on('click', (e) -> e.stopPropagation() e.preventDefault() # remove openClass from all elements that are not current $parent = $(@).parent('li') if $parent.hasClass(settings.openClass) close($parent) else close($parent.siblings()) open($parent) ) # Toggle for parent menus $parentButtons.on('click', (e) -> e.stopPropagation() e.preventDefault() $parent = $(@).parent('li') if $parent.hasClass(settings.openClass) close($parent) else open($parent) ) # Toggle moreMenu $('.'+settings.moreModifier,$moreMenu).click((e) -> e.stopPropagation() e.preventDefault() if $moreMenu.hasClass(settings.openClass) close($moreMenu) else open($moreMenu) ) # Toggle touch for roots menu $nav.children('.'+settings.rootsModifier).on('click', (e) -> e.stopPropagation() e.preventDefault() if $nav.hasClass(settings.rootsOpenClass) is true closeRootsMenu() else closeMenu() openRootsMenu() ) addMoreMenu = -> $currentChildMenu = $($breadcrumb[$breadcrumb.length - 2]).find('> ul') if $currentChildMenu.length $currentChildMenu.append($moreMenu) removeMoreMenu = -> if $.contains(document.documentElement, $moreMenu[0]) $('> ul > li', $moreMenu).each(-> $(@).insertBefore($moreMenu) ) $moreMenu.detach() calcWidth = -> if $currentChildMenu.length navWidth = 0; moreMenuWidth = $moreMenu.outerWidth(true) $visibleMenuItems = $currentChildMenu.children('li').not($moreMenu) $visibleMenuItems.each(-> navWidth += $(@).outerWidth( true ) ) availableSpace = $currentChildMenu.outerWidth(true) - $('>li',$currentChildMenu)[0].offsetLeft - moreMenuWidth - 50; if (navWidth > availableSpace) lastItem = $visibleMenuItems.last() lastItem.attr('data-width', lastItem.outerWidth(true)) lastItem.prependTo($('> ul', $moreMenu)) calcWidth() else firstMoreElement = $('> ul > li', $moreMenu).first(); if navWidth + firstMoreElement.data('width') < availableSpace firstMoreElement.insertBefore($moreMenu) if $('> ul >li', $moreMenu).length $moreMenu.css('display','block') else $moreMenu.css('display','none') # Get the breakpoint set with data-breakpoint if $nav.data('breakpoint') then breakpoint = $nav.data('breakpoint') resizer = -> if $(window).width() <= breakpoint $nav.removeClass(settings.largeModifier) closeMenu() if $.contains(document.documentElement, $moreMenu[0]) removeMoreMenu() else $nav.addClass(settings.largeModifier) closeMenu() if not $.contains(document.documentElement, $moreMenu[0]) addMoreMenu() calcWidth() @.makeNav = -> $current = $('li.'+settings.currentClass, $navUl) addItemClasses() addParentClasses() addBreadcrumbClasses() addButtons() closeMenu() closeRootsMenu() # Call once to set resizer() addListeners() @.makeNav() # Call on browser resize $(window).on('resize', resizer) @
[ { "context": "n_authentication = json.tycoon_authentication || 'password'\n metadata.planets_metadata = _.map(json.plane", "end": 793, "score": 0.8078563213348389, "start": 785, "tag": "PASSWORD", "value": "password" } ]
plugins/starpeace-client/galaxy/metadata-galaxy.coffee
Eric1212/starpeace-website-client
0
import _ from 'lodash' import moment from 'moment' import MetadataPlanet from '~/plugins/starpeace-client/planet/metadata-planet.coffee' import TimeUtils from '~/plugins/starpeace-client/utils/time-utils.coffee' export default class MetadataGalaxy constructor: (@id) -> @as_of = new Date() @planets_metadata = [] Object.defineProperties @prototype, planet_count: get: -> @planets_metadata.length online_count: get: -> _.sumBy(@planets_metadata, 'online_count') @from_json: (json) -> metadata = new MetadataGalaxy(json.id) metadata.name = json.name metadata.visitor_enabled = json.visitor_enabled || false metadata.tycoon_enabled = json.tycoon_enabled || false metadata.tycoon_authentication = json.tycoon_authentication || 'password' metadata.planets_metadata = _.map(json.planets_metadata, MetadataPlanet.from_json) metadata
122113
import _ from 'lodash' import moment from 'moment' import MetadataPlanet from '~/plugins/starpeace-client/planet/metadata-planet.coffee' import TimeUtils from '~/plugins/starpeace-client/utils/time-utils.coffee' export default class MetadataGalaxy constructor: (@id) -> @as_of = new Date() @planets_metadata = [] Object.defineProperties @prototype, planet_count: get: -> @planets_metadata.length online_count: get: -> _.sumBy(@planets_metadata, 'online_count') @from_json: (json) -> metadata = new MetadataGalaxy(json.id) metadata.name = json.name metadata.visitor_enabled = json.visitor_enabled || false metadata.tycoon_enabled = json.tycoon_enabled || false metadata.tycoon_authentication = json.tycoon_authentication || '<PASSWORD>' metadata.planets_metadata = _.map(json.planets_metadata, MetadataPlanet.from_json) metadata
true
import _ from 'lodash' import moment from 'moment' import MetadataPlanet from '~/plugins/starpeace-client/planet/metadata-planet.coffee' import TimeUtils from '~/plugins/starpeace-client/utils/time-utils.coffee' export default class MetadataGalaxy constructor: (@id) -> @as_of = new Date() @planets_metadata = [] Object.defineProperties @prototype, planet_count: get: -> @planets_metadata.length online_count: get: -> _.sumBy(@planets_metadata, 'online_count') @from_json: (json) -> metadata = new MetadataGalaxy(json.id) metadata.name = json.name metadata.visitor_enabled = json.visitor_enabled || false metadata.tycoon_enabled = json.tycoon_enabled || false metadata.tycoon_authentication = json.tycoon_authentication || 'PI:PASSWORD:<PASSWORD>END_PI' metadata.planets_metadata = _.map(json.planets_metadata, MetadataPlanet.from_json) metadata
[ { "context": "ievement is earned by spending gold.\n *\n * @name Consumerist\n * @prerequisite Spend 100000*[3*[n-1]+1] total ", "end": 162, "score": 0.8442814350128174, "start": 151, "tag": "NAME", "value": "Consumerist" }, { "context": " >= currentCheckValue\n item =\n ...
src/character/achievements/Consumerist.coffee
jawsome/IdleLands
3
Achievement = require "../base/Achievement" {toRoman} = require "roman-numerals" `/** * This achievement is earned by spending gold. * * @name Consumerist * @prerequisite Spend 100000*[3*[n-1]+1] total gold. * @reward +0.07 itemSellMultiplier * @reward +1 inventory slot (This only applies once for every 3 levels of Consumerist.) * @category Achievements * @package Player */` class Consumerist extends Achievement getAllAchievedFor: (player) -> baseStat = player.statistics['calculated total gold spent'] currentCheckValue = 100000 multiplier = 3 level = 1 achieved = [] while baseStat >= currentCheckValue item = name: "Consumerist #{toRoman level}" desc: "Spend #{currentCheckValue} total gold" reward: "+0.07 itemSellMultiplier" itemSellMultiplier: -> level*0.07 type: "event" item.title = "Consumerist" if level is 5 if level%%3 is 0 item.inventorySize = -> 1 achieved.push item currentCheckValue *= multiplier level++ achieved module.exports = exports = Consumerist
204429
Achievement = require "../base/Achievement" {toRoman} = require "roman-numerals" `/** * This achievement is earned by spending gold. * * @name <NAME> * @prerequisite Spend 100000*[3*[n-1]+1] total gold. * @reward +0.07 itemSellMultiplier * @reward +1 inventory slot (This only applies once for every 3 levels of Consumerist.) * @category Achievements * @package Player */` class Consumerist extends Achievement getAllAchievedFor: (player) -> baseStat = player.statistics['calculated total gold spent'] currentCheckValue = 100000 multiplier = 3 level = 1 achieved = [] while baseStat >= currentCheckValue item = name: "<NAME> #{toRoman level}" desc: "Spend #{currentCheckValue} total gold" reward: "+0.07 itemSellMultiplier" itemSellMultiplier: -> level*0.07 type: "event" item.title = "Consumerist" if level is 5 if level%%3 is 0 item.inventorySize = -> 1 achieved.push item currentCheckValue *= multiplier level++ achieved module.exports = exports = Consumerist
true
Achievement = require "../base/Achievement" {toRoman} = require "roman-numerals" `/** * This achievement is earned by spending gold. * * @name PI:NAME:<NAME>END_PI * @prerequisite Spend 100000*[3*[n-1]+1] total gold. * @reward +0.07 itemSellMultiplier * @reward +1 inventory slot (This only applies once for every 3 levels of Consumerist.) * @category Achievements * @package Player */` class Consumerist extends Achievement getAllAchievedFor: (player) -> baseStat = player.statistics['calculated total gold spent'] currentCheckValue = 100000 multiplier = 3 level = 1 achieved = [] while baseStat >= currentCheckValue item = name: "PI:NAME:<NAME>END_PI #{toRoman level}" desc: "Spend #{currentCheckValue} total gold" reward: "+0.07 itemSellMultiplier" itemSellMultiplier: -> level*0.07 type: "event" item.title = "Consumerist" if level is 5 if level%%3 is 0 item.inventorySize = -> 1 achieved.push item currentCheckValue *= multiplier level++ achieved module.exports = exports = Consumerist
[ { "context": "/users', city: 'New York'\n#\n# User.where(name: 'John').then (users) ->\n# alert 'You are a New York", "end": 192, "score": 0.9994810223579407, "start": 188, "tag": "NAME", "value": "John" }, { "context": "users) ->\n# alert 'You are a New Yorker called John'...
src/databound.coffee
EduardoluizSanBlasDeveloper0/ROR-crud-example
506
_ = require 'lodash' jQuery = require 'jquery' # You can specify scope for the connection. # # ```coffeescript # User = new Databound '/users', city: 'New York' # # User.where(name: 'John').then (users) -> # alert 'You are a New Yorker called John' # # User.create(name: 'Peter').then (new_user) -> # # I am from New York # alert "I am from #{new_user.city}" # ``` class Databound constructor: (@endpoint, @scope = {}, @options = {}) -> @extra_where_scopes = @options.extra_where_scopes or [] @records = [] @seeds = [] @properties = [] # ## Start of Configs # Functions ``request`` and ``promise`` are overritable Databound.API_URL = "" # Does a POST request and returns a ``promise`` request: (action, params) -> jQuery.post @url(action), @data(params), 'json' # Returns a ``promise`` which resolves with ``result`` promise: (result) -> deferred = jQuery.Deferred() deferred.resolve result deferred.promise() # ## End of Configs where: (params) -> _this = @ @wrappedRequest('where', params).then (resp) -> records = JSON.parse(resp.records).concat(_this.seeds) _this.records = _.sortBy(records, 'id') _this.promise _this.records all: -> @where() # Return a single record by ``id`` # # ```coffeescript # User.find(15).then (user) -> # alert "Yo, #{user.name}" # ``` find: (id) -> @checkUndefinedId('find', id) _this = @ @where(id: id).then -> record = _this.take(id) unless record throw new DataboundError("Couldn't find record with id: #{id}") _this.promise record # Return a single record by ``params`` # # ```coffeescript # User.findBy(name: 'John', city: 'New York').then (user) -> # alert "I'm John from New York" # ``` findBy: (params) -> _this = @ @where(params).then (resp) -> _this.promise _.first(_.values(resp)) create: (params) -> @requestAndRefresh 'create', params # Specify ``id`` when updating or destroying the record. # # ```coffeescript # User = new Databound '/users' # # User.update(id: 15, name: 'Saint John').then (updated_user) -> # alert updated_user # # User.destroy(15).then (resp) -> # alert resp.success # ``` update: (params) -> @requestAndRefresh 'update', params destroy: (id) -> @checkUndefinedId('destroy', id) @requestAndRefresh 'destroy', id: id # Just take already dowloaded records take: (id) -> _.detect @records, (record) -> id.toString() == record.id.toString() takeAll: -> @records # f.e. Have default records injectSeedRecords: (records) -> @seeds = records requestAndRefresh: (action, params) -> _this = @ # backend responds with: # # ```javascript # { # success: true, # id: record.id, # scoped_records: [] # } # ``` @wrappedRequest(action, params).then (resp) -> records = JSON.parse(resp.scoped_records) records_with_seeds = records.concat(_this.seeds) _this.records = _.sortBy(records_with_seeds, 'id') if resp.id _this.promise _this.take(resp.id) else _this.promise resp.success url: (action) -> if _.isEmpty(Databound.API_URL) "#{@endpoint}/#{action}" else "#{Databound.API_URL}/#{@endpoint}/#{action}" data: (params) -> scope: JSON.stringify(@scope) extra_where_scopes: JSON.stringify(@extra_where_scopes) data: JSON.stringify(params) wrappedRequest: (args...) -> @request(args...).then(_.bind(@handleSuccess, @)).fail(@handleFailure) handleSuccess: (resp) -> throw new Error 'Error in the backend' unless resp?.success @promise(resp) handleFailure: (e) -> if e.status == DataboundError.STATUS throw new DataboundError(e.responseJSON.message) else throw new Error "Error in the backend with status #{e.status}" checkUndefinedId: (action, id) -> return unless _.isUndefined(id) throw new DataboundError("Couldn't #{action} a record without an id") class DataboundError constructor: (text) -> @message = "Databound: #{text}" @STATUS: 405 DataboundError:: = new Error() module.exports = Databound
80781
_ = require 'lodash' jQuery = require 'jquery' # You can specify scope for the connection. # # ```coffeescript # User = new Databound '/users', city: 'New York' # # User.where(name: '<NAME>').then (users) -> # alert 'You are a New Yorker called <NAME>' # # User.create(name: '<NAME>').then (new_user) -> # # I am from New York # alert "I am from #{new_user.city}" # ``` class Databound constructor: (@endpoint, @scope = {}, @options = {}) -> @extra_where_scopes = @options.extra_where_scopes or [] @records = [] @seeds = [] @properties = [] # ## Start of Configs # Functions ``request`` and ``promise`` are overritable Databound.API_URL = "" # Does a POST request and returns a ``promise`` request: (action, params) -> jQuery.post @url(action), @data(params), 'json' # Returns a ``promise`` which resolves with ``result`` promise: (result) -> deferred = jQuery.Deferred() deferred.resolve result deferred.promise() # ## End of Configs where: (params) -> _this = @ @wrappedRequest('where', params).then (resp) -> records = JSON.parse(resp.records).concat(_this.seeds) _this.records = _.sortBy(records, 'id') _this.promise _this.records all: -> @where() # Return a single record by ``id`` # # ```coffeescript # User.find(15).then (user) -> # alert "Yo, #{user.name}" # ``` find: (id) -> @checkUndefinedId('find', id) _this = @ @where(id: id).then -> record = _this.take(id) unless record throw new DataboundError("Couldn't find record with id: #{id}") _this.promise record # Return a single record by ``params`` # # ```coffeescript # User.findBy(name: '<NAME>', city: 'New York').then (user) -> # alert "I'm <NAME> from New York" # ``` findBy: (params) -> _this = @ @where(params).then (resp) -> _this.promise _.first(_.values(resp)) create: (params) -> @requestAndRefresh 'create', params # Specify ``id`` when updating or destroying the record. # # ```coffeescript # User = new Databound '/users' # # User.update(id: 15, name: '<NAME>').then (updated_user) -> # alert updated_user # # User.destroy(15).then (resp) -> # alert resp.success # ``` update: (params) -> @requestAndRefresh 'update', params destroy: (id) -> @checkUndefinedId('destroy', id) @requestAndRefresh 'destroy', id: id # Just take already dowloaded records take: (id) -> _.detect @records, (record) -> id.toString() == record.id.toString() takeAll: -> @records # f.e. Have default records injectSeedRecords: (records) -> @seeds = records requestAndRefresh: (action, params) -> _this = @ # backend responds with: # # ```javascript # { # success: true, # id: record.id, # scoped_records: [] # } # ``` @wrappedRequest(action, params).then (resp) -> records = JSON.parse(resp.scoped_records) records_with_seeds = records.concat(_this.seeds) _this.records = _.sortBy(records_with_seeds, 'id') if resp.id _this.promise _this.take(resp.id) else _this.promise resp.success url: (action) -> if _.isEmpty(Databound.API_URL) "#{@endpoint}/#{action}" else "#{Databound.API_URL}/#{@endpoint}/#{action}" data: (params) -> scope: JSON.stringify(@scope) extra_where_scopes: JSON.stringify(@extra_where_scopes) data: JSON.stringify(params) wrappedRequest: (args...) -> @request(args...).then(_.bind(@handleSuccess, @)).fail(@handleFailure) handleSuccess: (resp) -> throw new Error 'Error in the backend' unless resp?.success @promise(resp) handleFailure: (e) -> if e.status == DataboundError.STATUS throw new DataboundError(e.responseJSON.message) else throw new Error "Error in the backend with status #{e.status}" checkUndefinedId: (action, id) -> return unless _.isUndefined(id) throw new DataboundError("Couldn't #{action} a record without an id") class DataboundError constructor: (text) -> @message = "Databound: #{text}" @STATUS: 405 DataboundError:: = new Error() module.exports = Databound
true
_ = require 'lodash' jQuery = require 'jquery' # You can specify scope for the connection. # # ```coffeescript # User = new Databound '/users', city: 'New York' # # User.where(name: 'PI:NAME:<NAME>END_PI').then (users) -> # alert 'You are a New Yorker called PI:NAME:<NAME>END_PI' # # User.create(name: 'PI:NAME:<NAME>END_PI').then (new_user) -> # # I am from New York # alert "I am from #{new_user.city}" # ``` class Databound constructor: (@endpoint, @scope = {}, @options = {}) -> @extra_where_scopes = @options.extra_where_scopes or [] @records = [] @seeds = [] @properties = [] # ## Start of Configs # Functions ``request`` and ``promise`` are overritable Databound.API_URL = "" # Does a POST request and returns a ``promise`` request: (action, params) -> jQuery.post @url(action), @data(params), 'json' # Returns a ``promise`` which resolves with ``result`` promise: (result) -> deferred = jQuery.Deferred() deferred.resolve result deferred.promise() # ## End of Configs where: (params) -> _this = @ @wrappedRequest('where', params).then (resp) -> records = JSON.parse(resp.records).concat(_this.seeds) _this.records = _.sortBy(records, 'id') _this.promise _this.records all: -> @where() # Return a single record by ``id`` # # ```coffeescript # User.find(15).then (user) -> # alert "Yo, #{user.name}" # ``` find: (id) -> @checkUndefinedId('find', id) _this = @ @where(id: id).then -> record = _this.take(id) unless record throw new DataboundError("Couldn't find record with id: #{id}") _this.promise record # Return a single record by ``params`` # # ```coffeescript # User.findBy(name: 'PI:NAME:<NAME>END_PI', city: 'New York').then (user) -> # alert "I'm PI:NAME:<NAME>END_PI from New York" # ``` findBy: (params) -> _this = @ @where(params).then (resp) -> _this.promise _.first(_.values(resp)) create: (params) -> @requestAndRefresh 'create', params # Specify ``id`` when updating or destroying the record. # # ```coffeescript # User = new Databound '/users' # # User.update(id: 15, name: 'PI:NAME:<NAME>END_PI').then (updated_user) -> # alert updated_user # # User.destroy(15).then (resp) -> # alert resp.success # ``` update: (params) -> @requestAndRefresh 'update', params destroy: (id) -> @checkUndefinedId('destroy', id) @requestAndRefresh 'destroy', id: id # Just take already dowloaded records take: (id) -> _.detect @records, (record) -> id.toString() == record.id.toString() takeAll: -> @records # f.e. Have default records injectSeedRecords: (records) -> @seeds = records requestAndRefresh: (action, params) -> _this = @ # backend responds with: # # ```javascript # { # success: true, # id: record.id, # scoped_records: [] # } # ``` @wrappedRequest(action, params).then (resp) -> records = JSON.parse(resp.scoped_records) records_with_seeds = records.concat(_this.seeds) _this.records = _.sortBy(records_with_seeds, 'id') if resp.id _this.promise _this.take(resp.id) else _this.promise resp.success url: (action) -> if _.isEmpty(Databound.API_URL) "#{@endpoint}/#{action}" else "#{Databound.API_URL}/#{@endpoint}/#{action}" data: (params) -> scope: JSON.stringify(@scope) extra_where_scopes: JSON.stringify(@extra_where_scopes) data: JSON.stringify(params) wrappedRequest: (args...) -> @request(args...).then(_.bind(@handleSuccess, @)).fail(@handleFailure) handleSuccess: (resp) -> throw new Error 'Error in the backend' unless resp?.success @promise(resp) handleFailure: (e) -> if e.status == DataboundError.STATUS throw new DataboundError(e.responseJSON.message) else throw new Error "Error in the backend with status #{e.status}" checkUndefinedId: (action, id) -> return unless _.isUndefined(id) throw new DataboundError("Couldn't #{action} a record without an id") class DataboundError constructor: (text) -> @message = "Databound: #{text}" @STATUS: 405 DataboundError:: = new Error() module.exports = Databound
[ { "context": ".be.eql ['histogram-normalized']\n keys = ['r', 'g', 'b', 'a', 'y', 'h', 's', 'l', 'c']\n for key in keys\n histogram = r", "end": 5185, "score": 0.9739892482757568, "start": 5144, "tag": "KEY", "value": "r', 'g', 'b', 'a', 'y', 'h', 's', 'l', 'c" } ]
spec/GetHistogram.coffee
noflo/noflo-image
9
noflo = require 'noflo' unless noflo.isBrowser() fixtures = require './fixtures' chai = require 'chai' unless chai path = require 'path' baseDir = path.resolve __dirname, '../' testutils = require './testutils' else baseDir = '/noflo-image' testutils = require 'noflo-image/spec/testutils.js' describe 'GetHistogram component', -> @timeout 5*1000 c = null canvas = null step = null out = null error = null beforeEach (done) -> loader = new noflo.ComponentLoader baseDir loader.load 'image/GetHistogram', (err, instance) -> return done err if err c = instance canvas = noflo.internalSocket.createSocket() step = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() error = noflo.internalSocket.createSocket() c.inPorts.canvas.attach canvas c.inPorts.step.attach step c.outPorts.histogram.attach out c.outPorts.error.attach error done() describe 'when instantiated', -> it 'should have input ports', -> chai.expect(c.inPorts.canvas).to.be.an 'object' chai.expect(c.inPorts.step).to.be.an 'object' it 'should have output ports', -> chai.expect(c.outPorts.histogram).to.be.an 'object' it 'should have an error output port', -> chai.expect(c.outPorts.error).to.be.an 'object' describe 'when passed a canvas', -> it 'should calculate histograms', (done) -> groupId = 'histogram-values' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-values'] chai.expect(res).to.be.deep.equal hists = 'rgbayhslc' for hist in hists expected = fixtures.histogram.colorful[hist] for val, i in res[hist] chai.expect(val, "histogram-#{hist}").to.be.closeTo expected[i], 0.001 done() inSrc = 'colorful-octagon.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId step.send 2 canvas.send c canvas.endGroup() it 'should calculate histograms even if step is higher than image size', (done) -> groupId = 'huge-step' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['huge-step'] chai.expect(res).to.be.deep.equal hists = 'rgbayhslc' for hist in hists expected = fixtures.histogram.colorful[hist] for val, i in res[hist] chai.expect(val, "histogram-#{hist}").to.be.closeTo expected[i], 0.001 done() inSrc = 'colorful-octagon.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId step.send 1000000 canvas.send c canvas.endGroup() it 'should calculate histograms even if step is not valid', (done) -> groupId = 'invalid-step' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['invalid-step'] chai.expect(res).to.be.deep.equal hists = 'rgbayhslc' for hist in hists expected = fixtures.histogram.colorful[hist] for val, i in res[hist] chai.expect(val, "histogram-#{hist}").to.be.closeTo expected[i], 0.001 done() inSrc = 'colorful-octagon.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId step.send 0 canvas.send c canvas.endGroup() it 'should calculate histograms with the right ranges', (done) -> groupId = 'histogram-ranges' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-ranges'] chai.expect(res.r.length).to.be.equal 256 chai.expect(res.g.length).to.be.equal 256 chai.expect(res.b.length).to.be.equal 256 chai.expect(res.a.length).to.be.equal 256 chai.expect(res.y.length).to.be.equal 256 chai.expect(res.h.length).to.be.equal 361 chai.expect(res.s.length).to.be.equal 101 chai.expect(res.l.length).to.be.equal 101 chai.expect(res.c.length).to.be.equal 135 done() inSrc = 'original.jpg' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() it 'should calculate normalized histograms', (done) -> groupId = 'histogram-normalized' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-normalized'] keys = ['r', 'g', 'b', 'a', 'y', 'h', 's', 'l', 'c'] for key in keys histogram = res[key] sum = histogram.reduce (a,b) -> return a + b chai.expect(sum).to.be.closeTo 1.0, 1.0 done() inSrc = 'original.jpg' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a saturated canvas', -> it 'should calculate S-histogram concentrated in high spectrum', (done) -> groupId = 'histogram-saturated' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-saturated'] histogram = res.s low = histogram.slice 0, histogram.length/2 sumLow = low.reduce (a,b) -> return a + b high = histogram.slice histogram.length/2 sumHigh = high.reduce (a,b) -> return a + b chai.expect(sumHigh).to.be.gte 0.5 chai.expect(sumLow).to.be.lte 0.5 done() inSrc = 'saturation.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a muted canvas', -> it 'should calculate S-histogram concentrated in low spectrum', (done) -> groupId = 'histogram-muted' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-muted'] histogram = res.s low = histogram.slice 0, histogram.length/2 sumLow = low.reduce (a,b) -> return a + b high = histogram.slice histogram.length/2 sumHigh = high.reduce (a,b) -> return a + b chai.expect(sumHigh).to.be.lte 0.5 chai.expect(sumLow).to.be.gte 0.5 done() inSrc = 'muted.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a light canvas', -> it 'should calculate L-histogram concentrated in high spectrum', (done) -> groupId = 'histogram-light' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-light'] histogram = res.l low = histogram.slice 0, histogram.length/2 sumLow = low.reduce (a,b) -> return a + b high = histogram.slice histogram.length/2 sumHigh = high.reduce (a,b) -> return a + b chai.expect(sumHigh).to.be.gte 0.5 chai.expect(sumLow).to.be.lte 0.5 done() inSrc = 'light.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a dark canvas', -> it 'should calculate L-histogram concentrated in low spectrum', (done) -> groupId = 'histogram-dark' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-dark'] histogram = res.l low = histogram.slice 0, histogram.length/2 sumLow = low.reduce (a,b) -> return a + b high = histogram.slice histogram.length/2 sumHigh = high.reduce (a,b) -> return a + b chai.expect(sumHigh).to.be.lte 0.5 chai.expect(sumLow).to.be.gte 0.5 done() inSrc = 'dark.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a canvas with any transparent pixel', -> it 'should calculate A-histogram with 100% frequency on 255', (done) -> groupId = 'histogram-alpha' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-alpha'] histogram = res.a chai.expect(histogram[255]).to.equal 1.0 done() inSrc = 'dark.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a 100% transparent canvas', -> it 'should calculate A-histogram with 100% frequency on zero', (done) -> groupId = 'histogram-alpha' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-alpha'] histogram = res.a # Zero alpha is transparent, so A-histogram should be all zero chai.expect(histogram[0]).to.equal 1.0 done() inSrc = 'all-transparent.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a zero sized canvas', -> it 'should return an error', (done) -> error.on 'data', (err) -> done() canvas.send '' describe 'when passed null', -> it 'should return an error', (done) -> error.on 'data', (err) -> done() canvas.send null
67165
noflo = require 'noflo' unless noflo.isBrowser() fixtures = require './fixtures' chai = require 'chai' unless chai path = require 'path' baseDir = path.resolve __dirname, '../' testutils = require './testutils' else baseDir = '/noflo-image' testutils = require 'noflo-image/spec/testutils.js' describe 'GetHistogram component', -> @timeout 5*1000 c = null canvas = null step = null out = null error = null beforeEach (done) -> loader = new noflo.ComponentLoader baseDir loader.load 'image/GetHistogram', (err, instance) -> return done err if err c = instance canvas = noflo.internalSocket.createSocket() step = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() error = noflo.internalSocket.createSocket() c.inPorts.canvas.attach canvas c.inPorts.step.attach step c.outPorts.histogram.attach out c.outPorts.error.attach error done() describe 'when instantiated', -> it 'should have input ports', -> chai.expect(c.inPorts.canvas).to.be.an 'object' chai.expect(c.inPorts.step).to.be.an 'object' it 'should have output ports', -> chai.expect(c.outPorts.histogram).to.be.an 'object' it 'should have an error output port', -> chai.expect(c.outPorts.error).to.be.an 'object' describe 'when passed a canvas', -> it 'should calculate histograms', (done) -> groupId = 'histogram-values' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-values'] chai.expect(res).to.be.deep.equal hists = 'rgbayhslc' for hist in hists expected = fixtures.histogram.colorful[hist] for val, i in res[hist] chai.expect(val, "histogram-#{hist}").to.be.closeTo expected[i], 0.001 done() inSrc = 'colorful-octagon.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId step.send 2 canvas.send c canvas.endGroup() it 'should calculate histograms even if step is higher than image size', (done) -> groupId = 'huge-step' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['huge-step'] chai.expect(res).to.be.deep.equal hists = 'rgbayhslc' for hist in hists expected = fixtures.histogram.colorful[hist] for val, i in res[hist] chai.expect(val, "histogram-#{hist}").to.be.closeTo expected[i], 0.001 done() inSrc = 'colorful-octagon.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId step.send 1000000 canvas.send c canvas.endGroup() it 'should calculate histograms even if step is not valid', (done) -> groupId = 'invalid-step' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['invalid-step'] chai.expect(res).to.be.deep.equal hists = 'rgbayhslc' for hist in hists expected = fixtures.histogram.colorful[hist] for val, i in res[hist] chai.expect(val, "histogram-#{hist}").to.be.closeTo expected[i], 0.001 done() inSrc = 'colorful-octagon.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId step.send 0 canvas.send c canvas.endGroup() it 'should calculate histograms with the right ranges', (done) -> groupId = 'histogram-ranges' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-ranges'] chai.expect(res.r.length).to.be.equal 256 chai.expect(res.g.length).to.be.equal 256 chai.expect(res.b.length).to.be.equal 256 chai.expect(res.a.length).to.be.equal 256 chai.expect(res.y.length).to.be.equal 256 chai.expect(res.h.length).to.be.equal 361 chai.expect(res.s.length).to.be.equal 101 chai.expect(res.l.length).to.be.equal 101 chai.expect(res.c.length).to.be.equal 135 done() inSrc = 'original.jpg' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() it 'should calculate normalized histograms', (done) -> groupId = 'histogram-normalized' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-normalized'] keys = ['<KEY>'] for key in keys histogram = res[key] sum = histogram.reduce (a,b) -> return a + b chai.expect(sum).to.be.closeTo 1.0, 1.0 done() inSrc = 'original.jpg' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a saturated canvas', -> it 'should calculate S-histogram concentrated in high spectrum', (done) -> groupId = 'histogram-saturated' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-saturated'] histogram = res.s low = histogram.slice 0, histogram.length/2 sumLow = low.reduce (a,b) -> return a + b high = histogram.slice histogram.length/2 sumHigh = high.reduce (a,b) -> return a + b chai.expect(sumHigh).to.be.gte 0.5 chai.expect(sumLow).to.be.lte 0.5 done() inSrc = 'saturation.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a muted canvas', -> it 'should calculate S-histogram concentrated in low spectrum', (done) -> groupId = 'histogram-muted' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-muted'] histogram = res.s low = histogram.slice 0, histogram.length/2 sumLow = low.reduce (a,b) -> return a + b high = histogram.slice histogram.length/2 sumHigh = high.reduce (a,b) -> return a + b chai.expect(sumHigh).to.be.lte 0.5 chai.expect(sumLow).to.be.gte 0.5 done() inSrc = 'muted.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a light canvas', -> it 'should calculate L-histogram concentrated in high spectrum', (done) -> groupId = 'histogram-light' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-light'] histogram = res.l low = histogram.slice 0, histogram.length/2 sumLow = low.reduce (a,b) -> return a + b high = histogram.slice histogram.length/2 sumHigh = high.reduce (a,b) -> return a + b chai.expect(sumHigh).to.be.gte 0.5 chai.expect(sumLow).to.be.lte 0.5 done() inSrc = 'light.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a dark canvas', -> it 'should calculate L-histogram concentrated in low spectrum', (done) -> groupId = 'histogram-dark' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-dark'] histogram = res.l low = histogram.slice 0, histogram.length/2 sumLow = low.reduce (a,b) -> return a + b high = histogram.slice histogram.length/2 sumHigh = high.reduce (a,b) -> return a + b chai.expect(sumHigh).to.be.lte 0.5 chai.expect(sumLow).to.be.gte 0.5 done() inSrc = 'dark.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a canvas with any transparent pixel', -> it 'should calculate A-histogram with 100% frequency on 255', (done) -> groupId = 'histogram-alpha' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-alpha'] histogram = res.a chai.expect(histogram[255]).to.equal 1.0 done() inSrc = 'dark.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a 100% transparent canvas', -> it 'should calculate A-histogram with 100% frequency on zero', (done) -> groupId = 'histogram-alpha' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-alpha'] histogram = res.a # Zero alpha is transparent, so A-histogram should be all zero chai.expect(histogram[0]).to.equal 1.0 done() inSrc = 'all-transparent.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a zero sized canvas', -> it 'should return an error', (done) -> error.on 'data', (err) -> done() canvas.send '' describe 'when passed null', -> it 'should return an error', (done) -> error.on 'data', (err) -> done() canvas.send null
true
noflo = require 'noflo' unless noflo.isBrowser() fixtures = require './fixtures' chai = require 'chai' unless chai path = require 'path' baseDir = path.resolve __dirname, '../' testutils = require './testutils' else baseDir = '/noflo-image' testutils = require 'noflo-image/spec/testutils.js' describe 'GetHistogram component', -> @timeout 5*1000 c = null canvas = null step = null out = null error = null beforeEach (done) -> loader = new noflo.ComponentLoader baseDir loader.load 'image/GetHistogram', (err, instance) -> return done err if err c = instance canvas = noflo.internalSocket.createSocket() step = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() error = noflo.internalSocket.createSocket() c.inPorts.canvas.attach canvas c.inPorts.step.attach step c.outPorts.histogram.attach out c.outPorts.error.attach error done() describe 'when instantiated', -> it 'should have input ports', -> chai.expect(c.inPorts.canvas).to.be.an 'object' chai.expect(c.inPorts.step).to.be.an 'object' it 'should have output ports', -> chai.expect(c.outPorts.histogram).to.be.an 'object' it 'should have an error output port', -> chai.expect(c.outPorts.error).to.be.an 'object' describe 'when passed a canvas', -> it 'should calculate histograms', (done) -> groupId = 'histogram-values' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-values'] chai.expect(res).to.be.deep.equal hists = 'rgbayhslc' for hist in hists expected = fixtures.histogram.colorful[hist] for val, i in res[hist] chai.expect(val, "histogram-#{hist}").to.be.closeTo expected[i], 0.001 done() inSrc = 'colorful-octagon.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId step.send 2 canvas.send c canvas.endGroup() it 'should calculate histograms even if step is higher than image size', (done) -> groupId = 'huge-step' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['huge-step'] chai.expect(res).to.be.deep.equal hists = 'rgbayhslc' for hist in hists expected = fixtures.histogram.colorful[hist] for val, i in res[hist] chai.expect(val, "histogram-#{hist}").to.be.closeTo expected[i], 0.001 done() inSrc = 'colorful-octagon.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId step.send 1000000 canvas.send c canvas.endGroup() it 'should calculate histograms even if step is not valid', (done) -> groupId = 'invalid-step' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['invalid-step'] chai.expect(res).to.be.deep.equal hists = 'rgbayhslc' for hist in hists expected = fixtures.histogram.colorful[hist] for val, i in res[hist] chai.expect(val, "histogram-#{hist}").to.be.closeTo expected[i], 0.001 done() inSrc = 'colorful-octagon.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId step.send 0 canvas.send c canvas.endGroup() it 'should calculate histograms with the right ranges', (done) -> groupId = 'histogram-ranges' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-ranges'] chai.expect(res.r.length).to.be.equal 256 chai.expect(res.g.length).to.be.equal 256 chai.expect(res.b.length).to.be.equal 256 chai.expect(res.a.length).to.be.equal 256 chai.expect(res.y.length).to.be.equal 256 chai.expect(res.h.length).to.be.equal 361 chai.expect(res.s.length).to.be.equal 101 chai.expect(res.l.length).to.be.equal 101 chai.expect(res.c.length).to.be.equal 135 done() inSrc = 'original.jpg' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() it 'should calculate normalized histograms', (done) -> groupId = 'histogram-normalized' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-normalized'] keys = ['PI:KEY:<KEY>END_PI'] for key in keys histogram = res[key] sum = histogram.reduce (a,b) -> return a + b chai.expect(sum).to.be.closeTo 1.0, 1.0 done() inSrc = 'original.jpg' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a saturated canvas', -> it 'should calculate S-histogram concentrated in high spectrum', (done) -> groupId = 'histogram-saturated' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-saturated'] histogram = res.s low = histogram.slice 0, histogram.length/2 sumLow = low.reduce (a,b) -> return a + b high = histogram.slice histogram.length/2 sumHigh = high.reduce (a,b) -> return a + b chai.expect(sumHigh).to.be.gte 0.5 chai.expect(sumLow).to.be.lte 0.5 done() inSrc = 'saturation.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a muted canvas', -> it 'should calculate S-histogram concentrated in low spectrum', (done) -> groupId = 'histogram-muted' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-muted'] histogram = res.s low = histogram.slice 0, histogram.length/2 sumLow = low.reduce (a,b) -> return a + b high = histogram.slice histogram.length/2 sumHigh = high.reduce (a,b) -> return a + b chai.expect(sumHigh).to.be.lte 0.5 chai.expect(sumLow).to.be.gte 0.5 done() inSrc = 'muted.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a light canvas', -> it 'should calculate L-histogram concentrated in high spectrum', (done) -> groupId = 'histogram-light' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-light'] histogram = res.l low = histogram.slice 0, histogram.length/2 sumLow = low.reduce (a,b) -> return a + b high = histogram.slice histogram.length/2 sumHigh = high.reduce (a,b) -> return a + b chai.expect(sumHigh).to.be.gte 0.5 chai.expect(sumLow).to.be.lte 0.5 done() inSrc = 'light.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a dark canvas', -> it 'should calculate L-histogram concentrated in low spectrum', (done) -> groupId = 'histogram-dark' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-dark'] histogram = res.l low = histogram.slice 0, histogram.length/2 sumLow = low.reduce (a,b) -> return a + b high = histogram.slice histogram.length/2 sumHigh = high.reduce (a,b) -> return a + b chai.expect(sumHigh).to.be.lte 0.5 chai.expect(sumLow).to.be.gte 0.5 done() inSrc = 'dark.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a canvas with any transparent pixel', -> it 'should calculate A-histogram with 100% frequency on 255', (done) -> groupId = 'histogram-alpha' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-alpha'] histogram = res.a chai.expect(histogram[255]).to.equal 1.0 done() inSrc = 'dark.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a 100% transparent canvas', -> it 'should calculate A-histogram with 100% frequency on zero', (done) -> groupId = 'histogram-alpha' groups = [] out.once 'begingroup', (group) -> groups.push group out.once 'endgroup', (group) -> groups.pop() out.once 'data', (res) -> chai.expect(groups).to.be.eql ['histogram-alpha'] histogram = res.a # Zero alpha is transparent, so A-histogram should be all zero chai.expect(histogram[0]).to.equal 1.0 done() inSrc = 'all-transparent.png' testutils.getCanvasWithImageNoShift inSrc, (c) -> canvas.beginGroup groupId canvas.send c canvas.endGroup() describe 'when passed a zero sized canvas', -> it 'should return an error', (done) -> error.on 'data', (err) -> done() canvas.send '' describe 'when passed null', -> it 'should return an error', (done) -> error.on 'data', (err) -> done() canvas.send null
[ { "context": "by id', (done) ->\n (new IndexedModel({name: 'Bob'})).save (err) ->\n assert.ok(!err, \"No err", "end": 1623, "score": 0.9994269609451294, "start": 1620, "tag": "NAME", "value": "Bob" }, { "context": "rors: #{err}\")\n\n (new IndexedModel({name: 'Fred...
test/spec/indexing.tests.coffee
vidigami/backbone-mongo
1
util = require 'util' assert = require 'assert' BackboneORM = require 'backbone-orm' {_, Backbone, Queue, Utils} = BackboneORM _.each BackboneORM.TestUtils.optionSets(), exports = (options) -> options = _.extend({}, options, __test__parameters) if __test__parameters? DATABASE_URL = options.database_url or '' BASE_SCHEMA = options.schema or {} SYNC = options.sync describe "Indexing Functionality #{options.$tags} @indexing", -> IndexedModel = null before -> BackboneORM.configure {model_cache: {enabled: !!options.cache, max: 100}} class IndexedModel extends Backbone.Model schema: id: [indexed: true] name: [indexed: true] url: "#{DATABASE_URL}/indexed_models" sync: SYNC(IndexedModel) after (callback) -> Utils.resetSchemas [IndexedModel], callback beforeEach (callback) -> Utils.resetSchemas [IndexedModel], callback it 'should ensure indexes', (done) -> IndexedModel::sync 'collection', (err, collection) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!collection) # indexing is async so need to poll checkIndexes = (callback, name) -> fn = -> collection.indexExists name, (err, exists) -> assert.ok(!err, "No errors: #{err}") return callback() if exists _.delay fn, 50 queue = new Queue() queue.defer (callback) -> checkIndexes(callback, 'id_1')() queue.defer (callback) -> checkIndexes(callback, 'name_1')() queue.await done it 'should sort by id', (done) -> (new IndexedModel({name: 'Bob'})).save (err) -> assert.ok(!err, "No errors: #{err}") (new IndexedModel({name: 'Fred'})).save (err) -> assert.ok(!err, "No errors: #{err}") IndexedModel.cursor().sort('id').toModels (err, models) -> assert.ok(!err, "No errors: #{err}") ids = (model.id for model in models) sorted_ids = _.clone(ids).sort() assert.deepEqual(ids, sorted_ids, "Models were returned in sorted order") done()
178512
util = require 'util' assert = require 'assert' BackboneORM = require 'backbone-orm' {_, Backbone, Queue, Utils} = BackboneORM _.each BackboneORM.TestUtils.optionSets(), exports = (options) -> options = _.extend({}, options, __test__parameters) if __test__parameters? DATABASE_URL = options.database_url or '' BASE_SCHEMA = options.schema or {} SYNC = options.sync describe "Indexing Functionality #{options.$tags} @indexing", -> IndexedModel = null before -> BackboneORM.configure {model_cache: {enabled: !!options.cache, max: 100}} class IndexedModel extends Backbone.Model schema: id: [indexed: true] name: [indexed: true] url: "#{DATABASE_URL}/indexed_models" sync: SYNC(IndexedModel) after (callback) -> Utils.resetSchemas [IndexedModel], callback beforeEach (callback) -> Utils.resetSchemas [IndexedModel], callback it 'should ensure indexes', (done) -> IndexedModel::sync 'collection', (err, collection) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!collection) # indexing is async so need to poll checkIndexes = (callback, name) -> fn = -> collection.indexExists name, (err, exists) -> assert.ok(!err, "No errors: #{err}") return callback() if exists _.delay fn, 50 queue = new Queue() queue.defer (callback) -> checkIndexes(callback, 'id_1')() queue.defer (callback) -> checkIndexes(callback, 'name_1')() queue.await done it 'should sort by id', (done) -> (new IndexedModel({name: '<NAME>'})).save (err) -> assert.ok(!err, "No errors: #{err}") (new IndexedModel({name: '<NAME>'})).save (err) -> assert.ok(!err, "No errors: #{err}") IndexedModel.cursor().sort('id').toModels (err, models) -> assert.ok(!err, "No errors: #{err}") ids = (model.id for model in models) sorted_ids = _.clone(ids).sort() assert.deepEqual(ids, sorted_ids, "Models were returned in sorted order") done()
true
util = require 'util' assert = require 'assert' BackboneORM = require 'backbone-orm' {_, Backbone, Queue, Utils} = BackboneORM _.each BackboneORM.TestUtils.optionSets(), exports = (options) -> options = _.extend({}, options, __test__parameters) if __test__parameters? DATABASE_URL = options.database_url or '' BASE_SCHEMA = options.schema or {} SYNC = options.sync describe "Indexing Functionality #{options.$tags} @indexing", -> IndexedModel = null before -> BackboneORM.configure {model_cache: {enabled: !!options.cache, max: 100}} class IndexedModel extends Backbone.Model schema: id: [indexed: true] name: [indexed: true] url: "#{DATABASE_URL}/indexed_models" sync: SYNC(IndexedModel) after (callback) -> Utils.resetSchemas [IndexedModel], callback beforeEach (callback) -> Utils.resetSchemas [IndexedModel], callback it 'should ensure indexes', (done) -> IndexedModel::sync 'collection', (err, collection) -> assert.ok(!err, "No errors: #{err}") assert.ok(!!collection) # indexing is async so need to poll checkIndexes = (callback, name) -> fn = -> collection.indexExists name, (err, exists) -> assert.ok(!err, "No errors: #{err}") return callback() if exists _.delay fn, 50 queue = new Queue() queue.defer (callback) -> checkIndexes(callback, 'id_1')() queue.defer (callback) -> checkIndexes(callback, 'name_1')() queue.await done it 'should sort by id', (done) -> (new IndexedModel({name: 'PI:NAME:<NAME>END_PI'})).save (err) -> assert.ok(!err, "No errors: #{err}") (new IndexedModel({name: 'PI:NAME:<NAME>END_PI'})).save (err) -> assert.ok(!err, "No errors: #{err}") IndexedModel.cursor().sort('id').toModels (err, models) -> assert.ok(!err, "No errors: #{err}") ids = (model.id for model in models) sorted_ids = _.clone(ids).sort() assert.deepEqual(ids, sorted_ids, "Models were returned in sorted order") done()
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9982169270515442, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-http-agent-keepalive.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. # cache the socket, close it after 100ms get = (path, callback) -> http.get host: "localhost" port: common.PORT agent: agent path: path , callback checkDataAndSockets = (body) -> assert.equal body.toString(), "hello world" assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` return second = -> # request second, use the same socket get "/second", (res) -> assert.equal res.statusCode, 200 res.on "data", checkDataAndSockets res.on "end", -> assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` process.nextTick -> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name].length, 1 remoteClose() return return return return remoteClose = -> # mock remote server close the socket get "/remote_close", (res) -> assert.deepEqual res.statusCode, 200 res.on "data", checkDataAndSockets res.on "end", -> assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` process.nextTick -> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name].length, 1 # waitting remote server close the socket setTimeout (-> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name], `undefined`, "freeSockets is not empty" remoteError() return ), 200 return return return return remoteError = -> # remove server will destroy ths socket req = get("/error", (res) -> throw new Error("should not call this function")return ) req.on "error", (err) -> assert.ok err assert.equal err.message, "socket hang up" assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` # Wait socket 'close' event emit setTimeout (-> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name], `undefined` done() return ), 1 return return done = -> console.log "http keepalive agent test success." process.exit 0 return common = require("../common") assert = require("assert") http = require("http") Agent = require("_http_agent").Agent EventEmitter = require("events").EventEmitter agent = new Agent( keepAlive: true keepAliveMsecs: 1000 maxSockets: 5 maxFreeSockets: 5 ) server = http.createServer((req, res) -> if req.url is "/error" res.destroy() return else if req.url is "/remote_close" socket = res.connection setTimeout (-> socket.end() return ), 100 res.end "hello world" return ) name = "localhost:" + common.PORT + "::" server.listen common.PORT, -> # request first, and keep alive get "/first", (res) -> assert.equal res.statusCode, 200 res.on "data", checkDataAndSockets res.on "end", -> assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` process.nextTick -> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name].length, 1 second() return return return return
196637
# 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. # cache the socket, close it after 100ms get = (path, callback) -> http.get host: "localhost" port: common.PORT agent: agent path: path , callback checkDataAndSockets = (body) -> assert.equal body.toString(), "hello world" assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` return second = -> # request second, use the same socket get "/second", (res) -> assert.equal res.statusCode, 200 res.on "data", checkDataAndSockets res.on "end", -> assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` process.nextTick -> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name].length, 1 remoteClose() return return return return remoteClose = -> # mock remote server close the socket get "/remote_close", (res) -> assert.deepEqual res.statusCode, 200 res.on "data", checkDataAndSockets res.on "end", -> assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` process.nextTick -> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name].length, 1 # waitting remote server close the socket setTimeout (-> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name], `undefined`, "freeSockets is not empty" remoteError() return ), 200 return return return return remoteError = -> # remove server will destroy ths socket req = get("/error", (res) -> throw new Error("should not call this function")return ) req.on "error", (err) -> assert.ok err assert.equal err.message, "socket hang up" assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` # Wait socket 'close' event emit setTimeout (-> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name], `undefined` done() return ), 1 return return done = -> console.log "http keepalive agent test success." process.exit 0 return common = require("../common") assert = require("assert") http = require("http") Agent = require("_http_agent").Agent EventEmitter = require("events").EventEmitter agent = new Agent( keepAlive: true keepAliveMsecs: 1000 maxSockets: 5 maxFreeSockets: 5 ) server = http.createServer((req, res) -> if req.url is "/error" res.destroy() return else if req.url is "/remote_close" socket = res.connection setTimeout (-> socket.end() return ), 100 res.end "hello world" return ) name = "localhost:" + common.PORT + "::" server.listen common.PORT, -> # request first, and keep alive get "/first", (res) -> assert.equal res.statusCode, 200 res.on "data", checkDataAndSockets res.on "end", -> assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` process.nextTick -> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name].length, 1 second() return return 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. # cache the socket, close it after 100ms get = (path, callback) -> http.get host: "localhost" port: common.PORT agent: agent path: path , callback checkDataAndSockets = (body) -> assert.equal body.toString(), "hello world" assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` return second = -> # request second, use the same socket get "/second", (res) -> assert.equal res.statusCode, 200 res.on "data", checkDataAndSockets res.on "end", -> assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` process.nextTick -> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name].length, 1 remoteClose() return return return return remoteClose = -> # mock remote server close the socket get "/remote_close", (res) -> assert.deepEqual res.statusCode, 200 res.on "data", checkDataAndSockets res.on "end", -> assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` process.nextTick -> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name].length, 1 # waitting remote server close the socket setTimeout (-> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name], `undefined`, "freeSockets is not empty" remoteError() return ), 200 return return return return remoteError = -> # remove server will destroy ths socket req = get("/error", (res) -> throw new Error("should not call this function")return ) req.on "error", (err) -> assert.ok err assert.equal err.message, "socket hang up" assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` # Wait socket 'close' event emit setTimeout (-> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name], `undefined` done() return ), 1 return return done = -> console.log "http keepalive agent test success." process.exit 0 return common = require("../common") assert = require("assert") http = require("http") Agent = require("_http_agent").Agent EventEmitter = require("events").EventEmitter agent = new Agent( keepAlive: true keepAliveMsecs: 1000 maxSockets: 5 maxFreeSockets: 5 ) server = http.createServer((req, res) -> if req.url is "/error" res.destroy() return else if req.url is "/remote_close" socket = res.connection setTimeout (-> socket.end() return ), 100 res.end "hello world" return ) name = "localhost:" + common.PORT + "::" server.listen common.PORT, -> # request first, and keep alive get "/first", (res) -> assert.equal res.statusCode, 200 res.on "data", checkDataAndSockets res.on "end", -> assert.equal agent.sockets[name].length, 1 assert.equal agent.freeSockets[name], `undefined` process.nextTick -> assert.equal agent.sockets[name], `undefined` assert.equal agent.freeSockets[name].length, 1 second() return return return return
[ { "context": "ams.level = level\n $routeParams.key = 'SM.1.1'\n $scope = $rootScope.$new()\n $controll", "end": 368, "score": 0.9993605613708496, "start": 362, "tag": "KEY", "value": "SM.1.1" }, { "context": "s', 'Deployment']\n @.activity.key.assert_Is 'SM....
test/controllers/project/Observed-Controller.test.coffee
DinisCruz/Maturity-Models-UI
7
describe 'controllers | project | ObservedController', -> $scope = null project = null level = null beforeEach -> module('MM_Graph') beforeEach -> project = 'bsimm' inject ($controller, $rootScope, $routeParams, $httpBackend)-> $routeParams.project = project $routeParams.level = level $routeParams.key = 'SM.1.1' $scope = $rootScope.$new() $controller('ObservedController', { $scope: $scope }) $httpBackend.flush() it 'constructor',-> using $scope, -> @.project.assert_Is 'bsimm' @.observed.keys().assert_Is ['Governance', 'Intelligence', 'SSDL Touchpoints', 'Deployment'] @.activity.key.assert_Is 'SM.1.1' it '$scope.page_Link',-> $scope.page_Link().assert_Is "view/project/#{project}/observed" it '$scope.show_Activity', -> $scope.show_Activity().assert_Is_True() inject ($routeParams)-> $routeParams.level = '1' $scope.show_Activity( ).assert_Is_False() $scope.show_Activity(level:'1').assert_Is_True() $routeParams.level = '2' $scope.show_Activity(level:'1').assert_Is_False() it '$scope.team_Table_Link',-> team = 'aaaaa' $scope.team_Table_Link(team).assert_Is "view/#{project}/#{team}/table"
59489
describe 'controllers | project | ObservedController', -> $scope = null project = null level = null beforeEach -> module('MM_Graph') beforeEach -> project = 'bsimm' inject ($controller, $rootScope, $routeParams, $httpBackend)-> $routeParams.project = project $routeParams.level = level $routeParams.key = '<KEY>' $scope = $rootScope.$new() $controller('ObservedController', { $scope: $scope }) $httpBackend.flush() it 'constructor',-> using $scope, -> @.project.assert_Is 'bsimm' @.observed.keys().assert_Is ['Governance', 'Intelligence', 'SSDL Touchpoints', 'Deployment'] @.activity.key.assert_Is '<KEY>' it '$scope.page_Link',-> $scope.page_Link().assert_Is "view/project/#{project}/observed" it '$scope.show_Activity', -> $scope.show_Activity().assert_Is_True() inject ($routeParams)-> $routeParams.level = '1' $scope.show_Activity( ).assert_Is_False() $scope.show_Activity(level:'1').assert_Is_True() $routeParams.level = '2' $scope.show_Activity(level:'1').assert_Is_False() it '$scope.team_Table_Link',-> team = 'aaaaa' $scope.team_Table_Link(team).assert_Is "view/#{project}/#{team}/table"
true
describe 'controllers | project | ObservedController', -> $scope = null project = null level = null beforeEach -> module('MM_Graph') beforeEach -> project = 'bsimm' inject ($controller, $rootScope, $routeParams, $httpBackend)-> $routeParams.project = project $routeParams.level = level $routeParams.key = 'PI:KEY:<KEY>END_PI' $scope = $rootScope.$new() $controller('ObservedController', { $scope: $scope }) $httpBackend.flush() it 'constructor',-> using $scope, -> @.project.assert_Is 'bsimm' @.observed.keys().assert_Is ['Governance', 'Intelligence', 'SSDL Touchpoints', 'Deployment'] @.activity.key.assert_Is 'PI:KEY:<KEY>END_PI' it '$scope.page_Link',-> $scope.page_Link().assert_Is "view/project/#{project}/observed" it '$scope.show_Activity', -> $scope.show_Activity().assert_Is_True() inject ($routeParams)-> $routeParams.level = '1' $scope.show_Activity( ).assert_Is_False() $scope.show_Activity(level:'1').assert_Is_True() $routeParams.level = '2' $scope.show_Activity(level:'1').assert_Is_False() it '$scope.team_Table_Link',-> team = 'aaaaa' $scope.team_Table_Link(team).assert_Is "view/#{project}/#{team}/table"
[ { "context": "nLegend: false\n }\n {\n id: 'ma5'\n name: 'MA5',\n linkedTo: 'clos", "end": 8082, "score": 0.8596545457839966, "start": 8079, "tag": "USERNAME", "value": "ma5" }, { "context": " }\n {\n id: 'ma5'\n name:...
app/assets/javascripts/component_ui/candlestick.js.coffee
gsmlg/peatio
3,436
if gon.local is "zh-CN" DATETIME_LABEL_FORMAT_FOR_TOOLTIP = millisecond: ['%m月%e日, %H:%M:%S.%L', '%m月%e日, %H:%M:%S.%L', '-%H:%M:%S.%L'] second: ['%m月%e日, %H:%M:%S', '%m月%e日, %H:%M:%S', '-%H:%M:%S'] minute: ['%m月%e日, %H:%M', '%m月%e日, %H:%M', '-%H:%M'] hour: ['%m月%e日, %H:%M', '%m月%e日, %H:%M', '-%H:%M'] day: ['%m月%e日, %H:%M', '%m月%e日, %H:%M', '-%H:%M'] week: ['%Y年%m月%e日', '%Y年%m月%e日', '-%m月%e日'] month: ['%Y年%m月', '%Y年%m月', '-%m'] year: ['%Y', '%Y', '-%Y'] DATETIME_LABEL_FORMAT = second: '%H:%M:%S' minute: '%H:%M' hour: '%H:%M' day: '%m-%d' week: '%m-%d' month: '%Y-%m' year: '%Y' RANGE_DEFAULT = fill: 'none', stroke: 'none', 'stroke-width': 0, r: 8, style: color: '#333', states: hover: fill: '#000', style: color: '#ccc' select: fill: '#000', style: color: '#eee' COLOR_ON = candlestick: color: '#990f0f' upColor: '#000000' lineColor: '#cc1414' upLineColor: '#49c043' close: color: null # The trick is use invalid color code to make the line transparent COLOR_OFF = candlestick: color: 'invalid' upColor: 'invalid' lineColor: 'invalid' upLineColor: 'invalid' close: color: 'invalid' COLOR = { candlestick: _.extend({}, COLOR_OFF.candlestick), close: _.extend({}, COLOR_OFF.close) } INDICATOR = {MA: false, EMA: false} @CandlestickUI = flight.component -> @mask = -> @$node.find('.mask').show() @unmask = -> @$node.find('.mask').hide() @request = -> @mask() @init = (event, data) -> @running = true @$node.find('#candlestick_chart').highcharts()?.destroy() @initHighStock(data) @trigger 'market::candlestick::created', data @switchType = (event, data) -> _.extend(COLOR[key], COLOR_OFF[key]) for key, val of COLOR _.extend(COLOR[data.x], COLOR_ON[data.x]) if chart = @$node.find('#candlestick_chart').highcharts() for type, colors of COLOR for s in chart.series if !s.userOptions.algorithm? && (s.userOptions.id == type) s.update(colors, false) @trigger "switch::main_indicator_switch::init" @switchMainIndicator = (event, data) -> INDICATOR[key] = false for key, val of INDICATOR INDICATOR[data.x] = true if chart = @$node.find('#candlestick_chart').highcharts() # reset all series depend on close for s in chart.series if s.userOptions.linkedTo == 'close' s.setVisible(true, false) for indicator, visible of INDICATOR for s in chart.series if s.userOptions.algorithm? && (s.userOptions.algorithm == indicator) s.setVisible(visible, false) chart.redraw() @default_range = (unit) -> 1000 * 60 * unit * 100 @initHighStock = (data) -> component = @ range = @default_range(data['minutes']) unit = $("[data-unit=#{data['minutes']}]").text() title = "#{gon.market.base_unit.toUpperCase()}/#{gon.market.quote_unit.toUpperCase()} - #{unit}" timeUnits = millisecond: 1 second: 1000 minute: 60000 hour: 3600000 day: 24 * 3600000 week: 7 * 24 * 3600000 month: 31 * 24 * 3600000 year: 31556952000 dataGrouping = enabled: false tooltipTemplate = JST["templates/tooltip"] if DATETIME_LABEL_FORMAT_FOR_TOOLTIP dataGrouping['dateTimeLabelFormats'] = DATETIME_LABEL_FORMAT_FOR_TOOLTIP @$node.find('#candlestick_chart').highcharts "StockChart", chart: events: load: => @unmask() animation: true marginTop: 95 backgroundColor: 'rgba(0,0,0, 0.0)' credits: enabled: false tooltip: crosshairs: [{ width: 0.5, dashStyle: 'solid', color: '#777' }, false], valueDecimals: gon.market.bid.fixed borderWidth: 0 backgroundColor: 'rgba(0,0,0,0)' borderRadius: 2 shadow: false shared: true positioner: (w, h, point) -> chart_w = $(@chart.renderTo).width() chart_h = $(@chart.renderTo).height() grid_h = Math.min(20, Math.ceil(chart_h/10)) x = Math.max(10, point.plotX-w-20) y = Math.max(0, Math.floor(point.plotY/grid_h)*grid_h-20) x: x, y: y useHTML: true formatter: -> chart = @points[0].series.chart series = @points[0].series index = @points[0].point.index key = @points[0].key for k, v of timeUnits if v >= series.xAxis.closestPointRange || (v <= timeUnits.day && key % v > 0) dateFormat = dateTimeLabelFormats = series.options.dataGrouping.dateTimeLabelFormats[k][0] title = Highcharts.dateFormat dateFormat, key break fun = (h, s) -> h[s.options.id] = s.data[index] h tooltipTemplate title: title indicator: INDICATOR format: (v, fixed=3) -> Highcharts.numberFormat v, fixed points: _.reduce chart.series, fun, {} plotOptions: candlestick: turboThreshold: 0 followPointer: true color: '#990f0f' upColor: '#000000' lineColor: '#cc1414' upLineColor: '#49c043' dataGrouping: dataGrouping column: turboThreshold: 0 dataGrouping: dataGrouping trendline: lineWidth: 1 histogram: lineWidth: 1 tooltip: pointFormat: """ <li><span style='color: {series.color};'>{series.name}: <b>{point.y}</b></span></li> """ scrollbar: buttonArrowColor: '#333' barBackgroundColor: '#202020' buttonBackgroundColor: '#202020' trackBackgroundColor: '#202020' barBorderColor: '#2a2a2a' buttonBorderColor: '#2a2a2a' trackBorderColor: '#2a2a2a' rangeSelector: enabled: false navigator: maskFill: 'rgba(32, 32, 32, 0.6)' outlineColor: '#333' outlineWidth: 1 xAxis: dateTimeLabelFormats: DATETIME_LABEL_FORMAT xAxis: type: 'datetime', dateTimeLabelFormats: DATETIME_LABEL_FORMAT lineColor: '#333' tickColor: '#333' tickWidth: 2 range: range events: afterSetExtremes: (e) -> if e.trigger == 'navigator' && e.triggerOp == 'navigator-drag' if component.liveRange(@.chart) && !component.running component.trigger "switch::range_switch::init" yAxis: [ { labels: enabled: true align: 'right' x: 2 y: 3 zIndex: -7 gridLineColor: '#222' gridLineDashStyle: 'ShortDot' top: "0%" height: "70%" lineColor: '#fff' minRange: if gon.ticker.last then parseFloat(gon.ticker.last)/25 else null } { labels: enabled: false top: "70%" gridLineColor: '#000' height: "15%" } { labels: enabled: false top: "85%" gridLineColor: '#000' height: "15%" } ] series: [ _.extend({ id: 'candlestick' name: gon.i18n.chart.candlestick type: "candlestick" data: data['candlestick'] showInLegend: false }, COLOR['candlestick']), _.extend({ id: 'close' type: 'spline' data: data['close'] showInLegend: false marker: radius: 0 }, COLOR['close']), { id: 'volume' name: gon.i18n.chart.volume yAxis: 1 type: "column" data: data['volume'] color: '#777' showInLegend: false } { id: 'ma5' name: 'MA5', linkedTo: 'close', showInLegend: true, type: 'trendline', algorithm: 'MA', periods: 5 color: '#7c9aaa' visible: INDICATOR['MA'] marker: radius: 0 } { id: 'ma10' name: 'MA10' linkedTo: 'close', showInLegend: true, type: 'trendline', algorithm: 'MA', periods: 10 color: '#be8f53' visible: INDICATOR['MA'] marker: radius: 0 } { id: 'ema7' name: 'EMA7', linkedTo: 'close', showInLegend: true, type: 'trendline', algorithm: 'EMA', periods: 7 color: '#7c9aaa' visible: INDICATOR['EMA'] marker: radius: 0 } { id: 'ema30' name: 'EMA30', linkedTo: 'close', showInLegend: true, type: 'trendline', algorithm: 'EMA', periods: 30 color: '#be8f53' visible: INDICATOR['EMA'] marker: radius: 0 } { id: 'macd' name : 'MACD', linkedTo: 'close', yAxis: 2, showInLegend: true, type: 'trendline', algorithm: 'MACD' color: '#7c9aaa' marker: radius: 0 } { id: 'sig' name : 'SIG', linkedTo: 'close', yAxis: 2, showInLegend: true, type: 'trendline', algorithm: 'signalLine' color: '#be8f53' marker: radius: 0 } { id: 'hist' name: 'HIST', linkedTo: 'close', yAxis: 2, showInLegend: true, type: 'histogram' color: '#990f0f' } ] @formatPointArray = (point) -> x: point[0], open: point[1], high: point[2], low: point[3], close: point[4] @createPointOnSeries = (chart, i, px, point) -> chart.series[i].addPoint(point, true, true) #last = chart.series[i].points[chart.series[i].points.length-1] #console.log "Add point on #{i}: px=#{px} lastx=#{last.x}" @createPoint = (chart, data, i) -> @createPointOnSeries(chart, 0, data.candlestick[i][0], data.candlestick[i]) @createPointOnSeries(chart, 1, data.close[i][0], data.close[i]) @createPointOnSeries(chart, 2, data.volume[i].x, data.volume[i]) chart.redraw(true) @updatePointOnSeries = (chart, i, px, point) -> if chart.series[i].points last = chart.series[i].points[chart.series[i].points.length-1] if px == last.x last.update(point, false) else console.log "Error update on series #{i}: px=#{px} lastx=#{last.x}" @updatePoint = (chart, data, i) -> @updatePointOnSeries(chart, 0, data.candlestick[i][0], @formatPointArray(data.candlestick[i])) @updatePointOnSeries(chart, 1, data.close[i][0], data.close[i][1]) @updatePointOnSeries(chart, 2, data.volume[i].x, data.volume[i]) chart.redraw(true) @process = (chart, data) -> for i in [0..(data.candlestick.length-1)] current = chart.series[0].points.length - 1 current_point = chart.series[0].points[current] if data.candlestick[i][0] > current_point.x @createPoint chart, data, i else @updatePoint chart, data, i @updateByTrades = (event, data) -> chart = @$node.find('#candlestick_chart').highcharts() if @liveRange(chart) @process(chart, data) else @running = false @liveRange = (chart) -> p1 = chart.series[0].points[ chart.series[0].points.length-1 ].x p2 = chart.series[10].points[ chart.series[10].points.length-1 ].x p1 == p2 @after 'initialize', -> @on document, 'market::candlestick::request', @request @on document, 'market::candlestick::response', @init @on document, 'market::candlestick::trades', @updateByTrades @on document, 'switch::main_indicator_switch', @switchMainIndicator @on document, 'switch::type_switch', @switchType
64511
if gon.local is "zh-CN" DATETIME_LABEL_FORMAT_FOR_TOOLTIP = millisecond: ['%m月%e日, %H:%M:%S.%L', '%m月%e日, %H:%M:%S.%L', '-%H:%M:%S.%L'] second: ['%m月%e日, %H:%M:%S', '%m月%e日, %H:%M:%S', '-%H:%M:%S'] minute: ['%m月%e日, %H:%M', '%m月%e日, %H:%M', '-%H:%M'] hour: ['%m月%e日, %H:%M', '%m月%e日, %H:%M', '-%H:%M'] day: ['%m月%e日, %H:%M', '%m月%e日, %H:%M', '-%H:%M'] week: ['%Y年%m月%e日', '%Y年%m月%e日', '-%m月%e日'] month: ['%Y年%m月', '%Y年%m月', '-%m'] year: ['%Y', '%Y', '-%Y'] DATETIME_LABEL_FORMAT = second: '%H:%M:%S' minute: '%H:%M' hour: '%H:%M' day: '%m-%d' week: '%m-%d' month: '%Y-%m' year: '%Y' RANGE_DEFAULT = fill: 'none', stroke: 'none', 'stroke-width': 0, r: 8, style: color: '#333', states: hover: fill: '#000', style: color: '#ccc' select: fill: '#000', style: color: '#eee' COLOR_ON = candlestick: color: '#990f0f' upColor: '#000000' lineColor: '#cc1414' upLineColor: '#49c043' close: color: null # The trick is use invalid color code to make the line transparent COLOR_OFF = candlestick: color: 'invalid' upColor: 'invalid' lineColor: 'invalid' upLineColor: 'invalid' close: color: 'invalid' COLOR = { candlestick: _.extend({}, COLOR_OFF.candlestick), close: _.extend({}, COLOR_OFF.close) } INDICATOR = {MA: false, EMA: false} @CandlestickUI = flight.component -> @mask = -> @$node.find('.mask').show() @unmask = -> @$node.find('.mask').hide() @request = -> @mask() @init = (event, data) -> @running = true @$node.find('#candlestick_chart').highcharts()?.destroy() @initHighStock(data) @trigger 'market::candlestick::created', data @switchType = (event, data) -> _.extend(COLOR[key], COLOR_OFF[key]) for key, val of COLOR _.extend(COLOR[data.x], COLOR_ON[data.x]) if chart = @$node.find('#candlestick_chart').highcharts() for type, colors of COLOR for s in chart.series if !s.userOptions.algorithm? && (s.userOptions.id == type) s.update(colors, false) @trigger "switch::main_indicator_switch::init" @switchMainIndicator = (event, data) -> INDICATOR[key] = false for key, val of INDICATOR INDICATOR[data.x] = true if chart = @$node.find('#candlestick_chart').highcharts() # reset all series depend on close for s in chart.series if s.userOptions.linkedTo == 'close' s.setVisible(true, false) for indicator, visible of INDICATOR for s in chart.series if s.userOptions.algorithm? && (s.userOptions.algorithm == indicator) s.setVisible(visible, false) chart.redraw() @default_range = (unit) -> 1000 * 60 * unit * 100 @initHighStock = (data) -> component = @ range = @default_range(data['minutes']) unit = $("[data-unit=#{data['minutes']}]").text() title = "#{gon.market.base_unit.toUpperCase()}/#{gon.market.quote_unit.toUpperCase()} - #{unit}" timeUnits = millisecond: 1 second: 1000 minute: 60000 hour: 3600000 day: 24 * 3600000 week: 7 * 24 * 3600000 month: 31 * 24 * 3600000 year: 31556952000 dataGrouping = enabled: false tooltipTemplate = JST["templates/tooltip"] if DATETIME_LABEL_FORMAT_FOR_TOOLTIP dataGrouping['dateTimeLabelFormats'] = DATETIME_LABEL_FORMAT_FOR_TOOLTIP @$node.find('#candlestick_chart').highcharts "StockChart", chart: events: load: => @unmask() animation: true marginTop: 95 backgroundColor: 'rgba(0,0,0, 0.0)' credits: enabled: false tooltip: crosshairs: [{ width: 0.5, dashStyle: 'solid', color: '#777' }, false], valueDecimals: gon.market.bid.fixed borderWidth: 0 backgroundColor: 'rgba(0,0,0,0)' borderRadius: 2 shadow: false shared: true positioner: (w, h, point) -> chart_w = $(@chart.renderTo).width() chart_h = $(@chart.renderTo).height() grid_h = Math.min(20, Math.ceil(chart_h/10)) x = Math.max(10, point.plotX-w-20) y = Math.max(0, Math.floor(point.plotY/grid_h)*grid_h-20) x: x, y: y useHTML: true formatter: -> chart = @points[0].series.chart series = @points[0].series index = @points[0].point.index key = @points[0].key for k, v of timeUnits if v >= series.xAxis.closestPointRange || (v <= timeUnits.day && key % v > 0) dateFormat = dateTimeLabelFormats = series.options.dataGrouping.dateTimeLabelFormats[k][0] title = Highcharts.dateFormat dateFormat, key break fun = (h, s) -> h[s.options.id] = s.data[index] h tooltipTemplate title: title indicator: INDICATOR format: (v, fixed=3) -> Highcharts.numberFormat v, fixed points: _.reduce chart.series, fun, {} plotOptions: candlestick: turboThreshold: 0 followPointer: true color: '#990f0f' upColor: '#000000' lineColor: '#cc1414' upLineColor: '#49c043' dataGrouping: dataGrouping column: turboThreshold: 0 dataGrouping: dataGrouping trendline: lineWidth: 1 histogram: lineWidth: 1 tooltip: pointFormat: """ <li><span style='color: {series.color};'>{series.name}: <b>{point.y}</b></span></li> """ scrollbar: buttonArrowColor: '#333' barBackgroundColor: '#202020' buttonBackgroundColor: '#202020' trackBackgroundColor: '#202020' barBorderColor: '#2a2a2a' buttonBorderColor: '#2a2a2a' trackBorderColor: '#2a2a2a' rangeSelector: enabled: false navigator: maskFill: 'rgba(32, 32, 32, 0.6)' outlineColor: '#333' outlineWidth: 1 xAxis: dateTimeLabelFormats: DATETIME_LABEL_FORMAT xAxis: type: 'datetime', dateTimeLabelFormats: DATETIME_LABEL_FORMAT lineColor: '#333' tickColor: '#333' tickWidth: 2 range: range events: afterSetExtremes: (e) -> if e.trigger == 'navigator' && e.triggerOp == 'navigator-drag' if component.liveRange(@.chart) && !component.running component.trigger "switch::range_switch::init" yAxis: [ { labels: enabled: true align: 'right' x: 2 y: 3 zIndex: -7 gridLineColor: '#222' gridLineDashStyle: 'ShortDot' top: "0%" height: "70%" lineColor: '#fff' minRange: if gon.ticker.last then parseFloat(gon.ticker.last)/25 else null } { labels: enabled: false top: "70%" gridLineColor: '#000' height: "15%" } { labels: enabled: false top: "85%" gridLineColor: '#000' height: "15%" } ] series: [ _.extend({ id: 'candlestick' name: gon.i18n.chart.candlestick type: "candlestick" data: data['candlestick'] showInLegend: false }, COLOR['candlestick']), _.extend({ id: 'close' type: 'spline' data: data['close'] showInLegend: false marker: radius: 0 }, COLOR['close']), { id: 'volume' name: gon.i18n.chart.volume yAxis: 1 type: "column" data: data['volume'] color: '#777' showInLegend: false } { id: 'ma5' name: '<NAME>', linkedTo: 'close', showInLegend: true, type: 'trendline', algorithm: 'MA', periods: 5 color: '#7c9aaa' visible: INDICATOR['MA'] marker: radius: 0 } { id: 'ma10' name: '<NAME>' linkedTo: 'close', showInLegend: true, type: 'trendline', algorithm: 'MA', periods: 10 color: '#be8f53' visible: INDICATOR['MA'] marker: radius: 0 } { id: 'ema7' name: '<NAME>MA7', linkedTo: 'close', showInLegend: true, type: 'trendline', algorithm: 'EMA', periods: 7 color: '#7c9aaa' visible: INDICATOR['EMA'] marker: radius: 0 } { id: 'ema30' name: '<NAME>MA30', linkedTo: 'close', showInLegend: true, type: 'trendline', algorithm: 'EMA', periods: 30 color: '#be8f53' visible: INDICATOR['EMA'] marker: radius: 0 } { id: 'macd' name : '<NAME>', linkedTo: 'close', yAxis: 2, showInLegend: true, type: 'trendline', algorithm: 'MACD' color: '#7c9aaa' marker: radius: 0 } { id: '<NAME>' name : '<NAME>', linkedTo: 'close', yAxis: 2, showInLegend: true, type: 'trendline', algorithm: 'signalLine' color: '#be8f53' marker: radius: 0 } { id: 'hist' name: '<NAME>', linkedTo: 'close', yAxis: 2, showInLegend: true, type: 'histogram' color: '#990f0f' } ] @formatPointArray = (point) -> x: point[0], open: point[1], high: point[2], low: point[3], close: point[4] @createPointOnSeries = (chart, i, px, point) -> chart.series[i].addPoint(point, true, true) #last = chart.series[i].points[chart.series[i].points.length-1] #console.log "Add point on #{i}: px=#{px} lastx=#{last.x}" @createPoint = (chart, data, i) -> @createPointOnSeries(chart, 0, data.candlestick[i][0], data.candlestick[i]) @createPointOnSeries(chart, 1, data.close[i][0], data.close[i]) @createPointOnSeries(chart, 2, data.volume[i].x, data.volume[i]) chart.redraw(true) @updatePointOnSeries = (chart, i, px, point) -> if chart.series[i].points last = chart.series[i].points[chart.series[i].points.length-1] if px == last.x last.update(point, false) else console.log "Error update on series #{i}: px=#{px} lastx=#{last.x}" @updatePoint = (chart, data, i) -> @updatePointOnSeries(chart, 0, data.candlestick[i][0], @formatPointArray(data.candlestick[i])) @updatePointOnSeries(chart, 1, data.close[i][0], data.close[i][1]) @updatePointOnSeries(chart, 2, data.volume[i].x, data.volume[i]) chart.redraw(true) @process = (chart, data) -> for i in [0..(data.candlestick.length-1)] current = chart.series[0].points.length - 1 current_point = chart.series[0].points[current] if data.candlestick[i][0] > current_point.x @createPoint chart, data, i else @updatePoint chart, data, i @updateByTrades = (event, data) -> chart = @$node.find('#candlestick_chart').highcharts() if @liveRange(chart) @process(chart, data) else @running = false @liveRange = (chart) -> p1 = chart.series[0].points[ chart.series[0].points.length-1 ].x p2 = chart.series[10].points[ chart.series[10].points.length-1 ].x p1 == p2 @after 'initialize', -> @on document, 'market::candlestick::request', @request @on document, 'market::candlestick::response', @init @on document, 'market::candlestick::trades', @updateByTrades @on document, 'switch::main_indicator_switch', @switchMainIndicator @on document, 'switch::type_switch', @switchType
true
if gon.local is "zh-CN" DATETIME_LABEL_FORMAT_FOR_TOOLTIP = millisecond: ['%m月%e日, %H:%M:%S.%L', '%m月%e日, %H:%M:%S.%L', '-%H:%M:%S.%L'] second: ['%m月%e日, %H:%M:%S', '%m月%e日, %H:%M:%S', '-%H:%M:%S'] minute: ['%m月%e日, %H:%M', '%m月%e日, %H:%M', '-%H:%M'] hour: ['%m月%e日, %H:%M', '%m月%e日, %H:%M', '-%H:%M'] day: ['%m月%e日, %H:%M', '%m月%e日, %H:%M', '-%H:%M'] week: ['%Y年%m月%e日', '%Y年%m月%e日', '-%m月%e日'] month: ['%Y年%m月', '%Y年%m月', '-%m'] year: ['%Y', '%Y', '-%Y'] DATETIME_LABEL_FORMAT = second: '%H:%M:%S' minute: '%H:%M' hour: '%H:%M' day: '%m-%d' week: '%m-%d' month: '%Y-%m' year: '%Y' RANGE_DEFAULT = fill: 'none', stroke: 'none', 'stroke-width': 0, r: 8, style: color: '#333', states: hover: fill: '#000', style: color: '#ccc' select: fill: '#000', style: color: '#eee' COLOR_ON = candlestick: color: '#990f0f' upColor: '#000000' lineColor: '#cc1414' upLineColor: '#49c043' close: color: null # The trick is use invalid color code to make the line transparent COLOR_OFF = candlestick: color: 'invalid' upColor: 'invalid' lineColor: 'invalid' upLineColor: 'invalid' close: color: 'invalid' COLOR = { candlestick: _.extend({}, COLOR_OFF.candlestick), close: _.extend({}, COLOR_OFF.close) } INDICATOR = {MA: false, EMA: false} @CandlestickUI = flight.component -> @mask = -> @$node.find('.mask').show() @unmask = -> @$node.find('.mask').hide() @request = -> @mask() @init = (event, data) -> @running = true @$node.find('#candlestick_chart').highcharts()?.destroy() @initHighStock(data) @trigger 'market::candlestick::created', data @switchType = (event, data) -> _.extend(COLOR[key], COLOR_OFF[key]) for key, val of COLOR _.extend(COLOR[data.x], COLOR_ON[data.x]) if chart = @$node.find('#candlestick_chart').highcharts() for type, colors of COLOR for s in chart.series if !s.userOptions.algorithm? && (s.userOptions.id == type) s.update(colors, false) @trigger "switch::main_indicator_switch::init" @switchMainIndicator = (event, data) -> INDICATOR[key] = false for key, val of INDICATOR INDICATOR[data.x] = true if chart = @$node.find('#candlestick_chart').highcharts() # reset all series depend on close for s in chart.series if s.userOptions.linkedTo == 'close' s.setVisible(true, false) for indicator, visible of INDICATOR for s in chart.series if s.userOptions.algorithm? && (s.userOptions.algorithm == indicator) s.setVisible(visible, false) chart.redraw() @default_range = (unit) -> 1000 * 60 * unit * 100 @initHighStock = (data) -> component = @ range = @default_range(data['minutes']) unit = $("[data-unit=#{data['minutes']}]").text() title = "#{gon.market.base_unit.toUpperCase()}/#{gon.market.quote_unit.toUpperCase()} - #{unit}" timeUnits = millisecond: 1 second: 1000 minute: 60000 hour: 3600000 day: 24 * 3600000 week: 7 * 24 * 3600000 month: 31 * 24 * 3600000 year: 31556952000 dataGrouping = enabled: false tooltipTemplate = JST["templates/tooltip"] if DATETIME_LABEL_FORMAT_FOR_TOOLTIP dataGrouping['dateTimeLabelFormats'] = DATETIME_LABEL_FORMAT_FOR_TOOLTIP @$node.find('#candlestick_chart').highcharts "StockChart", chart: events: load: => @unmask() animation: true marginTop: 95 backgroundColor: 'rgba(0,0,0, 0.0)' credits: enabled: false tooltip: crosshairs: [{ width: 0.5, dashStyle: 'solid', color: '#777' }, false], valueDecimals: gon.market.bid.fixed borderWidth: 0 backgroundColor: 'rgba(0,0,0,0)' borderRadius: 2 shadow: false shared: true positioner: (w, h, point) -> chart_w = $(@chart.renderTo).width() chart_h = $(@chart.renderTo).height() grid_h = Math.min(20, Math.ceil(chart_h/10)) x = Math.max(10, point.plotX-w-20) y = Math.max(0, Math.floor(point.plotY/grid_h)*grid_h-20) x: x, y: y useHTML: true formatter: -> chart = @points[0].series.chart series = @points[0].series index = @points[0].point.index key = @points[0].key for k, v of timeUnits if v >= series.xAxis.closestPointRange || (v <= timeUnits.day && key % v > 0) dateFormat = dateTimeLabelFormats = series.options.dataGrouping.dateTimeLabelFormats[k][0] title = Highcharts.dateFormat dateFormat, key break fun = (h, s) -> h[s.options.id] = s.data[index] h tooltipTemplate title: title indicator: INDICATOR format: (v, fixed=3) -> Highcharts.numberFormat v, fixed points: _.reduce chart.series, fun, {} plotOptions: candlestick: turboThreshold: 0 followPointer: true color: '#990f0f' upColor: '#000000' lineColor: '#cc1414' upLineColor: '#49c043' dataGrouping: dataGrouping column: turboThreshold: 0 dataGrouping: dataGrouping trendline: lineWidth: 1 histogram: lineWidth: 1 tooltip: pointFormat: """ <li><span style='color: {series.color};'>{series.name}: <b>{point.y}</b></span></li> """ scrollbar: buttonArrowColor: '#333' barBackgroundColor: '#202020' buttonBackgroundColor: '#202020' trackBackgroundColor: '#202020' barBorderColor: '#2a2a2a' buttonBorderColor: '#2a2a2a' trackBorderColor: '#2a2a2a' rangeSelector: enabled: false navigator: maskFill: 'rgba(32, 32, 32, 0.6)' outlineColor: '#333' outlineWidth: 1 xAxis: dateTimeLabelFormats: DATETIME_LABEL_FORMAT xAxis: type: 'datetime', dateTimeLabelFormats: DATETIME_LABEL_FORMAT lineColor: '#333' tickColor: '#333' tickWidth: 2 range: range events: afterSetExtremes: (e) -> if e.trigger == 'navigator' && e.triggerOp == 'navigator-drag' if component.liveRange(@.chart) && !component.running component.trigger "switch::range_switch::init" yAxis: [ { labels: enabled: true align: 'right' x: 2 y: 3 zIndex: -7 gridLineColor: '#222' gridLineDashStyle: 'ShortDot' top: "0%" height: "70%" lineColor: '#fff' minRange: if gon.ticker.last then parseFloat(gon.ticker.last)/25 else null } { labels: enabled: false top: "70%" gridLineColor: '#000' height: "15%" } { labels: enabled: false top: "85%" gridLineColor: '#000' height: "15%" } ] series: [ _.extend({ id: 'candlestick' name: gon.i18n.chart.candlestick type: "candlestick" data: data['candlestick'] showInLegend: false }, COLOR['candlestick']), _.extend({ id: 'close' type: 'spline' data: data['close'] showInLegend: false marker: radius: 0 }, COLOR['close']), { id: 'volume' name: gon.i18n.chart.volume yAxis: 1 type: "column" data: data['volume'] color: '#777' showInLegend: false } { id: 'ma5' name: 'PI:NAME:<NAME>END_PI', linkedTo: 'close', showInLegend: true, type: 'trendline', algorithm: 'MA', periods: 5 color: '#7c9aaa' visible: INDICATOR['MA'] marker: radius: 0 } { id: 'ma10' name: 'PI:NAME:<NAME>END_PI' linkedTo: 'close', showInLegend: true, type: 'trendline', algorithm: 'MA', periods: 10 color: '#be8f53' visible: INDICATOR['MA'] marker: radius: 0 } { id: 'ema7' name: 'PI:NAME:<NAME>END_PIMA7', linkedTo: 'close', showInLegend: true, type: 'trendline', algorithm: 'EMA', periods: 7 color: '#7c9aaa' visible: INDICATOR['EMA'] marker: radius: 0 } { id: 'ema30' name: 'PI:NAME:<NAME>END_PIMA30', linkedTo: 'close', showInLegend: true, type: 'trendline', algorithm: 'EMA', periods: 30 color: '#be8f53' visible: INDICATOR['EMA'] marker: radius: 0 } { id: 'macd' name : 'PI:NAME:<NAME>END_PI', linkedTo: 'close', yAxis: 2, showInLegend: true, type: 'trendline', algorithm: 'MACD' color: '#7c9aaa' marker: radius: 0 } { id: 'PI:NAME:<NAME>END_PI' name : 'PI:NAME:<NAME>END_PI', linkedTo: 'close', yAxis: 2, showInLegend: true, type: 'trendline', algorithm: 'signalLine' color: '#be8f53' marker: radius: 0 } { id: 'hist' name: 'PI:NAME:<NAME>END_PI', linkedTo: 'close', yAxis: 2, showInLegend: true, type: 'histogram' color: '#990f0f' } ] @formatPointArray = (point) -> x: point[0], open: point[1], high: point[2], low: point[3], close: point[4] @createPointOnSeries = (chart, i, px, point) -> chart.series[i].addPoint(point, true, true) #last = chart.series[i].points[chart.series[i].points.length-1] #console.log "Add point on #{i}: px=#{px} lastx=#{last.x}" @createPoint = (chart, data, i) -> @createPointOnSeries(chart, 0, data.candlestick[i][0], data.candlestick[i]) @createPointOnSeries(chart, 1, data.close[i][0], data.close[i]) @createPointOnSeries(chart, 2, data.volume[i].x, data.volume[i]) chart.redraw(true) @updatePointOnSeries = (chart, i, px, point) -> if chart.series[i].points last = chart.series[i].points[chart.series[i].points.length-1] if px == last.x last.update(point, false) else console.log "Error update on series #{i}: px=#{px} lastx=#{last.x}" @updatePoint = (chart, data, i) -> @updatePointOnSeries(chart, 0, data.candlestick[i][0], @formatPointArray(data.candlestick[i])) @updatePointOnSeries(chart, 1, data.close[i][0], data.close[i][1]) @updatePointOnSeries(chart, 2, data.volume[i].x, data.volume[i]) chart.redraw(true) @process = (chart, data) -> for i in [0..(data.candlestick.length-1)] current = chart.series[0].points.length - 1 current_point = chart.series[0].points[current] if data.candlestick[i][0] > current_point.x @createPoint chart, data, i else @updatePoint chart, data, i @updateByTrades = (event, data) -> chart = @$node.find('#candlestick_chart').highcharts() if @liveRange(chart) @process(chart, data) else @running = false @liveRange = (chart) -> p1 = chart.series[0].points[ chart.series[0].points.length-1 ].x p2 = chart.series[10].points[ chart.series[10].points.length-1 ].x p1 == p2 @after 'initialize', -> @on document, 'market::candlestick::request', @request @on document, 'market::candlestick::response', @init @on document, 'market::candlestick::trades', @updateByTrades @on document, 'switch::main_indicator_switch', @switchMainIndicator @on document, 'switch::type_switch', @switchType
[ { "context": "###\njQuery Age\nCopyright 2013 Kevin Sylvestre\n1.2.4\n###\n\n\"use strict\"\n\n$ = jQuery\n\nclass Age\n\n ", "end": 45, "score": 0.9998534321784973, "start": 30, "tag": "NAME", "value": "Kevin Sylvestre" } ]
javascripts/jquery.age.coffee
ksylvest/jquery-age
35
### jQuery Age Copyright 2013 Kevin Sylvestre 1.2.4 ### "use strict" $ = jQuery class Age @settings: singular: 1 interval: 1000 suffixes: past: "ago" future: "until" prefixes: past: "" future: "" units: ["years", "months", "weeks", "days", "hours", "minutes", "seconds"] formats: now: "now" singular: seconds: "a second" minutes: "a minute" hours: "an hour" days: "a day" weeks: "a week" months: "a month" years: "a year" plural: seconds: "{{amount}} seconds" minutes: "{{amount}} minutes" hours: "{{amount}} hours" days: "{{amount}} days" weeks: "{{amount}} weeks" months: "{{amount}} months" years: "{{amount}} years" tiny: seconds: "{{amount}}s" minutes: "{{amount}}m" hours: "{{amount}}h" days: "{{amount}}d" weeks: "{{amount}}w" months: "{{amount}}m" years: "{{amount}}y" constructor: ($el, settings = {}) -> @$el = $el @settings = $.extend {}, Age.settings, settings @reformat() reformat: => interval = @interval() @$el.html(@text(interval)) setTimeout @reformat, @settings.interval date: => new Date @$el.attr('datetime') or @$el.attr('date') or @$el.attr('time') suffix: (interval) => return @settings.suffixes.past if interval < 0 return @settings.suffixes.future if interval > 0 prefix: (interval) => return @settings.prefixes.past if interval < 0 return @settings.prefixes.future if interval > 0 adjust: (interval, scale) => Math.floor(Math.abs(interval / scale)) formatting: (interval) => seconds: @adjust(interval, 1000) minutes: @adjust(interval, 1000 * 60) hours: @adjust(interval, 1000 * 60 * 60) days: @adjust(interval, 1000 * 60 * 60 * 24) weeks: @adjust(interval, 1000 * 60 * 60 * 24 * 7) months: @adjust(interval, 1000 * 60 * 60 * 24 * 30) years: @adjust(interval, 1000 * 60 * 60 * 24 * 365) amount: (formatting) => return formatting[@unit(formatting)] || 0 unit: (formatting) => for unit in @settings.units return unit if formatting[unit] > 0 return undefined format: (amount, unit) => return @settings.formats[@settings.style]?[unit] if @settings.style? @settings.formats[if amount is @settings.singular then 'singular' else 'plural']?[unit] interval: => @date() - new Date text: (interval = @interval()) => return @settings.pending if interval > 0 and @settings.pending? return @settings.expired if interval < 0 and @settings.expired? suffix = @suffix(interval) prefix = @prefix(interval) formatting = @formatting(interval) amount = @amount(formatting) unit = @unit(formatting) format = @format(amount, unit) return @settings.formats.now unless format return "#{prefix} #{format.replace('{{unit}}', unit).replace('{{amount}}', amount)} #{suffix}".trim() $.fn.extend age: (options = {}) -> @each -> new Age($(@), options)
108066
### jQuery Age Copyright 2013 <NAME> 1.2.4 ### "use strict" $ = jQuery class Age @settings: singular: 1 interval: 1000 suffixes: past: "ago" future: "until" prefixes: past: "" future: "" units: ["years", "months", "weeks", "days", "hours", "minutes", "seconds"] formats: now: "now" singular: seconds: "a second" minutes: "a minute" hours: "an hour" days: "a day" weeks: "a week" months: "a month" years: "a year" plural: seconds: "{{amount}} seconds" minutes: "{{amount}} minutes" hours: "{{amount}} hours" days: "{{amount}} days" weeks: "{{amount}} weeks" months: "{{amount}} months" years: "{{amount}} years" tiny: seconds: "{{amount}}s" minutes: "{{amount}}m" hours: "{{amount}}h" days: "{{amount}}d" weeks: "{{amount}}w" months: "{{amount}}m" years: "{{amount}}y" constructor: ($el, settings = {}) -> @$el = $el @settings = $.extend {}, Age.settings, settings @reformat() reformat: => interval = @interval() @$el.html(@text(interval)) setTimeout @reformat, @settings.interval date: => new Date @$el.attr('datetime') or @$el.attr('date') or @$el.attr('time') suffix: (interval) => return @settings.suffixes.past if interval < 0 return @settings.suffixes.future if interval > 0 prefix: (interval) => return @settings.prefixes.past if interval < 0 return @settings.prefixes.future if interval > 0 adjust: (interval, scale) => Math.floor(Math.abs(interval / scale)) formatting: (interval) => seconds: @adjust(interval, 1000) minutes: @adjust(interval, 1000 * 60) hours: @adjust(interval, 1000 * 60 * 60) days: @adjust(interval, 1000 * 60 * 60 * 24) weeks: @adjust(interval, 1000 * 60 * 60 * 24 * 7) months: @adjust(interval, 1000 * 60 * 60 * 24 * 30) years: @adjust(interval, 1000 * 60 * 60 * 24 * 365) amount: (formatting) => return formatting[@unit(formatting)] || 0 unit: (formatting) => for unit in @settings.units return unit if formatting[unit] > 0 return undefined format: (amount, unit) => return @settings.formats[@settings.style]?[unit] if @settings.style? @settings.formats[if amount is @settings.singular then 'singular' else 'plural']?[unit] interval: => @date() - new Date text: (interval = @interval()) => return @settings.pending if interval > 0 and @settings.pending? return @settings.expired if interval < 0 and @settings.expired? suffix = @suffix(interval) prefix = @prefix(interval) formatting = @formatting(interval) amount = @amount(formatting) unit = @unit(formatting) format = @format(amount, unit) return @settings.formats.now unless format return "#{prefix} #{format.replace('{{unit}}', unit).replace('{{amount}}', amount)} #{suffix}".trim() $.fn.extend age: (options = {}) -> @each -> new Age($(@), options)
true
### jQuery Age Copyright 2013 PI:NAME:<NAME>END_PI 1.2.4 ### "use strict" $ = jQuery class Age @settings: singular: 1 interval: 1000 suffixes: past: "ago" future: "until" prefixes: past: "" future: "" units: ["years", "months", "weeks", "days", "hours", "minutes", "seconds"] formats: now: "now" singular: seconds: "a second" minutes: "a minute" hours: "an hour" days: "a day" weeks: "a week" months: "a month" years: "a year" plural: seconds: "{{amount}} seconds" minutes: "{{amount}} minutes" hours: "{{amount}} hours" days: "{{amount}} days" weeks: "{{amount}} weeks" months: "{{amount}} months" years: "{{amount}} years" tiny: seconds: "{{amount}}s" minutes: "{{amount}}m" hours: "{{amount}}h" days: "{{amount}}d" weeks: "{{amount}}w" months: "{{amount}}m" years: "{{amount}}y" constructor: ($el, settings = {}) -> @$el = $el @settings = $.extend {}, Age.settings, settings @reformat() reformat: => interval = @interval() @$el.html(@text(interval)) setTimeout @reformat, @settings.interval date: => new Date @$el.attr('datetime') or @$el.attr('date') or @$el.attr('time') suffix: (interval) => return @settings.suffixes.past if interval < 0 return @settings.suffixes.future if interval > 0 prefix: (interval) => return @settings.prefixes.past if interval < 0 return @settings.prefixes.future if interval > 0 adjust: (interval, scale) => Math.floor(Math.abs(interval / scale)) formatting: (interval) => seconds: @adjust(interval, 1000) minutes: @adjust(interval, 1000 * 60) hours: @adjust(interval, 1000 * 60 * 60) days: @adjust(interval, 1000 * 60 * 60 * 24) weeks: @adjust(interval, 1000 * 60 * 60 * 24 * 7) months: @adjust(interval, 1000 * 60 * 60 * 24 * 30) years: @adjust(interval, 1000 * 60 * 60 * 24 * 365) amount: (formatting) => return formatting[@unit(formatting)] || 0 unit: (formatting) => for unit in @settings.units return unit if formatting[unit] > 0 return undefined format: (amount, unit) => return @settings.formats[@settings.style]?[unit] if @settings.style? @settings.formats[if amount is @settings.singular then 'singular' else 'plural']?[unit] interval: => @date() - new Date text: (interval = @interval()) => return @settings.pending if interval > 0 and @settings.pending? return @settings.expired if interval < 0 and @settings.expired? suffix = @suffix(interval) prefix = @prefix(interval) formatting = @formatting(interval) amount = @amount(formatting) unit = @unit(formatting) format = @format(amount, unit) return @settings.formats.now unless format return "#{prefix} #{format.replace('{{unit}}', unit).replace('{{amount}}', amount)} #{suffix}".trim() $.fn.extend age: (options = {}) -> @each -> new Age($(@), options)
[ { "context": "# Copyright © 2014–6 Brad Ackerman.\n#\n# Licensed under the Apache License, Version 2", "end": 34, "score": 0.9998531341552734, "start": 21, "tag": "NAME", "value": "Brad Ackerman" } ]
assets/coffee/datatable-extensions.coffee
backerman/eveindy
2
# Copyright © 2014–6 Brad Ackerman. # # 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. jQuery.extend jQuery.fn.dataTableExt.oSort, "numeric-inf-pre": (a) -> if a is '∞' then +Infinity else parseFloat a "numeric-inf-asc": (a, b) -> ((a < b) ? -1 : ((a > b) ? 1 : 0)) "numeric-inf-desc": (a, b) -> ((a < b) ? 1 : ((a > b) ? -1 : 0))
167985
# Copyright © 2014–6 <NAME>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. jQuery.extend jQuery.fn.dataTableExt.oSort, "numeric-inf-pre": (a) -> if a is '∞' then +Infinity else parseFloat a "numeric-inf-asc": (a, b) -> ((a < b) ? -1 : ((a > b) ? 1 : 0)) "numeric-inf-desc": (a, b) -> ((a < b) ? 1 : ((a > b) ? -1 : 0))
true
# Copyright © 2014–6 PI:NAME:<NAME>END_PI. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. jQuery.extend jQuery.fn.dataTableExt.oSort, "numeric-inf-pre": (a) -> if a is '∞' then +Infinity else parseFloat a "numeric-inf-asc": (a, b) -> ((a < b) ? -1 : ((a > b) ? 1 : 0)) "numeric-inf-desc": (a, b) -> ((a < b) ? 1 : ((a > b) ? -1 : 0))
[ { "context": "# @file canvas.coffee\n# @Copyright (c) 2016 Taylor Siviter\n# This source code is licensed under the MIT Lice", "end": 58, "score": 0.9997469782829285, "start": 44, "tag": "NAME", "value": "Taylor Siviter" } ]
src/core/canvas.coffee
siviter-t/lampyridae.coffee
4
# @file canvas.coffee # @Copyright (c) 2016 Taylor Siviter # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. require 'core/draw' class Lampyridae.Canvas ### Construct and manage a Canvas object. # # @param id [String] Name of the #id selector for the canvas element # @param parent [String] Name of the element to attach the canvas to (defaults to body) ### constructor: (id, @parent = 'body') -> if arguments.length < 1 throw new Error "Canvas requires an \#id selector" # Control variables @_updateStack = [] # Stores a stack of functions to call every update @_stopAnim = false @_pauseAnim = false @findOrMakeCanvas(id) @context = @element.getContext '2d' @size() window.addEventListener 'resize', => @size() @draw = new Lampyridae.Draw @ ### Checks whether the given id selector exists; creating or registering accordingly. # If it does, it registers the current parent element for this object. # If it does not, it creates one under the given parent element. # # @param id [String] Name of the #id selector for the canvas element # @param parent [String] Name of the element to attach the canvas to (defaults to body) ### findOrMakeCanvas: (id, parent = @parent) -> @element = document.getElementById id if @element? then @parent = @element.parentElement else @element = document.createElement 'canvas' if parent == 'body' then @parent = document.body else @parent = document.getElementById parent @id id @appendCanvas() ### Appends a generated <canvas> tag to the DOM - if required. ### appendCanvas: () -> @parent.appendChild @element Lampyridae.Log.out "Appended \##{@element.id} to #{@parent.nodeName.toLowerCase()}\##{@parent.id}" # Access/Set/Get methods # ### Return or set the id selector of the canvas. # # @param id [String] The id string to set (optional; if needed) # @return [String] The current id selector of the canvas ### id: (id) -> if id? then @element.id = id return @element.id ### Return or set the width of the canvas. # # @param width [Number] The width to set (optional; if needed) # @return [Number] The current width of the canvas ### width: (width) -> if width? then @element.setAttribute 'width', width return @element.clientWidth ### Return or set the height of the canvas. # # @param height [Number] The width to set (optional; if needed) # @return [Number] The current height of the canvas ### height: (height) -> if height? then @element.setAttribute 'height', height return @element.clientHeight ### Set the overall size of the canvas. # Defaults to its current parent element's size. # # @param width [Number] The width to set (optional) # @param height [Number] The width to set (optional) ### size: (width = @parent.clientWidth, height = @parent.clientHeight) -> @width width; @height height ### Returns the current area of the canvas. # # @return [Number] The current area of the canvas ### area: () -> return @width() * @height() # Animation and update methods # ### Adds a function to the update stack. # # @f [Function] Function to call on Canvas.update ### addUpdate: (f) => if toString.call(f) isnt '[object Function]' throw new Error "Canvas.addUpdate requires a function" @_updateStack.push f ### Removes the top function from the update stack. # # @return [Bool] True if the top function has been removed; false if there's nothing left ### popUpdate: () => if @_updateStack.length > 0 @_updateStack.pop() return true return false ### Removes the first instance of the function from the top of the update stack. # # @f [Function] Function to stop calling on Canvas.update # @return [Bool] True if it has been found and removed; false otherwise # @note Iterates backwards through the update stack! ### removeUpdate: (f) => if toString.call(f) isnt '[object Function]' throw new Error "Canvas.addUpdate requires a function" for i in [@_updateStack.length - 1..0] by -1 if @_updateStack[i] == f @_updateStack.splice(i, 1) return true return false ### Iterates through the update stack and calls the update functions. ### update: () => i() for i in @_updateStack ### Animates the canvas! # Uses the functions in the update stack to add magic to the canvas. # # @note is controlled by the pause and stopAnimation() ### animate: () => unless @_stopAnim unless @_pauseAnim then @update() requestAnimationFrame @animate else @_stopAnim = false; @_pauseAnim = false ### Toggles the paused state of the canvas animation. ### pause: () => @_pauseAnim = !@_pauseAnim ### Stops the animation outright. ### stop: () => @_stopAnim = true # Helper Methods # ### Schedule a functon to call after a specified time # # @param time [Number] Time to wait in milliseconds # @param f [Function] Function to call after time has expired ### schedule: (time, f) -> setTimeout f, time ### Has the Canvas object acquired the 2d context (CanvasRenderingContext2D) api? # # @return [Bool] True if it does, false if it does not ### has2DContext: () -> if @context? then return @context.constructor == CanvasRenderingContext2D else return false # end class Lampyridae.Canvas module.exports = Lampyridae.Canvas
180621
# @file canvas.coffee # @Copyright (c) 2016 <NAME> # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. require 'core/draw' class Lampyridae.Canvas ### Construct and manage a Canvas object. # # @param id [String] Name of the #id selector for the canvas element # @param parent [String] Name of the element to attach the canvas to (defaults to body) ### constructor: (id, @parent = 'body') -> if arguments.length < 1 throw new Error "Canvas requires an \#id selector" # Control variables @_updateStack = [] # Stores a stack of functions to call every update @_stopAnim = false @_pauseAnim = false @findOrMakeCanvas(id) @context = @element.getContext '2d' @size() window.addEventListener 'resize', => @size() @draw = new Lampyridae.Draw @ ### Checks whether the given id selector exists; creating or registering accordingly. # If it does, it registers the current parent element for this object. # If it does not, it creates one under the given parent element. # # @param id [String] Name of the #id selector for the canvas element # @param parent [String] Name of the element to attach the canvas to (defaults to body) ### findOrMakeCanvas: (id, parent = @parent) -> @element = document.getElementById id if @element? then @parent = @element.parentElement else @element = document.createElement 'canvas' if parent == 'body' then @parent = document.body else @parent = document.getElementById parent @id id @appendCanvas() ### Appends a generated <canvas> tag to the DOM - if required. ### appendCanvas: () -> @parent.appendChild @element Lampyridae.Log.out "Appended \##{@element.id} to #{@parent.nodeName.toLowerCase()}\##{@parent.id}" # Access/Set/Get methods # ### Return or set the id selector of the canvas. # # @param id [String] The id string to set (optional; if needed) # @return [String] The current id selector of the canvas ### id: (id) -> if id? then @element.id = id return @element.id ### Return or set the width of the canvas. # # @param width [Number] The width to set (optional; if needed) # @return [Number] The current width of the canvas ### width: (width) -> if width? then @element.setAttribute 'width', width return @element.clientWidth ### Return or set the height of the canvas. # # @param height [Number] The width to set (optional; if needed) # @return [Number] The current height of the canvas ### height: (height) -> if height? then @element.setAttribute 'height', height return @element.clientHeight ### Set the overall size of the canvas. # Defaults to its current parent element's size. # # @param width [Number] The width to set (optional) # @param height [Number] The width to set (optional) ### size: (width = @parent.clientWidth, height = @parent.clientHeight) -> @width width; @height height ### Returns the current area of the canvas. # # @return [Number] The current area of the canvas ### area: () -> return @width() * @height() # Animation and update methods # ### Adds a function to the update stack. # # @f [Function] Function to call on Canvas.update ### addUpdate: (f) => if toString.call(f) isnt '[object Function]' throw new Error "Canvas.addUpdate requires a function" @_updateStack.push f ### Removes the top function from the update stack. # # @return [Bool] True if the top function has been removed; false if there's nothing left ### popUpdate: () => if @_updateStack.length > 0 @_updateStack.pop() return true return false ### Removes the first instance of the function from the top of the update stack. # # @f [Function] Function to stop calling on Canvas.update # @return [Bool] True if it has been found and removed; false otherwise # @note Iterates backwards through the update stack! ### removeUpdate: (f) => if toString.call(f) isnt '[object Function]' throw new Error "Canvas.addUpdate requires a function" for i in [@_updateStack.length - 1..0] by -1 if @_updateStack[i] == f @_updateStack.splice(i, 1) return true return false ### Iterates through the update stack and calls the update functions. ### update: () => i() for i in @_updateStack ### Animates the canvas! # Uses the functions in the update stack to add magic to the canvas. # # @note is controlled by the pause and stopAnimation() ### animate: () => unless @_stopAnim unless @_pauseAnim then @update() requestAnimationFrame @animate else @_stopAnim = false; @_pauseAnim = false ### Toggles the paused state of the canvas animation. ### pause: () => @_pauseAnim = !@_pauseAnim ### Stops the animation outright. ### stop: () => @_stopAnim = true # Helper Methods # ### Schedule a functon to call after a specified time # # @param time [Number] Time to wait in milliseconds # @param f [Function] Function to call after time has expired ### schedule: (time, f) -> setTimeout f, time ### Has the Canvas object acquired the 2d context (CanvasRenderingContext2D) api? # # @return [Bool] True if it does, false if it does not ### has2DContext: () -> if @context? then return @context.constructor == CanvasRenderingContext2D else return false # end class Lampyridae.Canvas module.exports = Lampyridae.Canvas
true
# @file canvas.coffee # @Copyright (c) 2016 PI:NAME:<NAME>END_PI # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. require 'core/draw' class Lampyridae.Canvas ### Construct and manage a Canvas object. # # @param id [String] Name of the #id selector for the canvas element # @param parent [String] Name of the element to attach the canvas to (defaults to body) ### constructor: (id, @parent = 'body') -> if arguments.length < 1 throw new Error "Canvas requires an \#id selector" # Control variables @_updateStack = [] # Stores a stack of functions to call every update @_stopAnim = false @_pauseAnim = false @findOrMakeCanvas(id) @context = @element.getContext '2d' @size() window.addEventListener 'resize', => @size() @draw = new Lampyridae.Draw @ ### Checks whether the given id selector exists; creating or registering accordingly. # If it does, it registers the current parent element for this object. # If it does not, it creates one under the given parent element. # # @param id [String] Name of the #id selector for the canvas element # @param parent [String] Name of the element to attach the canvas to (defaults to body) ### findOrMakeCanvas: (id, parent = @parent) -> @element = document.getElementById id if @element? then @parent = @element.parentElement else @element = document.createElement 'canvas' if parent == 'body' then @parent = document.body else @parent = document.getElementById parent @id id @appendCanvas() ### Appends a generated <canvas> tag to the DOM - if required. ### appendCanvas: () -> @parent.appendChild @element Lampyridae.Log.out "Appended \##{@element.id} to #{@parent.nodeName.toLowerCase()}\##{@parent.id}" # Access/Set/Get methods # ### Return or set the id selector of the canvas. # # @param id [String] The id string to set (optional; if needed) # @return [String] The current id selector of the canvas ### id: (id) -> if id? then @element.id = id return @element.id ### Return or set the width of the canvas. # # @param width [Number] The width to set (optional; if needed) # @return [Number] The current width of the canvas ### width: (width) -> if width? then @element.setAttribute 'width', width return @element.clientWidth ### Return or set the height of the canvas. # # @param height [Number] The width to set (optional; if needed) # @return [Number] The current height of the canvas ### height: (height) -> if height? then @element.setAttribute 'height', height return @element.clientHeight ### Set the overall size of the canvas. # Defaults to its current parent element's size. # # @param width [Number] The width to set (optional) # @param height [Number] The width to set (optional) ### size: (width = @parent.clientWidth, height = @parent.clientHeight) -> @width width; @height height ### Returns the current area of the canvas. # # @return [Number] The current area of the canvas ### area: () -> return @width() * @height() # Animation and update methods # ### Adds a function to the update stack. # # @f [Function] Function to call on Canvas.update ### addUpdate: (f) => if toString.call(f) isnt '[object Function]' throw new Error "Canvas.addUpdate requires a function" @_updateStack.push f ### Removes the top function from the update stack. # # @return [Bool] True if the top function has been removed; false if there's nothing left ### popUpdate: () => if @_updateStack.length > 0 @_updateStack.pop() return true return false ### Removes the first instance of the function from the top of the update stack. # # @f [Function] Function to stop calling on Canvas.update # @return [Bool] True if it has been found and removed; false otherwise # @note Iterates backwards through the update stack! ### removeUpdate: (f) => if toString.call(f) isnt '[object Function]' throw new Error "Canvas.addUpdate requires a function" for i in [@_updateStack.length - 1..0] by -1 if @_updateStack[i] == f @_updateStack.splice(i, 1) return true return false ### Iterates through the update stack and calls the update functions. ### update: () => i() for i in @_updateStack ### Animates the canvas! # Uses the functions in the update stack to add magic to the canvas. # # @note is controlled by the pause and stopAnimation() ### animate: () => unless @_stopAnim unless @_pauseAnim then @update() requestAnimationFrame @animate else @_stopAnim = false; @_pauseAnim = false ### Toggles the paused state of the canvas animation. ### pause: () => @_pauseAnim = !@_pauseAnim ### Stops the animation outright. ### stop: () => @_stopAnim = true # Helper Methods # ### Schedule a functon to call after a specified time # # @param time [Number] Time to wait in milliseconds # @param f [Function] Function to call after time has expired ### schedule: (time, f) -> setTimeout f, time ### Has the Canvas object acquired the 2d context (CanvasRenderingContext2D) api? # # @return [Bool] True if it does, false if it does not ### has2DContext: () -> if @context? then return @context.constructor == CanvasRenderingContext2D else return false # end class Lampyridae.Canvas module.exports = Lampyridae.Canvas
[ { "context": "returnValue field of the response object.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n###\r\nclass UpgradeProductV", "end": 712, "score": 0.9998797178268433, "start": 700, "tag": "NAME", "value": "Nathan Klick" } ]
Workspace/QRef/NodeServer/src/router/routes/rpc/admin/UpgradeProductVersionsRoute.coffee
qrefdev/qref
0
RpcRoute = require('../../../RpcRoute') QRefSlaveManager = require('../../../../db/QRefSlaveManager') RpcResponse = require('../../../../serialization/RpcResponse') UserAuth = require('../../../../security/UserAuth') https = require('https') async = require('async') ### Service route that returns the next available version of a given checklist. @example Service Methods (see {ChecklistVersionRpcRequest}) Request Format: application/json Response Format: application/json POST /services/rpc/aircraft/checklist/version @BODY - (Required) ChecklistVersionRpcRequest Returns the next available version number in the returnValue field of the response object. @author Nathan Klick @copyright QRef 2012 ### class UpgradeProductVersionsRoute extends RpcRoute constructor: () -> super [{ method: 'POST', path: '/upgradeProductVersions' }, { method: 'GET', path: '/upgradeProductVersions' }] post: (req, res) => if not @.isValidRequest(req) resp = new RpcResponse(null) resp.failure('Bad Request', 400) res.json(resp, 200) return token = req.param('token') UserAuth.isInRole(token, 'Administrators', (err, hasRole) => if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not hasRole resp = new RpcResponse(null) resp.failure('Not Authorized', 403) res.json(resp, 200) return async.forEach(QRefSlaveManager.getSlaves(), (item, cb) => @.upgradeProductVersions(item, cb) ,(err) => if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return resp = new RpcResponse(null) res.json(resp, 200) return ) ) upgradeProductVersions: (db, callback) => db.Product.find((err, arrProducts) => if err? callback(err) return if not arrProducts? or arrProducts.length == 0 callback(null) return async.forEach(arrProducts, (product, cb) => db.AircraftChecklist .where('manufacturer') .equals(product.manufacturer) .where('model') .equals(product.model) .where('user') .equals(null) .where('isDeleted') .equals(false) .sort('-version') .findOne((err, latestChecklist) => if err? cb(err) return if not latestChecklist? cb(new Error('No checklist found for the product.')) return if product.aircraftChecklist.toString() != latestChecklist._id.toString() product.aircraftChecklist = latestChecklist._id product.save(cb) ) ,(err) => callback(err) ) ) isValidRequest: (req) -> if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.token? true else false module.exports = new UpgradeProductVersionsRoute()
50761
RpcRoute = require('../../../RpcRoute') QRefSlaveManager = require('../../../../db/QRefSlaveManager') RpcResponse = require('../../../../serialization/RpcResponse') UserAuth = require('../../../../security/UserAuth') https = require('https') async = require('async') ### Service route that returns the next available version of a given checklist. @example Service Methods (see {ChecklistVersionRpcRequest}) Request Format: application/json Response Format: application/json POST /services/rpc/aircraft/checklist/version @BODY - (Required) ChecklistVersionRpcRequest Returns the next available version number in the returnValue field of the response object. @author <NAME> @copyright QRef 2012 ### class UpgradeProductVersionsRoute extends RpcRoute constructor: () -> super [{ method: 'POST', path: '/upgradeProductVersions' }, { method: 'GET', path: '/upgradeProductVersions' }] post: (req, res) => if not @.isValidRequest(req) resp = new RpcResponse(null) resp.failure('Bad Request', 400) res.json(resp, 200) return token = req.param('token') UserAuth.isInRole(token, 'Administrators', (err, hasRole) => if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not hasRole resp = new RpcResponse(null) resp.failure('Not Authorized', 403) res.json(resp, 200) return async.forEach(QRefSlaveManager.getSlaves(), (item, cb) => @.upgradeProductVersions(item, cb) ,(err) => if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return resp = new RpcResponse(null) res.json(resp, 200) return ) ) upgradeProductVersions: (db, callback) => db.Product.find((err, arrProducts) => if err? callback(err) return if not arrProducts? or arrProducts.length == 0 callback(null) return async.forEach(arrProducts, (product, cb) => db.AircraftChecklist .where('manufacturer') .equals(product.manufacturer) .where('model') .equals(product.model) .where('user') .equals(null) .where('isDeleted') .equals(false) .sort('-version') .findOne((err, latestChecklist) => if err? cb(err) return if not latestChecklist? cb(new Error('No checklist found for the product.')) return if product.aircraftChecklist.toString() != latestChecklist._id.toString() product.aircraftChecklist = latestChecklist._id product.save(cb) ) ,(err) => callback(err) ) ) isValidRequest: (req) -> if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.token? true else false module.exports = new UpgradeProductVersionsRoute()
true
RpcRoute = require('../../../RpcRoute') QRefSlaveManager = require('../../../../db/QRefSlaveManager') RpcResponse = require('../../../../serialization/RpcResponse') UserAuth = require('../../../../security/UserAuth') https = require('https') async = require('async') ### Service route that returns the next available version of a given checklist. @example Service Methods (see {ChecklistVersionRpcRequest}) Request Format: application/json Response Format: application/json POST /services/rpc/aircraft/checklist/version @BODY - (Required) ChecklistVersionRpcRequest Returns the next available version number in the returnValue field of the response object. @author PI:NAME:<NAME>END_PI @copyright QRef 2012 ### class UpgradeProductVersionsRoute extends RpcRoute constructor: () -> super [{ method: 'POST', path: '/upgradeProductVersions' }, { method: 'GET', path: '/upgradeProductVersions' }] post: (req, res) => if not @.isValidRequest(req) resp = new RpcResponse(null) resp.failure('Bad Request', 400) res.json(resp, 200) return token = req.param('token') UserAuth.isInRole(token, 'Administrators', (err, hasRole) => if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not hasRole resp = new RpcResponse(null) resp.failure('Not Authorized', 403) res.json(resp, 200) return async.forEach(QRefSlaveManager.getSlaves(), (item, cb) => @.upgradeProductVersions(item, cb) ,(err) => if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return resp = new RpcResponse(null) res.json(resp, 200) return ) ) upgradeProductVersions: (db, callback) => db.Product.find((err, arrProducts) => if err? callback(err) return if not arrProducts? or arrProducts.length == 0 callback(null) return async.forEach(arrProducts, (product, cb) => db.AircraftChecklist .where('manufacturer') .equals(product.manufacturer) .where('model') .equals(product.model) .where('user') .equals(null) .where('isDeleted') .equals(false) .sort('-version') .findOne((err, latestChecklist) => if err? cb(err) return if not latestChecklist? cb(new Error('No checklist found for the product.')) return if product.aircraftChecklist.toString() != latestChecklist._id.toString() product.aircraftChecklist = latestChecklist._id product.save(cb) ) ,(err) => callback(err) ) ) isValidRequest: (req) -> if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.token? true else false module.exports = new UpgradeProductVersionsRoute()
[ { "context": "oudao.com'\n path: '/openapi.do?keyfrom=atom-trans-en-zh&key=769450225&type=data&doctype=json&v", "end": 1053, "score": 0.5757845044136047, "start": 1053, "tag": "KEY", "value": "" }, { "context": "com'\n path: '/openapi.do?keyfrom=atom-trans-en-zh&key=769...
lib/trans-en-zh-view.coffee
alim0x/atom-trans-en-zh
13
http = require 'http' module.exports = class TransEnZhView constructor: (serializedState) -> # Create root element @element = document.createElement('div') @element.classList.add('trans-en-zh') # Create translate result elements query = document.createElement('div') query.classList.add('query') @element.appendChild(query) translation = document.createElement('div') translation.classList.add('translation') @element.appendChild(translation) basic = document.createElement('div') basic.classList.add('basic') @element.appendChild(basic) web = document.createElement('div') web.classList.add('web') @element.appendChild(web) # Returns an object that can be retrieved when package is activated serialize: -> # Tear down any state and detach destroy: -> @element.remove() getElement: -> @element getYoudao: (lookup, callback) -> data = '' lookup = encodeURI(lookup) options = host: 'fanyi.youdao.com' path: '/openapi.do?keyfrom=atom-trans-en-zh&key=769450225&type=data&doctype=json&version=1.1&q='+lookup req = http.get options, (res) -> res.on 'data', (chunk) -> data += chunk res.on 'end', () -> callback(data) req.on "error", (e) -> console.log "Erorr: {e.message}" getNothing: -> console.log 'nothing' @element.children[0].innerHTML = '_(:з」∠)_ Nothing selected...' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' gotIt: (data) => console.log 'got it' jsonData = JSON.parse data if jsonData.errorCode == 0 @element.children[0].innerHTML = jsonData.query @element.children[1].innerHTML = jsonData.translation pronounce = '' explains = '' webexplains = '<div class=\"webexplains\">网络释义</div>' if jsonData.basic != undefined if jsonData.basic['uk-phonetic'] != undefined pronounce = pronounce + '英 [' + jsonData.basic['uk-phonetic'] + '] ' if jsonData.basic['us-phonetic'] != undefined pronounce = pronounce + '美 [' + jsonData.basic['us-phonetic'] + '] ' else if jsonData.basic.phonetic != undefined pronounce = '[' + jsonData.phonetic + ']' pronounce = '<div class=\"pronounce\">' + pronounce + '</div><br />' if jsonData.basic.explains != undefined explains = explains + i + '<br />' for i in jsonData.basic.explains @element.children[2].innerHTML = pronounce + explains + '<hr />' if jsonData.web != undefined for item in jsonData.web webexplains = webexplains + item.key + ' : ' for j in item.value webexplains = webexplains + j + ' ' webexplains = webexplains + '<br />' @element.children[3].innerHTML = webexplains if jsonData.errorCode == 20 @element.children[0].innerHTML = '要翻译的文本过长' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' if jsonData.errorCode == 30 @element.children[0].innerHTML = '无法进行有效的翻译' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' if jsonData.errorCode == 40 @element.children[0].innerHTML = '不支持的语言类型' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' if jsonData.errorCode == 50 @element.children[0].innerHTML = '无效的key' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' if jsonData.errorCode == 60 @element.children[0].innerHTML = '无词典结果,仅在获取词典结果生效' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = ''
87237
http = require 'http' module.exports = class TransEnZhView constructor: (serializedState) -> # Create root element @element = document.createElement('div') @element.classList.add('trans-en-zh') # Create translate result elements query = document.createElement('div') query.classList.add('query') @element.appendChild(query) translation = document.createElement('div') translation.classList.add('translation') @element.appendChild(translation) basic = document.createElement('div') basic.classList.add('basic') @element.appendChild(basic) web = document.createElement('div') web.classList.add('web') @element.appendChild(web) # Returns an object that can be retrieved when package is activated serialize: -> # Tear down any state and detach destroy: -> @element.remove() getElement: -> @element getYoudao: (lookup, callback) -> data = '' lookup = encodeURI(lookup) options = host: 'fanyi.youdao.com' path: '/openapi.do?keyfrom=atom<KEY>-trans<KEY>-en<KEY>-zh&key=<KEY>&type=data&doctype=json&version=1.1&q='+lookup req = http.get options, (res) -> res.on 'data', (chunk) -> data += chunk res.on 'end', () -> callback(data) req.on "error", (e) -> console.log "Erorr: {e.message}" getNothing: -> console.log 'nothing' @element.children[0].innerHTML = '_(:з」∠)_ Nothing selected...' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' gotIt: (data) => console.log 'got it' jsonData = JSON.parse data if jsonData.errorCode == 0 @element.children[0].innerHTML = jsonData.query @element.children[1].innerHTML = jsonData.translation pronounce = '' explains = '' webexplains = '<div class=\"webexplains\">网络释义</div>' if jsonData.basic != undefined if jsonData.basic['uk-phonetic'] != undefined pronounce = pronounce + '英 [' + jsonData.basic['uk-phonetic'] + '] ' if jsonData.basic['us-phonetic'] != undefined pronounce = pronounce + '美 [' + jsonData.basic['us-phonetic'] + '] ' else if jsonData.basic.phonetic != undefined pronounce = '[' + jsonData.phonetic + ']' pronounce = '<div class=\"pronounce\">' + pronounce + '</div><br />' if jsonData.basic.explains != undefined explains = explains + i + '<br />' for i in jsonData.basic.explains @element.children[2].innerHTML = pronounce + explains + '<hr />' if jsonData.web != undefined for item in jsonData.web webexplains = webexplains + item.key + ' : ' for j in item.value webexplains = webexplains + j + ' ' webexplains = webexplains + '<br />' @element.children[3].innerHTML = webexplains if jsonData.errorCode == 20 @element.children[0].innerHTML = '要翻译的文本过长' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' if jsonData.errorCode == 30 @element.children[0].innerHTML = '无法进行有效的翻译' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' if jsonData.errorCode == 40 @element.children[0].innerHTML = '不支持的语言类型' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' if jsonData.errorCode == 50 @element.children[0].innerHTML = '无效的key' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' if jsonData.errorCode == 60 @element.children[0].innerHTML = '无词典结果,仅在获取词典结果生效' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = ''
true
http = require 'http' module.exports = class TransEnZhView constructor: (serializedState) -> # Create root element @element = document.createElement('div') @element.classList.add('trans-en-zh') # Create translate result elements query = document.createElement('div') query.classList.add('query') @element.appendChild(query) translation = document.createElement('div') translation.classList.add('translation') @element.appendChild(translation) basic = document.createElement('div') basic.classList.add('basic') @element.appendChild(basic) web = document.createElement('div') web.classList.add('web') @element.appendChild(web) # Returns an object that can be retrieved when package is activated serialize: -> # Tear down any state and detach destroy: -> @element.remove() getElement: -> @element getYoudao: (lookup, callback) -> data = '' lookup = encodeURI(lookup) options = host: 'fanyi.youdao.com' path: '/openapi.do?keyfrom=atomPI:KEY:<KEY>END_PI-transPI:KEY:<KEY>END_PI-enPI:KEY:<KEY>END_PI-zh&key=PI:KEY:<KEY>END_PI&type=data&doctype=json&version=1.1&q='+lookup req = http.get options, (res) -> res.on 'data', (chunk) -> data += chunk res.on 'end', () -> callback(data) req.on "error", (e) -> console.log "Erorr: {e.message}" getNothing: -> console.log 'nothing' @element.children[0].innerHTML = '_(:з」∠)_ Nothing selected...' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' gotIt: (data) => console.log 'got it' jsonData = JSON.parse data if jsonData.errorCode == 0 @element.children[0].innerHTML = jsonData.query @element.children[1].innerHTML = jsonData.translation pronounce = '' explains = '' webexplains = '<div class=\"webexplains\">网络释义</div>' if jsonData.basic != undefined if jsonData.basic['uk-phonetic'] != undefined pronounce = pronounce + '英 [' + jsonData.basic['uk-phonetic'] + '] ' if jsonData.basic['us-phonetic'] != undefined pronounce = pronounce + '美 [' + jsonData.basic['us-phonetic'] + '] ' else if jsonData.basic.phonetic != undefined pronounce = '[' + jsonData.phonetic + ']' pronounce = '<div class=\"pronounce\">' + pronounce + '</div><br />' if jsonData.basic.explains != undefined explains = explains + i + '<br />' for i in jsonData.basic.explains @element.children[2].innerHTML = pronounce + explains + '<hr />' if jsonData.web != undefined for item in jsonData.web webexplains = webexplains + item.key + ' : ' for j in item.value webexplains = webexplains + j + ' ' webexplains = webexplains + '<br />' @element.children[3].innerHTML = webexplains if jsonData.errorCode == 20 @element.children[0].innerHTML = '要翻译的文本过长' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' if jsonData.errorCode == 30 @element.children[0].innerHTML = '无法进行有效的翻译' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' if jsonData.errorCode == 40 @element.children[0].innerHTML = '不支持的语言类型' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' if jsonData.errorCode == 50 @element.children[0].innerHTML = '无效的key' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = '' if jsonData.errorCode == 60 @element.children[0].innerHTML = '无词典结果,仅在获取词典结果生效' @element.children[1].innerHTML = '' @element.children[2].innerHTML = '' @element.children[3].innerHTML = ''
[ { "context": " 'should update a File', ->\n file = { name: 'name', lastModified: date1, size: 123 }\n fileInfo", "end": 5305, "score": 0.9367552995681763, "start": 5301, "tag": "NAME", "value": "name" }, { "context": "ied: date1, size: 123 }\n fileInfo = { name: 'name'...
test/MassUpload/UploadCollectionSpec.coffee
overview/js-mass-upload
2
_ = require('underscore') UploadCollection = require('../../src/MassUpload/UploadCollection') Upload = require('../../src/MassUpload/Upload') describe 'MassUpload/UploadCollection', -> date1 = new Date('Mon, 12 Aug 2013 10:02:54 -0400').valueOf() file1 = { name: 'file1.txt', lastModified: date1, size: 10000 } file2 = { name: 'file2.txt', lastModified: date1, size: 20000 } fileInfo1 = { name: 'file1.txt', lastModified: date1, loaded: 2000, total: 10000 } fileInfo2 = { name: 'file2.txt', lastModified: date1, loaded: 3000, total: 20000 } subject = undefined beforeEach -> subject = new UploadCollection([]) afterEach -> subject?.off() describe 'reset', -> it 'should reset to empty list without params', -> subject.reset() expect(subject.length).to.eq(0) it 'should return the collection', -> resetSpy = sinon.spy() subject.on('reset', resetSpy) subject.reset() expect(resetSpy).to.have.been.calledWith(subject) describe 'remove', -> it 'should remove the upload', -> subject.on('remove', spy = sinon.spy()) subject.reset([ { file: file1, fileInfo: fileInfo1 } { file: file2, fileInfo: fileInfo2 } ]) upload = subject.get('file2.txt') subject.remove(upload) expect(subject.length).to.eq(1) expect(subject.get('file2.txt')).not.to.exist expect(subject.get('file1.txt')).to.exist expect(spy).to.have.been.calledWith(upload, subject) describe 'addFiles() when file does not exist', -> addBatchArgs = null beforeEach -> addBatchArgs = [] subject.on('add-batch', (uploads) -> addBatchArgs.push(uploads)) subject.addFiles([ file1, file2 ]) afterEach -> subject.off('add-batch') it 'should create Upload objects', -> expect(subject.length).to.eq(2) upload1 = subject.models[0] upload2 = subject.models[1] expect(upload1.attributes.file).to.eq(file1) expect(upload1.attributes.fileInfo).to.eq(null) expect(upload1.attributes.error).to.eq(null) expect(upload2.attributes.file).to.eq(file2) expect(upload2.attributes.fileInfo).to.eq(null) expect(upload2.attributes.error).to.eq(null) it 'should trigger add-batch', -> expect(addBatchArgs.length).to.eq(1) expect(addBatchArgs[0].length).to.eq(2) expect(addBatchArgs[0][0].attributes.file).to.eq(file1) describe 'addFiles() when an un-uploaded file already exists', -> file1 = { name: 'file1.txt', lastModified: date1, size: 10000 } addBatchArgs = null beforeEach -> addBatchArgs = [] subject.on('add-batch', (uploads) -> addBatchArgs.push(uploads)) subject.addFiles([ file1 ]) subject.addFiles([ file1 ]) afterEach -> subject.off('add-batch') it 'should not duplicate the file', -> expect(subject.length).to.eq(1) it 'should not trigger add-batch when merging', -> expect(addBatchArgs.length).to.eq(1) describe 'addFileInfos() when fileInfo does not exist', -> addBatchArgs = null beforeEach -> addBatchArgs = [] subject.on('add-batch', (uploads) -> addBatchArgs.push(uploads)) subject.addFileInfos([fileInfo1]) afterEach -> subject.off('add-batch') it 'should create Upload objects', -> expect(subject.length).to.eq(1) upload1 = subject.models[0] expect(upload1.attributes.file).to.eq(null) expect(upload1.attributes.fileInfo).to.eq(fileInfo1) expect(upload1.attributes.error).to.eq(null) it 'should not re-add existing fileInfos', -> subject.addFileInfos([fileInfo1]) expect(subject.length).to.eq(1) it 'should trigger add-batch', -> expect(addBatchArgs.length).to.eq(1) expect(addBatchArgs[0].length).to.eq(1) expect(addBatchArgs[0][0].attributes.fileInfo).to.eq(fileInfo1) describe 'with a file-backed Upload', -> file1 = { name: 'file1.txt', lastModified: date1, size: 10000 } beforeEach -> subject.addFiles([file1]) it 'should merge a fileInfo through addFileInfos()', -> fileInfo1 = { name: 'file1.txt', lastModified: date1, loaded: 2000, total: 10000 } subject.addFileInfos([fileInfo1]) expect(subject.length).to.eq(1) upload = subject.models[0] expect(upload.attributes.file).to.eq(file1) expect(upload.attributes.fileInfo).to.eq(fileInfo1) describe 'with a fileInfo-backed Upload', -> fileInfo1 = { name: 'file1.txt', lastModified: date1, loaded: 2000, total: 10000 } beforeEach -> subject.addFileInfos([fileInfo1]) it 'should merge a file through addFiles()', -> file1 = { name: 'file1.txt', lastModified: date1, size: 10000 } subject.addFiles([file1]) expect(subject.length).to.eq(1) upload = subject.models[0] expect(upload.attributes.file).to.eq(file1) expect(upload.attributes.fileInfo).to.eq(fileInfo1) describe 'addWithMerge', -> it 'should add a File', -> file = { name: 'name', lastModified: date1, size: 123 } subject.addWithMerge([{ id: 'id', file: file }]) expect(subject.models).to.have.length(1) expect(subject.models[0].id).to.eq('id') expect(subject.models[0].file).to.eq(file) it 'should update a File', -> file = { name: 'name', lastModified: date1, size: 123 } fileInfo = { name: 'name', lastModified: date1, total: 123, loaded: 10 } subject.addWithMerge([{ id: 'id', file: file }]) subject.addWithMerge([{ id: 'id', file: file, fileInfo: fileInfo }]) expect(subject.models).to.have.length(1) expect(subject.models[0].fileInfo).to.eq(fileInfo) describe 'next', -> it 'should return null on empty collection', -> expect(subject.next()).to.eq(null) it 'should return null if all files are uploaded', -> subject.reset([ { file: file1, fileInfo: _.defaults({ loaded: file1.size }, fileInfo1), error: null } ]) expect(subject.next()).to.eq(null) it 'should return null if an unfinished file was not selected by the user', -> subject.reset([ { file: null, fileInfo: fileInfo1, error: null } ]) expect(subject.next()).to.eq(null) it 'should return null if all files have errors', -> subject.reset([ { file: file1, fileInfo: fileInfo1, error: 'error' } ]) expect(subject.next()).to.eq(null) it 'should return an un-uploaded file', -> upload = { file: file1, fileInfo: fileInfo1, error: null } subject.reset([ upload ]) expect(subject.next()).to.eq(subject.get('file1.txt')) it 'should return a deleting file ahead of an uploading file', -> subject.reset([ { file: file1, fileInfo: fileInfo1, uploading: true, error: null } { file: file2, fileInfo: fileInfo2, deleting: true, error: null } ]) expect(subject.next()).to.eq(subject.get('file2.txt')) it 'should return an uploading file ahead of an unfinished file', -> subject.reset([ { file: file1, fileInfo: fileInfo1, error: null } { file: file2, fileInfo: fileInfo2, uploading: true, error: null } ]) expect(subject.next()).to.eq(subject.get('file2.txt')) it 'should return an unfinished file ahead of an unstarted file', -> subject.reset([ { file: file1, fileInfo: null, error: null } { file: file2, fileInfo: fileInfo2, error: null } ]) expect(subject.next()).to.eq(subject.get('file2.txt')) it 'should return files in collection order', -> subject.reset([ { file: file2, fileInfo: null, error: null } { file: file1, fileInfo: null, error: null } ]) expect(subject.next()).to.eq(subject.get('file2.txt')) it 'should return a second file after the first is uploaded', -> subject.reset([ { file: file1, fileInfo: null, error: null } { file: file2, fileInfo: null, error: null } ]) subject.get('file1.txt').set(fileInfo: _.extend({}, fileInfo1, { loaded: 10000 })) expect(subject.next()).to.eq(subject.get('file2.txt'))
29818
_ = require('underscore') UploadCollection = require('../../src/MassUpload/UploadCollection') Upload = require('../../src/MassUpload/Upload') describe 'MassUpload/UploadCollection', -> date1 = new Date('Mon, 12 Aug 2013 10:02:54 -0400').valueOf() file1 = { name: 'file1.txt', lastModified: date1, size: 10000 } file2 = { name: 'file2.txt', lastModified: date1, size: 20000 } fileInfo1 = { name: 'file1.txt', lastModified: date1, loaded: 2000, total: 10000 } fileInfo2 = { name: 'file2.txt', lastModified: date1, loaded: 3000, total: 20000 } subject = undefined beforeEach -> subject = new UploadCollection([]) afterEach -> subject?.off() describe 'reset', -> it 'should reset to empty list without params', -> subject.reset() expect(subject.length).to.eq(0) it 'should return the collection', -> resetSpy = sinon.spy() subject.on('reset', resetSpy) subject.reset() expect(resetSpy).to.have.been.calledWith(subject) describe 'remove', -> it 'should remove the upload', -> subject.on('remove', spy = sinon.spy()) subject.reset([ { file: file1, fileInfo: fileInfo1 } { file: file2, fileInfo: fileInfo2 } ]) upload = subject.get('file2.txt') subject.remove(upload) expect(subject.length).to.eq(1) expect(subject.get('file2.txt')).not.to.exist expect(subject.get('file1.txt')).to.exist expect(spy).to.have.been.calledWith(upload, subject) describe 'addFiles() when file does not exist', -> addBatchArgs = null beforeEach -> addBatchArgs = [] subject.on('add-batch', (uploads) -> addBatchArgs.push(uploads)) subject.addFiles([ file1, file2 ]) afterEach -> subject.off('add-batch') it 'should create Upload objects', -> expect(subject.length).to.eq(2) upload1 = subject.models[0] upload2 = subject.models[1] expect(upload1.attributes.file).to.eq(file1) expect(upload1.attributes.fileInfo).to.eq(null) expect(upload1.attributes.error).to.eq(null) expect(upload2.attributes.file).to.eq(file2) expect(upload2.attributes.fileInfo).to.eq(null) expect(upload2.attributes.error).to.eq(null) it 'should trigger add-batch', -> expect(addBatchArgs.length).to.eq(1) expect(addBatchArgs[0].length).to.eq(2) expect(addBatchArgs[0][0].attributes.file).to.eq(file1) describe 'addFiles() when an un-uploaded file already exists', -> file1 = { name: 'file1.txt', lastModified: date1, size: 10000 } addBatchArgs = null beforeEach -> addBatchArgs = [] subject.on('add-batch', (uploads) -> addBatchArgs.push(uploads)) subject.addFiles([ file1 ]) subject.addFiles([ file1 ]) afterEach -> subject.off('add-batch') it 'should not duplicate the file', -> expect(subject.length).to.eq(1) it 'should not trigger add-batch when merging', -> expect(addBatchArgs.length).to.eq(1) describe 'addFileInfos() when fileInfo does not exist', -> addBatchArgs = null beforeEach -> addBatchArgs = [] subject.on('add-batch', (uploads) -> addBatchArgs.push(uploads)) subject.addFileInfos([fileInfo1]) afterEach -> subject.off('add-batch') it 'should create Upload objects', -> expect(subject.length).to.eq(1) upload1 = subject.models[0] expect(upload1.attributes.file).to.eq(null) expect(upload1.attributes.fileInfo).to.eq(fileInfo1) expect(upload1.attributes.error).to.eq(null) it 'should not re-add existing fileInfos', -> subject.addFileInfos([fileInfo1]) expect(subject.length).to.eq(1) it 'should trigger add-batch', -> expect(addBatchArgs.length).to.eq(1) expect(addBatchArgs[0].length).to.eq(1) expect(addBatchArgs[0][0].attributes.fileInfo).to.eq(fileInfo1) describe 'with a file-backed Upload', -> file1 = { name: 'file1.txt', lastModified: date1, size: 10000 } beforeEach -> subject.addFiles([file1]) it 'should merge a fileInfo through addFileInfos()', -> fileInfo1 = { name: 'file1.txt', lastModified: date1, loaded: 2000, total: 10000 } subject.addFileInfos([fileInfo1]) expect(subject.length).to.eq(1) upload = subject.models[0] expect(upload.attributes.file).to.eq(file1) expect(upload.attributes.fileInfo).to.eq(fileInfo1) describe 'with a fileInfo-backed Upload', -> fileInfo1 = { name: 'file1.txt', lastModified: date1, loaded: 2000, total: 10000 } beforeEach -> subject.addFileInfos([fileInfo1]) it 'should merge a file through addFiles()', -> file1 = { name: 'file1.txt', lastModified: date1, size: 10000 } subject.addFiles([file1]) expect(subject.length).to.eq(1) upload = subject.models[0] expect(upload.attributes.file).to.eq(file1) expect(upload.attributes.fileInfo).to.eq(fileInfo1) describe 'addWithMerge', -> it 'should add a File', -> file = { name: 'name', lastModified: date1, size: 123 } subject.addWithMerge([{ id: 'id', file: file }]) expect(subject.models).to.have.length(1) expect(subject.models[0].id).to.eq('id') expect(subject.models[0].file).to.eq(file) it 'should update a File', -> file = { name: '<NAME>', lastModified: date1, size: 123 } fileInfo = { name: '<NAME>', lastModified: date1, total: 123, loaded: 10 } subject.addWithMerge([{ id: 'id', file: file }]) subject.addWithMerge([{ id: 'id', file: file, fileInfo: fileInfo }]) expect(subject.models).to.have.length(1) expect(subject.models[0].fileInfo).to.eq(fileInfo) describe 'next', -> it 'should return null on empty collection', -> expect(subject.next()).to.eq(null) it 'should return null if all files are uploaded', -> subject.reset([ { file: file1, fileInfo: _.defaults({ loaded: file1.size }, fileInfo1), error: null } ]) expect(subject.next()).to.eq(null) it 'should return null if an unfinished file was not selected by the user', -> subject.reset([ { file: null, fileInfo: fileInfo1, error: null } ]) expect(subject.next()).to.eq(null) it 'should return null if all files have errors', -> subject.reset([ { file: file1, fileInfo: fileInfo1, error: 'error' } ]) expect(subject.next()).to.eq(null) it 'should return an un-uploaded file', -> upload = { file: file1, fileInfo: fileInfo1, error: null } subject.reset([ upload ]) expect(subject.next()).to.eq(subject.get('file1.txt')) it 'should return a deleting file ahead of an uploading file', -> subject.reset([ { file: file1, fileInfo: fileInfo1, uploading: true, error: null } { file: file2, fileInfo: fileInfo2, deleting: true, error: null } ]) expect(subject.next()).to.eq(subject.get('file2.txt')) it 'should return an uploading file ahead of an unfinished file', -> subject.reset([ { file: file1, fileInfo: fileInfo1, error: null } { file: file2, fileInfo: fileInfo2, uploading: true, error: null } ]) expect(subject.next()).to.eq(subject.get('file2.txt')) it 'should return an unfinished file ahead of an unstarted file', -> subject.reset([ { file: file1, fileInfo: null, error: null } { file: file2, fileInfo: fileInfo2, error: null } ]) expect(subject.next()).to.eq(subject.get('file2.txt')) it 'should return files in collection order', -> subject.reset([ { file: file2, fileInfo: null, error: null } { file: file1, fileInfo: null, error: null } ]) expect(subject.next()).to.eq(subject.get('file2.txt')) it 'should return a second file after the first is uploaded', -> subject.reset([ { file: file1, fileInfo: null, error: null } { file: file2, fileInfo: null, error: null } ]) subject.get('file1.txt').set(fileInfo: _.extend({}, fileInfo1, { loaded: 10000 })) expect(subject.next()).to.eq(subject.get('file2.txt'))
true
_ = require('underscore') UploadCollection = require('../../src/MassUpload/UploadCollection') Upload = require('../../src/MassUpload/Upload') describe 'MassUpload/UploadCollection', -> date1 = new Date('Mon, 12 Aug 2013 10:02:54 -0400').valueOf() file1 = { name: 'file1.txt', lastModified: date1, size: 10000 } file2 = { name: 'file2.txt', lastModified: date1, size: 20000 } fileInfo1 = { name: 'file1.txt', lastModified: date1, loaded: 2000, total: 10000 } fileInfo2 = { name: 'file2.txt', lastModified: date1, loaded: 3000, total: 20000 } subject = undefined beforeEach -> subject = new UploadCollection([]) afterEach -> subject?.off() describe 'reset', -> it 'should reset to empty list without params', -> subject.reset() expect(subject.length).to.eq(0) it 'should return the collection', -> resetSpy = sinon.spy() subject.on('reset', resetSpy) subject.reset() expect(resetSpy).to.have.been.calledWith(subject) describe 'remove', -> it 'should remove the upload', -> subject.on('remove', spy = sinon.spy()) subject.reset([ { file: file1, fileInfo: fileInfo1 } { file: file2, fileInfo: fileInfo2 } ]) upload = subject.get('file2.txt') subject.remove(upload) expect(subject.length).to.eq(1) expect(subject.get('file2.txt')).not.to.exist expect(subject.get('file1.txt')).to.exist expect(spy).to.have.been.calledWith(upload, subject) describe 'addFiles() when file does not exist', -> addBatchArgs = null beforeEach -> addBatchArgs = [] subject.on('add-batch', (uploads) -> addBatchArgs.push(uploads)) subject.addFiles([ file1, file2 ]) afterEach -> subject.off('add-batch') it 'should create Upload objects', -> expect(subject.length).to.eq(2) upload1 = subject.models[0] upload2 = subject.models[1] expect(upload1.attributes.file).to.eq(file1) expect(upload1.attributes.fileInfo).to.eq(null) expect(upload1.attributes.error).to.eq(null) expect(upload2.attributes.file).to.eq(file2) expect(upload2.attributes.fileInfo).to.eq(null) expect(upload2.attributes.error).to.eq(null) it 'should trigger add-batch', -> expect(addBatchArgs.length).to.eq(1) expect(addBatchArgs[0].length).to.eq(2) expect(addBatchArgs[0][0].attributes.file).to.eq(file1) describe 'addFiles() when an un-uploaded file already exists', -> file1 = { name: 'file1.txt', lastModified: date1, size: 10000 } addBatchArgs = null beforeEach -> addBatchArgs = [] subject.on('add-batch', (uploads) -> addBatchArgs.push(uploads)) subject.addFiles([ file1 ]) subject.addFiles([ file1 ]) afterEach -> subject.off('add-batch') it 'should not duplicate the file', -> expect(subject.length).to.eq(1) it 'should not trigger add-batch when merging', -> expect(addBatchArgs.length).to.eq(1) describe 'addFileInfos() when fileInfo does not exist', -> addBatchArgs = null beforeEach -> addBatchArgs = [] subject.on('add-batch', (uploads) -> addBatchArgs.push(uploads)) subject.addFileInfos([fileInfo1]) afterEach -> subject.off('add-batch') it 'should create Upload objects', -> expect(subject.length).to.eq(1) upload1 = subject.models[0] expect(upload1.attributes.file).to.eq(null) expect(upload1.attributes.fileInfo).to.eq(fileInfo1) expect(upload1.attributes.error).to.eq(null) it 'should not re-add existing fileInfos', -> subject.addFileInfos([fileInfo1]) expect(subject.length).to.eq(1) it 'should trigger add-batch', -> expect(addBatchArgs.length).to.eq(1) expect(addBatchArgs[0].length).to.eq(1) expect(addBatchArgs[0][0].attributes.fileInfo).to.eq(fileInfo1) describe 'with a file-backed Upload', -> file1 = { name: 'file1.txt', lastModified: date1, size: 10000 } beforeEach -> subject.addFiles([file1]) it 'should merge a fileInfo through addFileInfos()', -> fileInfo1 = { name: 'file1.txt', lastModified: date1, loaded: 2000, total: 10000 } subject.addFileInfos([fileInfo1]) expect(subject.length).to.eq(1) upload = subject.models[0] expect(upload.attributes.file).to.eq(file1) expect(upload.attributes.fileInfo).to.eq(fileInfo1) describe 'with a fileInfo-backed Upload', -> fileInfo1 = { name: 'file1.txt', lastModified: date1, loaded: 2000, total: 10000 } beforeEach -> subject.addFileInfos([fileInfo1]) it 'should merge a file through addFiles()', -> file1 = { name: 'file1.txt', lastModified: date1, size: 10000 } subject.addFiles([file1]) expect(subject.length).to.eq(1) upload = subject.models[0] expect(upload.attributes.file).to.eq(file1) expect(upload.attributes.fileInfo).to.eq(fileInfo1) describe 'addWithMerge', -> it 'should add a File', -> file = { name: 'name', lastModified: date1, size: 123 } subject.addWithMerge([{ id: 'id', file: file }]) expect(subject.models).to.have.length(1) expect(subject.models[0].id).to.eq('id') expect(subject.models[0].file).to.eq(file) it 'should update a File', -> file = { name: 'PI:NAME:<NAME>END_PI', lastModified: date1, size: 123 } fileInfo = { name: 'PI:NAME:<NAME>END_PI', lastModified: date1, total: 123, loaded: 10 } subject.addWithMerge([{ id: 'id', file: file }]) subject.addWithMerge([{ id: 'id', file: file, fileInfo: fileInfo }]) expect(subject.models).to.have.length(1) expect(subject.models[0].fileInfo).to.eq(fileInfo) describe 'next', -> it 'should return null on empty collection', -> expect(subject.next()).to.eq(null) it 'should return null if all files are uploaded', -> subject.reset([ { file: file1, fileInfo: _.defaults({ loaded: file1.size }, fileInfo1), error: null } ]) expect(subject.next()).to.eq(null) it 'should return null if an unfinished file was not selected by the user', -> subject.reset([ { file: null, fileInfo: fileInfo1, error: null } ]) expect(subject.next()).to.eq(null) it 'should return null if all files have errors', -> subject.reset([ { file: file1, fileInfo: fileInfo1, error: 'error' } ]) expect(subject.next()).to.eq(null) it 'should return an un-uploaded file', -> upload = { file: file1, fileInfo: fileInfo1, error: null } subject.reset([ upload ]) expect(subject.next()).to.eq(subject.get('file1.txt')) it 'should return a deleting file ahead of an uploading file', -> subject.reset([ { file: file1, fileInfo: fileInfo1, uploading: true, error: null } { file: file2, fileInfo: fileInfo2, deleting: true, error: null } ]) expect(subject.next()).to.eq(subject.get('file2.txt')) it 'should return an uploading file ahead of an unfinished file', -> subject.reset([ { file: file1, fileInfo: fileInfo1, error: null } { file: file2, fileInfo: fileInfo2, uploading: true, error: null } ]) expect(subject.next()).to.eq(subject.get('file2.txt')) it 'should return an unfinished file ahead of an unstarted file', -> subject.reset([ { file: file1, fileInfo: null, error: null } { file: file2, fileInfo: fileInfo2, error: null } ]) expect(subject.next()).to.eq(subject.get('file2.txt')) it 'should return files in collection order', -> subject.reset([ { file: file2, fileInfo: null, error: null } { file: file1, fileInfo: null, error: null } ]) expect(subject.next()).to.eq(subject.get('file2.txt')) it 'should return a second file after the first is uploaded', -> subject.reset([ { file: file1, fileInfo: null, error: null } { file: file2, fileInfo: null, error: null } ]) subject.get('file1.txt').set(fileInfo: _.extend({}, fileInfo1, { loaded: 10000 })) expect(subject.next()).to.eq(subject.get('file2.txt'))
[ { "context": "#---------------------\n# Requests\n#\n# Author : Redy Ru\n# Email : redy.ru@gmail.com\n# License : MIT\n# Des", "end": 54, "score": 0.9998732805252075, "start": 47, "tag": "NAME", "value": "Redy Ru" }, { "context": "--------\n# Requests\n#\n# Author : Redy Ru\n# Email ...
client/src/libs/requests.coffee
Soopro/totoro
0
#--------------------- # Requests # # Author : Redy Ru # Email : redy.ru@gmail.com # License : MIT # Description: Requests is a wrapper for wx.request. # Options: # - show_navbar_loading: `bool` display navbar loading icon while requesting. # - before_request: `function` run before request. # - after_success: `function` run after request success. # - after_reject: `function` run after request reject. #--------------------- version = '1.0.0' config = common: interceptor: (opts)-> return opts _interceptor = (opts, custom_interceptor)-> try config.common.interceptor(opts) catch e console.error e if typeof(custom_interceptor) is 'function' custom_interceptor(opts) return opts request = (method, url, opts)-> opts = {} if not opts opts.method = method opts.url = url opts = _interceptor(opts, opts.interceptor) promise = new Promise (resolve, reject)-> if opts.show_navbar_loading wx.showNavigationBarLoading() opts.success = (res) -> if res.statusCode >= 400 if typeof(opts.after_reject) is 'function' opts.after_reject(res) reject(res) else if typeof(opts.after_success) is 'function' opts.after_success(res) resolve(res.data, res) opts.fail = (res) -> reject(res) opts.complete = -> if opts.show_navbar_loading wx.hideNavigationBarLoading() wx.request(opts) return promise request_get = (url, args, opts)-> opts = {} if not opts opts.data = args request('GET', url, opts) request_put = (url, data, opts)-> opts = {} if not opts opts.data = data request('PUT', url, opts) request_post = (url, data, opts)-> opts = {} if not opts opts.data = data request('POST', url, opts) request_del = (url, args, opts)-> opts = {} if not opts opts.data = args request('DELETE', url, opts) requests = version: version config: config request: request get: request_get put: request_put update: request_put post: request_post del: request_del remove: request_del module.exports = requests
12368
#--------------------- # Requests # # Author : <NAME> # Email : <EMAIL> # License : MIT # Description: Requests is a wrapper for wx.request. # Options: # - show_navbar_loading: `bool` display navbar loading icon while requesting. # - before_request: `function` run before request. # - after_success: `function` run after request success. # - after_reject: `function` run after request reject. #--------------------- version = '1.0.0' config = common: interceptor: (opts)-> return opts _interceptor = (opts, custom_interceptor)-> try config.common.interceptor(opts) catch e console.error e if typeof(custom_interceptor) is 'function' custom_interceptor(opts) return opts request = (method, url, opts)-> opts = {} if not opts opts.method = method opts.url = url opts = _interceptor(opts, opts.interceptor) promise = new Promise (resolve, reject)-> if opts.show_navbar_loading wx.showNavigationBarLoading() opts.success = (res) -> if res.statusCode >= 400 if typeof(opts.after_reject) is 'function' opts.after_reject(res) reject(res) else if typeof(opts.after_success) is 'function' opts.after_success(res) resolve(res.data, res) opts.fail = (res) -> reject(res) opts.complete = -> if opts.show_navbar_loading wx.hideNavigationBarLoading() wx.request(opts) return promise request_get = (url, args, opts)-> opts = {} if not opts opts.data = args request('GET', url, opts) request_put = (url, data, opts)-> opts = {} if not opts opts.data = data request('PUT', url, opts) request_post = (url, data, opts)-> opts = {} if not opts opts.data = data request('POST', url, opts) request_del = (url, args, opts)-> opts = {} if not opts opts.data = args request('DELETE', url, opts) requests = version: version config: config request: request get: request_get put: request_put update: request_put post: request_post del: request_del remove: request_del module.exports = requests
true
#--------------------- # Requests # # Author : PI:NAME:<NAME>END_PI # Email : PI:EMAIL:<EMAIL>END_PI # License : MIT # Description: Requests is a wrapper for wx.request. # Options: # - show_navbar_loading: `bool` display navbar loading icon while requesting. # - before_request: `function` run before request. # - after_success: `function` run after request success. # - after_reject: `function` run after request reject. #--------------------- version = '1.0.0' config = common: interceptor: (opts)-> return opts _interceptor = (opts, custom_interceptor)-> try config.common.interceptor(opts) catch e console.error e if typeof(custom_interceptor) is 'function' custom_interceptor(opts) return opts request = (method, url, opts)-> opts = {} if not opts opts.method = method opts.url = url opts = _interceptor(opts, opts.interceptor) promise = new Promise (resolve, reject)-> if opts.show_navbar_loading wx.showNavigationBarLoading() opts.success = (res) -> if res.statusCode >= 400 if typeof(opts.after_reject) is 'function' opts.after_reject(res) reject(res) else if typeof(opts.after_success) is 'function' opts.after_success(res) resolve(res.data, res) opts.fail = (res) -> reject(res) opts.complete = -> if opts.show_navbar_loading wx.hideNavigationBarLoading() wx.request(opts) return promise request_get = (url, args, opts)-> opts = {} if not opts opts.data = args request('GET', url, opts) request_put = (url, data, opts)-> opts = {} if not opts opts.data = data request('PUT', url, opts) request_post = (url, data, opts)-> opts = {} if not opts opts.data = data request('POST', url, opts) request_del = (url, args, opts)-> opts = {} if not opts opts.data = args request('DELETE', url, opts) requests = version: version config: config request: request get: request_get put: request_put update: request_put post: request_post del: request_del remove: request_del module.exports = requests
[ { "context": "class DataBoard\n @keys = ['pinnedThreads', 'hiddenThreads', 'hiddenPosts', 'lastReadPosts'", "end": 41, "score": 0.9741781949996948, "start": 28, "tag": "KEY", "value": "pinnedThreads" }, { "context": "class DataBoard\n @keys = ['pinnedThreads', 'hiddenThreads', 'hid...
src/General/DataBoard.coffee
N3X15/4chan-x
1
class DataBoard @keys = ['pinnedThreads', 'hiddenThreads', 'hiddenPosts', 'lastReadPosts', 'yourPosts', 'watchedThreads'] constructor: (@key, sync, dontClean) -> @data = Conf[key] $.sync key, @onSync @clean() unless dontClean return unless sync # Chrome also fires the onChanged callback on the current tab, # so we only start syncing when we're ready. init = => $.off d, '4chanXInitFinished', init @sync = sync $.on d, '4chanXInitFinished', init save: -> $.set @key, @data delete: ({boardID, threadID, postID}) -> if postID delete @data.boards[boardID][threadID][postID] @deleteIfEmpty {boardID, threadID} else if threadID delete @data.boards[boardID][threadID] @deleteIfEmpty {boardID} else delete @data.boards[boardID] @save() deleteIfEmpty: ({boardID, threadID}) -> if threadID unless Object.keys(@data.boards[boardID][threadID]).length delete @data.boards[boardID][threadID] @deleteIfEmpty {boardID} else unless Object.keys(@data.boards[boardID]).length delete @data.boards[boardID] set: ({boardID, threadID, postID, val}) -> if postID isnt undefined ((@data.boards[boardID] or= {})[threadID] or= {})[postID] = val else if threadID isnt undefined (@data.boards[boardID] or= {})[threadID] = val else @data.boards[boardID] = val @save() get: ({boardID, threadID, postID, defaultValue}) -> if board = @data.boards[boardID] unless threadID if postID for ID, thread in board if postID of thread val = thread[postID] break else val = board else if thread = board[threadID] val = if postID thread[postID] else thread val or defaultValue clean: -> now = Date.now() return if (@data.lastChecked or 0) > now - 2 * $.HOUR for boardID of @data.boards @deleteIfEmpty {boardID} @ajaxClean boardID if boardID of @data.boards @data.lastChecked = now @save() ajaxClean: (boardID) -> $.cache "//a.4cdn.org/#{boardID}/threads.json", (e) => if e.target.status isnt 200 @delete {boardID} if e.target.status is 404 return board = @data.boards[boardID] threads = {} for page in e.target.response for thread in page.threads when thread.no of board threads[thread.no] = board[thread.no] count = Object.keys(threads).length return if count is Object.keys(board).length # Nothing changed. if count @set {boardID, val: threads} else @delete {boardID} onSync: (data) => @data = data or boards: {} @sync?()
166715
class DataBoard @keys = ['<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>', '<KEY>'] constructor: (@key, sync, dontClean) -> @data = Conf[key] $.sync key, @onSync @clean() unless dontClean return unless sync # Chrome also fires the onChanged callback on the current tab, # so we only start syncing when we're ready. init = => $.off d, '4chanXInitFinished', init @sync = sync $.on d, '4chanXInitFinished', init save: -> $.set @key, @data delete: ({boardID, threadID, postID}) -> if postID delete @data.boards[boardID][threadID][postID] @deleteIfEmpty {boardID, threadID} else if threadID delete @data.boards[boardID][threadID] @deleteIfEmpty {boardID} else delete @data.boards[boardID] @save() deleteIfEmpty: ({boardID, threadID}) -> if threadID unless Object.keys(@data.boards[boardID][threadID]).length delete @data.boards[boardID][threadID] @deleteIfEmpty {boardID} else unless Object.keys(@data.boards[boardID]).length delete @data.boards[boardID] set: ({boardID, threadID, postID, val}) -> if postID isnt undefined ((@data.boards[boardID] or= {})[threadID] or= {})[postID] = val else if threadID isnt undefined (@data.boards[boardID] or= {})[threadID] = val else @data.boards[boardID] = val @save() get: ({boardID, threadID, postID, defaultValue}) -> if board = @data.boards[boardID] unless threadID if postID for ID, thread in board if postID of thread val = thread[postID] break else val = board else if thread = board[threadID] val = if postID thread[postID] else thread val or defaultValue clean: -> now = Date.now() return if (@data.lastChecked or 0) > now - 2 * $.HOUR for boardID of @data.boards @deleteIfEmpty {boardID} @ajaxClean boardID if boardID of @data.boards @data.lastChecked = now @save() ajaxClean: (boardID) -> $.cache "//a.4cdn.org/#{boardID}/threads.json", (e) => if e.target.status isnt 200 @delete {boardID} if e.target.status is 404 return board = @data.boards[boardID] threads = {} for page in e.target.response for thread in page.threads when thread.no of board threads[thread.no] = board[thread.no] count = Object.keys(threads).length return if count is Object.keys(board).length # Nothing changed. if count @set {boardID, val: threads} else @delete {boardID} onSync: (data) => @data = data or boards: {} @sync?()
true
class DataBoard @keys = ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI'] constructor: (@key, sync, dontClean) -> @data = Conf[key] $.sync key, @onSync @clean() unless dontClean return unless sync # Chrome also fires the onChanged callback on the current tab, # so we only start syncing when we're ready. init = => $.off d, '4chanXInitFinished', init @sync = sync $.on d, '4chanXInitFinished', init save: -> $.set @key, @data delete: ({boardID, threadID, postID}) -> if postID delete @data.boards[boardID][threadID][postID] @deleteIfEmpty {boardID, threadID} else if threadID delete @data.boards[boardID][threadID] @deleteIfEmpty {boardID} else delete @data.boards[boardID] @save() deleteIfEmpty: ({boardID, threadID}) -> if threadID unless Object.keys(@data.boards[boardID][threadID]).length delete @data.boards[boardID][threadID] @deleteIfEmpty {boardID} else unless Object.keys(@data.boards[boardID]).length delete @data.boards[boardID] set: ({boardID, threadID, postID, val}) -> if postID isnt undefined ((@data.boards[boardID] or= {})[threadID] or= {})[postID] = val else if threadID isnt undefined (@data.boards[boardID] or= {})[threadID] = val else @data.boards[boardID] = val @save() get: ({boardID, threadID, postID, defaultValue}) -> if board = @data.boards[boardID] unless threadID if postID for ID, thread in board if postID of thread val = thread[postID] break else val = board else if thread = board[threadID] val = if postID thread[postID] else thread val or defaultValue clean: -> now = Date.now() return if (@data.lastChecked or 0) > now - 2 * $.HOUR for boardID of @data.boards @deleteIfEmpty {boardID} @ajaxClean boardID if boardID of @data.boards @data.lastChecked = now @save() ajaxClean: (boardID) -> $.cache "//a.4cdn.org/#{boardID}/threads.json", (e) => if e.target.status isnt 200 @delete {boardID} if e.target.status is 404 return board = @data.boards[boardID] threads = {} for page in e.target.response for thread in page.threads when thread.no of board threads[thread.no] = board[thread.no] count = Object.keys(threads).length return if count is Object.keys(board).length # Nothing changed. if count @set {boardID, val: threads} else @delete {boardID} onSync: (data) => @data = data or boards: {} @sync?()
[ { "context": "ontents: '<div style=\"text-align: center;\">Author: Marc Bachmann</div>'\n\n footer:\n height: 28mm,\n contents:", "end": 328, "score": 0.9998184442520142, "start": 315, "tag": "NAME", "value": "Marc Bachmann" } ]
lib/phantomjs-convert.coffee
romen/markdown-preview-enhanced
1
# TODO: finish this file # This is an experimental file # Not ready for use yet. ### --- phantomjs: path: ./test.pdf format: A3, A4, A5, Legal, Letter, Tabloid orientation: portrait or landscape margin: number or array header: height: "45mm", contents: '<div style="text-align: center;">Author: Marc Bachmann</div>' footer: height: 28mm, contents: first: 'Cover page', 2: 'Second page' // Any page number is working. 1-based index default: '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>', // fallback value last: 'Last Page' --- ### ### phantomsJSConvert = (text, config={}, projectDirectoryPath, fileDirectoryPath)-> if !config.path return atom.notifications.addError('phantomjs output path not provided') # dest if config.path[0] == '/' outputFilePath = path.resolve(projectDirectoryPath, '.' + config.path) else outputFilePath = path.resolve(fileDirectoryPath, config.path) useAbsoluteImagePath = false TODO: convert to markdown TODO: convert to html TODO: call phantomjs ###
193724
# TODO: finish this file # This is an experimental file # Not ready for use yet. ### --- phantomjs: path: ./test.pdf format: A3, A4, A5, Legal, Letter, Tabloid orientation: portrait or landscape margin: number or array header: height: "45mm", contents: '<div style="text-align: center;">Author: <NAME></div>' footer: height: 28mm, contents: first: 'Cover page', 2: 'Second page' // Any page number is working. 1-based index default: '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>', // fallback value last: 'Last Page' --- ### ### phantomsJSConvert = (text, config={}, projectDirectoryPath, fileDirectoryPath)-> if !config.path return atom.notifications.addError('phantomjs output path not provided') # dest if config.path[0] == '/' outputFilePath = path.resolve(projectDirectoryPath, '.' + config.path) else outputFilePath = path.resolve(fileDirectoryPath, config.path) useAbsoluteImagePath = false TODO: convert to markdown TODO: convert to html TODO: call phantomjs ###
true
# TODO: finish this file # This is an experimental file # Not ready for use yet. ### --- phantomjs: path: ./test.pdf format: A3, A4, A5, Legal, Letter, Tabloid orientation: portrait or landscape margin: number or array header: height: "45mm", contents: '<div style="text-align: center;">Author: PI:NAME:<NAME>END_PI</div>' footer: height: 28mm, contents: first: 'Cover page', 2: 'Second page' // Any page number is working. 1-based index default: '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>', // fallback value last: 'Last Page' --- ### ### phantomsJSConvert = (text, config={}, projectDirectoryPath, fileDirectoryPath)-> if !config.path return atom.notifications.addError('phantomjs output path not provided') # dest if config.path[0] == '/' outputFilePath = path.resolve(projectDirectoryPath, '.' + config.path) else outputFilePath = path.resolve(fileDirectoryPath, config.path) useAbsoluteImagePath = false TODO: convert to markdown TODO: convert to html TODO: call phantomjs ###
[ { "context": "ss keys\n for key in keys\n key.keyType ?= 'string'\n type = key.keyType.split(':')\n if typ", "end": 989, "score": 0.6727542281150818, "start": 983, "tag": "KEY", "value": "string" }, { "context": "Keys[relEnt.keyName] = validKeys[relEnt.keyName]._id\...
src/sfw_entity_ext.coffee
musocrat/sfw_model
0
'use strict' # Export module module.exports = ext: -> new SfwEntityExt() iExt: -> new SfwEntityIExt() # Setup adapter = require('./sfw_model_adapter') NeDB = adapter.NeDB SfwEntity = require('./sfw_entity') Event = require('events').EventEmitter # NeEntity Class extensions class SfwEntityExt constructor: -> _hasKeys: (entity, keys) => # helpers keyError = (key, msg) => return @emitError({action: "#{entity.model}.hasKeys()", params: {key: key}}, msg) mapDistantRelation = (key, type) => familyTree = type.slice(2).reverse() for model in familyTree if !lastRelation then lastRelation = @getEntityByParentOrChild(entity.parents, entity.children, model) else lastRelation = @getEntityByParentOrChild(lastRelation.parents, lastRelation.children, model) return keyError(key, 'failed mapping distant relation') unless lastRelation return lastRelation || null # process keys for key in keys key.keyType ?= 'string' type = key.keyType.split(':') if type[0] == 'entity' if type[1] then relationType = type[1] else return keyError(key, 'no relation set for entity') if type[2] then relatedModel = type[2] else return keyError(key, 'no model set for entity') relatedModel = type[2] switch relationType when 'parent' then relationship = entity.parents.filter(@getEntityByModel(relatedModel))[0] || null when 'child' then relationship = entity.children.filter(@getEntityByModel(relatedModel))[0] || null when 'distant' then relationship = mapDistantRelation(key, type) return keyError(key, 'error establishing relationship for key') unless relationship key.relatedEntity = relationship entity.primaryKey ?= key if key.primaryKey entity.keys.push(key) entity.keyNames.push(key.keyName) return true ## SfwEntity Class extensions _find: (entity, evt, val, cb, cbParams, aryMod) => evt.on('error', (e) -> console.error(e)) unless evt._events.error query = {} unless entity.primaryKey && entity.primaryKey.keyName return @emitError({action: "#{entity.model}.find()", params: {val: val}}, 'model has no primary key', evt, cb) query[entity.primaryKey.keyName] = val query.model = entity.model NeDB.find query, (err, results) => @emitResults(err, results, entity, "#{entity.model}.find()", {val: val}, aryMod, evt, cb, cbParams) return true _findBy: (entity, evt, hashOrKey, val, cb , cbParams, aryMod) => evt.on('error', (e) -> console.error(e)) unless evt._events.error if @isObject(hashOrKey) query = hashOrKey else if val query = {} query[hashOrKey] = val else return @emitError({action: "#{entity.model}.findBy()", params: {objectOrKey: hashOrKey, val: val}}, 'params should be (object) or (key, val)', evt, cb) query.model = entity.model NeDB.find query, (err, results) => @emitResults(err, results, entity, "#{entity.model}.findBy()", query, aryMod, evt, cb, cbParams) return true _findOrCreateBy: (entity, evt, hashOrKey, val = null, cb = null, cbParams = null) => evt.on('error', (e) -> console.error(e)) unless evt._events.error entity.findBy(hashOrKey, val, null, null, 'first') .on 'error', (findByErr) -> evt.emit('error', findByErr) if cb then cb(findByErr, null, cbParams) return .on 'data', (findByResults) -> if findByResults evt.emit('data', findByResults) if cb then cb(null, findByResults, cbParams) return entity.create(hashOrKey, val, null, null) .on 'error', (createErr) -> evt.emit('error', createErr) if cb then cb(createErr, null, cbParams) return .on 'data', (createResults) -> evt.emit('data', createResults) if cb then cb(null, createResults, cbParams) return true _create: (entity, evt, hashOrKey, val, cb, cbParams, instance = null) => evt.on('error', (e) -> console.error(e)) unless evt._events.error if @isObject(hashOrKey) query = hashOrKey else if val query = {} query[hashOrKey] = val else return @emitError({action: "#{entity.model}.create()", params: {objectOrKey: hashOrKey, val: val}}, 'params should be (object) or (key, val)', evt, cb) doCreate = (validKeys) => validKeys.model = entity.model related = [] relatedEntities = entity.keys.filter (key) -> key.relatedEntity for relEnt in relatedEntities rel = {} rel[relEnt.keyName] = validKeys[relEnt.keyName] related.push(rel) validKeys[relEnt.keyName] = validKeys[relEnt.keyName]._id NeDB.insert validKeys, (insertErr, insertResults) => @emitResults( insertErr, insertResults, entity, "#{entity.model}.create()", {object: query}, 'first', evt, cb, cbParams, instance, related) @validateData(entity, query, true) .on 'error', (vkError) => return @emitError( {action: "#{entity.model}.create()", params: {objectOrKey: hashOrKey, val: val}}, vkError, evt, cb) .on 'data', doCreate return true ## Helpers # Get time and date in a nice string now: => return "#{(d = new Date()).toLocaleDateString()} #{d.toLocaleTimeString()}" # Check if parameter is a non-Array Object isObject: (o) => Object.prototype.toString.call(o) == '[object Object]' # Check if parameter is an Array isArray: (o) => o instanceof Array # Check if value matches _id format (NeDB) isNeId: (val) => return (val.length == 16 && !val.match(/\s/)) # For related entity, check if key has value and if so is it in _id format relatedKeyNotEmpty: (val) => return (val && @isNeId(val)) # Callback function used with an Array.filter to get the matching entity based on the model name getEntityByModel: (model) => return (entity) -> return entity.model == model.toCamelCaseInitCap() # Initiate the above helper for parent or child entities getEntityByParentOrChild: (parents, children, model) => return parents.filter(@getEntityByModel(model))[0] || children.filter(@getEntityByModel(model))[0] || null # Callback function used with an Array.filter to validate that the passed key is defined in the model's schema validateKeyIsDefined: (keyName) => return (key) -> return key.keyName == keyName # Validate email likeness (very loose definition of email validation) validateEmail: (mKey, v) => return (mKey.keyType != 'email' || mKey.skipValidation || v.match(/.*@.*\..*/)) # Validate uri likeness (very loose definition of uri validation) validateUri: (mKey, v) => return (mKey.keyType != 'url' || mKey.skipValidation || v.match(/.*\..*/)) # Callback that validates uniqueness of key validateKeyUniqueness: (results, params) => if !results || results.isZeroLength() || (results.first()._id == params.id && results.length == 1) params.uniqAry.removeElementByValue(params.keyName) params.cb() else params.errCb("value must be unique for key => #{params.keyName}") return # Callback that validates relations are met and sets related entity as value validateKeyRelation: (results, params) => if results && results.length > 0 params.validKeys[params.keyName] = results.first() params.relAry.removeElementByValue(params.keyName) params.cb() else params.errCb("relation could not be established for key => #{params.keyName}") return # Validate key / value data for schema definition, required, unique, etc... validateData: (entity, passedObj, validateRequired = null) => evt = new Event() validKeys = {} includedKeys = [] processed = 0 modelKeys = entity.keys includedKeys.push(k) for k, v of passedObj required = modelKeys.filter((key) -> key.requireKey).map((key) -> key.keyName) mustBeUnique = modelKeys.filter((key) -> key.uniqueKey if key.keyName in includedKeys).map((key) -> key.keyName) related = modelKeys.filter((key) -> key.relatedEntity if key.keyName in includedKeys).map((key) -> key.keyName) handleKeyError = (msg) -> evt.emit 'error', msg; return emitWhenReady = -> if processed == includedKeys.length handleKeyError('required keys not included') if validateRequired && required.length > 0 evt.emit 'data', validKeys if mustBeUnique.isZeroLength() && related.isZeroLength() # validate key type constraints, uniqueness, and relation of each key value pair processKeys = (k, v) => modelKey = (modelKeys.filter(@validateKeyIsDefined(k))[0]) if modelKey validKeys[k] = v required.removeElementByValue(k) return handleKeyError('key type is email, but not in email format') unless @validateEmail(modelKey, v) return handleKeyError('key type is url, but not in url format') unless @validateUri(modelKey, v) if modelKey.uniqueKey vkuParams = { keyName: modelKey.keyName, id: passedObj.id, uniqAry: mustBeUnique, cb: emitWhenReady, errCb: handleKeyError } entity.findBy(modelKey.keyName, v, null, vkuParams) .on 'error', handleKeyError .on 'data', @validateKeyUniqueness if modelKey.relatedEntity if @isNeId(v) vkrParams = { validKeys: validKeys, keyName: modelKey.keyName, relAry: related, cb: emitWhenReady, errCb: handleKeyError } modelKey.relatedEntity.findBy('_id', v, null, vkrParams) .on 'error', handleKeyError .on 'data', @validateKeyRelation else if modelKey.relatedEntity.model == v.model related.removeElementByValue(modelKey.keyName) emitWhenReady() else return handleKeyError('relation could not be resolved') processed += 1 return processAllKeys = -> processKeys(k, v) for k, v of passedObj setTimeout(processAllKeys, 0) setTimeout(emitWhenReady, 0) return evt # Return related instances nestRelatedInstances: (instance, related = null) => evt = new Event() relatedEntities = instance.entity.keys.filter (key) -> key.relatedEntity relatedKeys = relatedEntities.map((key) -> key.keyName) emitWhenReady = -> if (relatedKeys.every (key) -> !instance[key] || instance.entity.isInstance(instance[key])) evt.emit('success'); return true getRelated = (relEnt, id, keyName) -> relEnt.findByFirst('_id', id) .on 'error', (err) -> evt.emit 'error', err .on 'data', (data) -> instance[keyName] = data; emitWhenReady() processRelations = => for rel in relatedEntities keyName = rel.keyName val = instance[keyName] return unless @relatedKeyNotEmpty(val) if related && related[keyName] then instance[keyName] = related[keyName]; emitWhenReady() else getRelated(rel.relatedEntity, val, keyName) setTimeout(processRelations, 0) return evt # Log the hell out of errors emitError: (env, msg, evt = null, cb = null) => error = {error: {time: @now(), action: env.action, params: env.params, msg: msg}} #console.error(error) if evt then evt.emit('error', error) if cb then cb(error, null) return error # Result handler that emits data event and initializes callback with results emitResults: (err, results, entity, caller, params, aryMod, evt = null, cb = null, cbParams = null, instance = null, related = null) => return @emitError({action: caller, params: params}, err, evt, cb) if err resultsOut = [] emitWhenReady = -> resultsOut = resultsOut[aryMod]() if aryMod && aryMod in ['first', 'last'] if evt then evt.emit('data', resultsOut, cbParams); evt.emit('success', true) if cb then cb(null, resultsOut, cbParams) if !results || ( (isAry = results instanceof Array) && results.isZeroLength() ) emitWhenReady() else buildInstance = (result) => bIEvt = new Event() instance ?= new SfwEntity.entityInstance(entity) instance[k] = v for k, v of result instance.id = instance._id related = entity.keys.filter((key) => key.relatedEntity if @relatedKeyNotEmpty(instance[key.keyName])) processInstance = => if related.isZeroLength() bIEvt.emit('data', instance) else @nestRelatedInstances(instance, related) .on 'error', (nestErr) => @emitError({action: caller, params: params}, nestErr, evt, cb); return .on 'success', -> bIEvt.emit 'data', instance setTimeout(processInstance, 0) return bIEvt pushResultEmitIfReady = (bInst) -> resultsOut.push(bInst); emitWhenReady() if !isAry || resultsOut.length == results.length results = [results] unless isAry buildInstance(result).on('data', pushResultEmitIfReady) for result in results return resultsOut sfwExt = new SfwEntityExt() # NeEntity instance extensions class SfwEntityIExt constructor: -> updateInstance: (instance, updateObj) => instance[k] = v for k, v of updateObj when k in instance.entity.keyNames return _update: (instance, evt, hashOrKey, val, cb , cbParams) => evt.on('error', (e) -> console.error(e)) unless evt._events.error if sfwExt.isObject(hashOrKey) query = hashOrKey else if val query = {} query[hashOrKey] = val else return sfwExt.emitError( {action: "#{instance.model}.instance.update()", params: {objectOrKey: hashOrKey, val: val}}, 'params should be (object) or (key, val)', evt, cb) query[k] ?= v for k, v of instance.attributes() doUpdate = (validKeys) => validKeys.model = instance.model related = instance.entity.keys.filter (key) -> key.relatedEntity for relEnt in related validKeys[relEnt.keyName] = validKeys[relEnt.keyName]._id NeDB.update {_id: instance.id}, validKeys, {}, (err, results) => @updateInstance(instance, validKeys) if err then evt.emit('error', err); cb(err, null, cbParams) if cb if results then evt.emit('data', instance); evt.emit('success'); cb(null, true, cbParams) if cb return true sfwExt.validateData(instance.entity, query, false) .on 'error', (vdErr) -> sfwExt.emitError( {action: "#{instance.model}.instance.update()", params: {objectOrKey: hashOrKey, val: val}}, vdErr, evt, cb) .on 'data', doUpdate return _destroy: (instance) => destroyEvt = new Event() doRemove = -> NeDB.remove {_id: instance.id}, {}, (err, results) -> if err then destroyEvt.emit('error', err); return if results then destroyEvt.emit('success', true); return setTimeout(doRemove, 0) return destroyEvt
136228
'use strict' # Export module module.exports = ext: -> new SfwEntityExt() iExt: -> new SfwEntityIExt() # Setup adapter = require('./sfw_model_adapter') NeDB = adapter.NeDB SfwEntity = require('./sfw_entity') Event = require('events').EventEmitter # NeEntity Class extensions class SfwEntityExt constructor: -> _hasKeys: (entity, keys) => # helpers keyError = (key, msg) => return @emitError({action: "#{entity.model}.hasKeys()", params: {key: key}}, msg) mapDistantRelation = (key, type) => familyTree = type.slice(2).reverse() for model in familyTree if !lastRelation then lastRelation = @getEntityByParentOrChild(entity.parents, entity.children, model) else lastRelation = @getEntityByParentOrChild(lastRelation.parents, lastRelation.children, model) return keyError(key, 'failed mapping distant relation') unless lastRelation return lastRelation || null # process keys for key in keys key.keyType ?= '<KEY>' type = key.keyType.split(':') if type[0] == 'entity' if type[1] then relationType = type[1] else return keyError(key, 'no relation set for entity') if type[2] then relatedModel = type[2] else return keyError(key, 'no model set for entity') relatedModel = type[2] switch relationType when 'parent' then relationship = entity.parents.filter(@getEntityByModel(relatedModel))[0] || null when 'child' then relationship = entity.children.filter(@getEntityByModel(relatedModel))[0] || null when 'distant' then relationship = mapDistantRelation(key, type) return keyError(key, 'error establishing relationship for key') unless relationship key.relatedEntity = relationship entity.primaryKey ?= key if key.primaryKey entity.keys.push(key) entity.keyNames.push(key.keyName) return true ## SfwEntity Class extensions _find: (entity, evt, val, cb, cbParams, aryMod) => evt.on('error', (e) -> console.error(e)) unless evt._events.error query = {} unless entity.primaryKey && entity.primaryKey.keyName return @emitError({action: "#{entity.model}.find()", params: {val: val}}, 'model has no primary key', evt, cb) query[entity.primaryKey.keyName] = val query.model = entity.model NeDB.find query, (err, results) => @emitResults(err, results, entity, "#{entity.model}.find()", {val: val}, aryMod, evt, cb, cbParams) return true _findBy: (entity, evt, hashOrKey, val, cb , cbParams, aryMod) => evt.on('error', (e) -> console.error(e)) unless evt._events.error if @isObject(hashOrKey) query = hashOrKey else if val query = {} query[hashOrKey] = val else return @emitError({action: "#{entity.model}.findBy()", params: {objectOrKey: hashOrKey, val: val}}, 'params should be (object) or (key, val)', evt, cb) query.model = entity.model NeDB.find query, (err, results) => @emitResults(err, results, entity, "#{entity.model}.findBy()", query, aryMod, evt, cb, cbParams) return true _findOrCreateBy: (entity, evt, hashOrKey, val = null, cb = null, cbParams = null) => evt.on('error', (e) -> console.error(e)) unless evt._events.error entity.findBy(hashOrKey, val, null, null, 'first') .on 'error', (findByErr) -> evt.emit('error', findByErr) if cb then cb(findByErr, null, cbParams) return .on 'data', (findByResults) -> if findByResults evt.emit('data', findByResults) if cb then cb(null, findByResults, cbParams) return entity.create(hashOrKey, val, null, null) .on 'error', (createErr) -> evt.emit('error', createErr) if cb then cb(createErr, null, cbParams) return .on 'data', (createResults) -> evt.emit('data', createResults) if cb then cb(null, createResults, cbParams) return true _create: (entity, evt, hashOrKey, val, cb, cbParams, instance = null) => evt.on('error', (e) -> console.error(e)) unless evt._events.error if @isObject(hashOrKey) query = hashOrKey else if val query = {} query[hashOrKey] = val else return @emitError({action: "#{entity.model}.create()", params: {objectOrKey: hashOrKey, val: val}}, 'params should be (object) or (key, val)', evt, cb) doCreate = (validKeys) => validKeys.model = entity.model related = [] relatedEntities = entity.keys.filter (key) -> key.relatedEntity for relEnt in relatedEntities rel = {} rel[relEnt.keyName] = validKeys[relEnt.keyName] related.push(rel) validKeys[relEnt.keyName] = validKeys[relEnt.keyName]._<KEY> NeDB.insert validKeys, (insertErr, insertResults) => @emitResults( insertErr, insertResults, entity, "#{entity.model}.create()", {object: query}, 'first', evt, cb, cbParams, instance, related) @validateData(entity, query, true) .on 'error', (vkError) => return @emitError( {action: "#{entity.model}.create()", params: {objectOrKey: hashOrKey, val: val}}, vkError, evt, cb) .on 'data', doCreate return true ## Helpers # Get time and date in a nice string now: => return "#{(d = new Date()).toLocaleDateString()} #{d.toLocaleTimeString()}" # Check if parameter is a non-Array Object isObject: (o) => Object.prototype.toString.call(o) == '[object Object]' # Check if parameter is an Array isArray: (o) => o instanceof Array # Check if value matches _id format (NeDB) isNeId: (val) => return (val.length == 16 && !val.match(/\s/)) # For related entity, check if key has value and if so is it in _id format relatedKeyNotEmpty: (val) => return (val && @isNeId(val)) # Callback function used with an Array.filter to get the matching entity based on the model name getEntityByModel: (model) => return (entity) -> return entity.model == model.toCamelCaseInitCap() # Initiate the above helper for parent or child entities getEntityByParentOrChild: (parents, children, model) => return parents.filter(@getEntityByModel(model))[0] || children.filter(@getEntityByModel(model))[0] || null # Callback function used with an Array.filter to validate that the passed key is defined in the model's schema validateKeyIsDefined: (keyName) => return (key) -> return key.keyName == keyName # Validate email likeness (very loose definition of email validation) validateEmail: (mKey, v) => return (mKey.keyType != 'email' || mKey.skipValidation || v.match(/.*@.*\..*/)) # Validate uri likeness (very loose definition of uri validation) validateUri: (mKey, v) => return (mKey.keyType != 'url' || mKey.skipValidation || v.match(/.*\..*/)) # Callback that validates uniqueness of key validateKeyUniqueness: (results, params) => if !results || results.isZeroLength() || (results.first()._id == params.id && results.length == 1) params.uniqAry.removeElementByValue(params.keyName) params.cb() else params.errCb("value must be unique for key => #{params.keyName}") return # Callback that validates relations are met and sets related entity as value validateKeyRelation: (results, params) => if results && results.length > 0 params.validKeys[params.keyName] = results.first() params.relAry.removeElementByValue(params.keyName) params.cb() else params.errCb("relation could not be established for key => #{params.keyName}") return # Validate key / value data for schema definition, required, unique, etc... validateData: (entity, passedObj, validateRequired = null) => evt = new Event() validKeys = {} includedKeys = [] processed = 0 modelKeys = entity.keys includedKeys.push(k) for k, v of passedObj required = modelKeys.filter((key) -> key.requireKey).map((key) -> key.keyName) mustBeUnique = modelKeys.filter((key) -> key.uniqueKey if key.keyName in includedKeys).map((key) -> key.keyName) related = modelKeys.filter((key) -> key.relatedEntity if key.keyName in includedKeys).map((key) -> key.keyName) handleKeyError = (msg) -> evt.emit 'error', msg; return emitWhenReady = -> if processed == includedKeys.length handleKeyError('required keys not included') if validateRequired && required.length > 0 evt.emit 'data', validKeys if mustBeUnique.isZeroLength() && related.isZeroLength() # validate key type constraints, uniqueness, and relation of each key value pair processKeys = (k, v) => modelKey = (modelKeys.filter(@validateKeyIsDefined(k))[0]) if modelKey validKeys[k] = v required.removeElementByValue(k) return handleKeyError('key type is email, but not in email format') unless @validateEmail(modelKey, v) return handleKeyError('key type is url, but not in url format') unless @validateUri(modelKey, v) if modelKey.uniqueKey vkuParams = { keyName: modelKey.keyName, id: passedObj.id, uniqAry: mustBeUnique, cb: emitWhenReady, errCb: handleKeyError } entity.findBy(modelKey.keyName, v, null, vkuParams) .on 'error', handleKeyError .on 'data', @validateKeyUniqueness if modelKey.relatedEntity if @isNeId(v) vkrParams = { validKeys: validKeys, keyName: modelKey.keyName, relAry: related, cb: emitWhenReady, errCb: handleKeyError } modelKey.relatedEntity.findBy('_id', v, null, vkrParams) .on 'error', handleKeyError .on 'data', @validateKeyRelation else if modelKey.relatedEntity.model == v.model related.removeElementByValue(modelKey.keyName) emitWhenReady() else return handleKeyError('relation could not be resolved') processed += 1 return processAllKeys = -> processKeys(k, v) for k, v of passedObj setTimeout(processAllKeys, 0) setTimeout(emitWhenReady, 0) return evt # Return related instances nestRelatedInstances: (instance, related = null) => evt = new Event() relatedEntities = instance.entity.keys.filter (key) -> key.relatedEntity relatedKeys = relatedEntities.map((key) -> key.keyName) emitWhenReady = -> if (relatedKeys.every (key) -> !instance[key] || instance.entity.isInstance(instance[key])) evt.emit('success'); return true getRelated = (relEnt, id, keyName) -> relEnt.findByFirst('_id', id) .on 'error', (err) -> evt.emit 'error', err .on 'data', (data) -> instance[keyName] = data; emitWhenReady() processRelations = => for rel in relatedEntities keyName = rel.keyName val = instance[keyName] return unless @relatedKeyNotEmpty(val) if related && related[keyName] then instance[keyName] = related[keyName]; emitWhenReady() else getRelated(rel.relatedEntity, val, keyName) setTimeout(processRelations, 0) return evt # Log the hell out of errors emitError: (env, msg, evt = null, cb = null) => error = {error: {time: @now(), action: env.action, params: env.params, msg: msg}} #console.error(error) if evt then evt.emit('error', error) if cb then cb(error, null) return error # Result handler that emits data event and initializes callback with results emitResults: (err, results, entity, caller, params, aryMod, evt = null, cb = null, cbParams = null, instance = null, related = null) => return @emitError({action: caller, params: params}, err, evt, cb) if err resultsOut = [] emitWhenReady = -> resultsOut = resultsOut[aryMod]() if aryMod && aryMod in ['first', 'last'] if evt then evt.emit('data', resultsOut, cbParams); evt.emit('success', true) if cb then cb(null, resultsOut, cbParams) if !results || ( (isAry = results instanceof Array) && results.isZeroLength() ) emitWhenReady() else buildInstance = (result) => bIEvt = new Event() instance ?= new SfwEntity.entityInstance(entity) instance[k] = v for k, v of result instance.id = instance._id related = entity.keys.filter((key) => key.relatedEntity if @relatedKeyNotEmpty(instance[key.keyName])) processInstance = => if related.isZeroLength() bIEvt.emit('data', instance) else @nestRelatedInstances(instance, related) .on 'error', (nestErr) => @emitError({action: caller, params: params}, nestErr, evt, cb); return .on 'success', -> bIEvt.emit 'data', instance setTimeout(processInstance, 0) return bIEvt pushResultEmitIfReady = (bInst) -> resultsOut.push(bInst); emitWhenReady() if !isAry || resultsOut.length == results.length results = [results] unless isAry buildInstance(result).on('data', pushResultEmitIfReady) for result in results return resultsOut sfwExt = new SfwEntityExt() # NeEntity instance extensions class SfwEntityIExt constructor: -> updateInstance: (instance, updateObj) => instance[k] = v for k, v of updateObj when k in instance.entity.keyNames return _update: (instance, evt, hashOrKey, val, cb , cbParams) => evt.on('error', (e) -> console.error(e)) unless evt._events.error if sfwExt.isObject(hashOrKey) query = hashOrKey else if val query = {} query[hashOrKey] = val else return sfwExt.emitError( {action: "#{instance.model}.instance.update()", params: {objectOrKey: hashOrKey, val: val}}, 'params should be (object) or (key, val)', evt, cb) query[k] ?= v for k, v of instance.attributes() doUpdate = (validKeys) => validKeys.model = instance.model related = instance.entity.keys.filter (key) -> key.relatedEntity for relEnt in related validKeys[relEnt.keyName] = validKeys[relEnt.keyName]._<KEY> NeDB.update {_id: instance.id}, validKeys, {}, (err, results) => @updateInstance(instance, validKeys) if err then evt.emit('error', err); cb(err, null, cbParams) if cb if results then evt.emit('data', instance); evt.emit('success'); cb(null, true, cbParams) if cb return true sfwExt.validateData(instance.entity, query, false) .on 'error', (vdErr) -> sfwExt.emitError( {action: "#{instance.model}.instance.update()", params: {objectOrKey: hashOrKey, val: val}}, vdErr, evt, cb) .on 'data', doUpdate return _destroy: (instance) => destroyEvt = new Event() doRemove = -> NeDB.remove {_id: instance.id}, {}, (err, results) -> if err then destroyEvt.emit('error', err); return if results then destroyEvt.emit('success', true); return setTimeout(doRemove, 0) return destroyEvt
true
'use strict' # Export module module.exports = ext: -> new SfwEntityExt() iExt: -> new SfwEntityIExt() # Setup adapter = require('./sfw_model_adapter') NeDB = adapter.NeDB SfwEntity = require('./sfw_entity') Event = require('events').EventEmitter # NeEntity Class extensions class SfwEntityExt constructor: -> _hasKeys: (entity, keys) => # helpers keyError = (key, msg) => return @emitError({action: "#{entity.model}.hasKeys()", params: {key: key}}, msg) mapDistantRelation = (key, type) => familyTree = type.slice(2).reverse() for model in familyTree if !lastRelation then lastRelation = @getEntityByParentOrChild(entity.parents, entity.children, model) else lastRelation = @getEntityByParentOrChild(lastRelation.parents, lastRelation.children, model) return keyError(key, 'failed mapping distant relation') unless lastRelation return lastRelation || null # process keys for key in keys key.keyType ?= 'PI:KEY:<KEY>END_PI' type = key.keyType.split(':') if type[0] == 'entity' if type[1] then relationType = type[1] else return keyError(key, 'no relation set for entity') if type[2] then relatedModel = type[2] else return keyError(key, 'no model set for entity') relatedModel = type[2] switch relationType when 'parent' then relationship = entity.parents.filter(@getEntityByModel(relatedModel))[0] || null when 'child' then relationship = entity.children.filter(@getEntityByModel(relatedModel))[0] || null when 'distant' then relationship = mapDistantRelation(key, type) return keyError(key, 'error establishing relationship for key') unless relationship key.relatedEntity = relationship entity.primaryKey ?= key if key.primaryKey entity.keys.push(key) entity.keyNames.push(key.keyName) return true ## SfwEntity Class extensions _find: (entity, evt, val, cb, cbParams, aryMod) => evt.on('error', (e) -> console.error(e)) unless evt._events.error query = {} unless entity.primaryKey && entity.primaryKey.keyName return @emitError({action: "#{entity.model}.find()", params: {val: val}}, 'model has no primary key', evt, cb) query[entity.primaryKey.keyName] = val query.model = entity.model NeDB.find query, (err, results) => @emitResults(err, results, entity, "#{entity.model}.find()", {val: val}, aryMod, evt, cb, cbParams) return true _findBy: (entity, evt, hashOrKey, val, cb , cbParams, aryMod) => evt.on('error', (e) -> console.error(e)) unless evt._events.error if @isObject(hashOrKey) query = hashOrKey else if val query = {} query[hashOrKey] = val else return @emitError({action: "#{entity.model}.findBy()", params: {objectOrKey: hashOrKey, val: val}}, 'params should be (object) or (key, val)', evt, cb) query.model = entity.model NeDB.find query, (err, results) => @emitResults(err, results, entity, "#{entity.model}.findBy()", query, aryMod, evt, cb, cbParams) return true _findOrCreateBy: (entity, evt, hashOrKey, val = null, cb = null, cbParams = null) => evt.on('error', (e) -> console.error(e)) unless evt._events.error entity.findBy(hashOrKey, val, null, null, 'first') .on 'error', (findByErr) -> evt.emit('error', findByErr) if cb then cb(findByErr, null, cbParams) return .on 'data', (findByResults) -> if findByResults evt.emit('data', findByResults) if cb then cb(null, findByResults, cbParams) return entity.create(hashOrKey, val, null, null) .on 'error', (createErr) -> evt.emit('error', createErr) if cb then cb(createErr, null, cbParams) return .on 'data', (createResults) -> evt.emit('data', createResults) if cb then cb(null, createResults, cbParams) return true _create: (entity, evt, hashOrKey, val, cb, cbParams, instance = null) => evt.on('error', (e) -> console.error(e)) unless evt._events.error if @isObject(hashOrKey) query = hashOrKey else if val query = {} query[hashOrKey] = val else return @emitError({action: "#{entity.model}.create()", params: {objectOrKey: hashOrKey, val: val}}, 'params should be (object) or (key, val)', evt, cb) doCreate = (validKeys) => validKeys.model = entity.model related = [] relatedEntities = entity.keys.filter (key) -> key.relatedEntity for relEnt in relatedEntities rel = {} rel[relEnt.keyName] = validKeys[relEnt.keyName] related.push(rel) validKeys[relEnt.keyName] = validKeys[relEnt.keyName]._PI:KEY:<KEY>END_PI NeDB.insert validKeys, (insertErr, insertResults) => @emitResults( insertErr, insertResults, entity, "#{entity.model}.create()", {object: query}, 'first', evt, cb, cbParams, instance, related) @validateData(entity, query, true) .on 'error', (vkError) => return @emitError( {action: "#{entity.model}.create()", params: {objectOrKey: hashOrKey, val: val}}, vkError, evt, cb) .on 'data', doCreate return true ## Helpers # Get time and date in a nice string now: => return "#{(d = new Date()).toLocaleDateString()} #{d.toLocaleTimeString()}" # Check if parameter is a non-Array Object isObject: (o) => Object.prototype.toString.call(o) == '[object Object]' # Check if parameter is an Array isArray: (o) => o instanceof Array # Check if value matches _id format (NeDB) isNeId: (val) => return (val.length == 16 && !val.match(/\s/)) # For related entity, check if key has value and if so is it in _id format relatedKeyNotEmpty: (val) => return (val && @isNeId(val)) # Callback function used with an Array.filter to get the matching entity based on the model name getEntityByModel: (model) => return (entity) -> return entity.model == model.toCamelCaseInitCap() # Initiate the above helper for parent or child entities getEntityByParentOrChild: (parents, children, model) => return parents.filter(@getEntityByModel(model))[0] || children.filter(@getEntityByModel(model))[0] || null # Callback function used with an Array.filter to validate that the passed key is defined in the model's schema validateKeyIsDefined: (keyName) => return (key) -> return key.keyName == keyName # Validate email likeness (very loose definition of email validation) validateEmail: (mKey, v) => return (mKey.keyType != 'email' || mKey.skipValidation || v.match(/.*@.*\..*/)) # Validate uri likeness (very loose definition of uri validation) validateUri: (mKey, v) => return (mKey.keyType != 'url' || mKey.skipValidation || v.match(/.*\..*/)) # Callback that validates uniqueness of key validateKeyUniqueness: (results, params) => if !results || results.isZeroLength() || (results.first()._id == params.id && results.length == 1) params.uniqAry.removeElementByValue(params.keyName) params.cb() else params.errCb("value must be unique for key => #{params.keyName}") return # Callback that validates relations are met and sets related entity as value validateKeyRelation: (results, params) => if results && results.length > 0 params.validKeys[params.keyName] = results.first() params.relAry.removeElementByValue(params.keyName) params.cb() else params.errCb("relation could not be established for key => #{params.keyName}") return # Validate key / value data for schema definition, required, unique, etc... validateData: (entity, passedObj, validateRequired = null) => evt = new Event() validKeys = {} includedKeys = [] processed = 0 modelKeys = entity.keys includedKeys.push(k) for k, v of passedObj required = modelKeys.filter((key) -> key.requireKey).map((key) -> key.keyName) mustBeUnique = modelKeys.filter((key) -> key.uniqueKey if key.keyName in includedKeys).map((key) -> key.keyName) related = modelKeys.filter((key) -> key.relatedEntity if key.keyName in includedKeys).map((key) -> key.keyName) handleKeyError = (msg) -> evt.emit 'error', msg; return emitWhenReady = -> if processed == includedKeys.length handleKeyError('required keys not included') if validateRequired && required.length > 0 evt.emit 'data', validKeys if mustBeUnique.isZeroLength() && related.isZeroLength() # validate key type constraints, uniqueness, and relation of each key value pair processKeys = (k, v) => modelKey = (modelKeys.filter(@validateKeyIsDefined(k))[0]) if modelKey validKeys[k] = v required.removeElementByValue(k) return handleKeyError('key type is email, but not in email format') unless @validateEmail(modelKey, v) return handleKeyError('key type is url, but not in url format') unless @validateUri(modelKey, v) if modelKey.uniqueKey vkuParams = { keyName: modelKey.keyName, id: passedObj.id, uniqAry: mustBeUnique, cb: emitWhenReady, errCb: handleKeyError } entity.findBy(modelKey.keyName, v, null, vkuParams) .on 'error', handleKeyError .on 'data', @validateKeyUniqueness if modelKey.relatedEntity if @isNeId(v) vkrParams = { validKeys: validKeys, keyName: modelKey.keyName, relAry: related, cb: emitWhenReady, errCb: handleKeyError } modelKey.relatedEntity.findBy('_id', v, null, vkrParams) .on 'error', handleKeyError .on 'data', @validateKeyRelation else if modelKey.relatedEntity.model == v.model related.removeElementByValue(modelKey.keyName) emitWhenReady() else return handleKeyError('relation could not be resolved') processed += 1 return processAllKeys = -> processKeys(k, v) for k, v of passedObj setTimeout(processAllKeys, 0) setTimeout(emitWhenReady, 0) return evt # Return related instances nestRelatedInstances: (instance, related = null) => evt = new Event() relatedEntities = instance.entity.keys.filter (key) -> key.relatedEntity relatedKeys = relatedEntities.map((key) -> key.keyName) emitWhenReady = -> if (relatedKeys.every (key) -> !instance[key] || instance.entity.isInstance(instance[key])) evt.emit('success'); return true getRelated = (relEnt, id, keyName) -> relEnt.findByFirst('_id', id) .on 'error', (err) -> evt.emit 'error', err .on 'data', (data) -> instance[keyName] = data; emitWhenReady() processRelations = => for rel in relatedEntities keyName = rel.keyName val = instance[keyName] return unless @relatedKeyNotEmpty(val) if related && related[keyName] then instance[keyName] = related[keyName]; emitWhenReady() else getRelated(rel.relatedEntity, val, keyName) setTimeout(processRelations, 0) return evt # Log the hell out of errors emitError: (env, msg, evt = null, cb = null) => error = {error: {time: @now(), action: env.action, params: env.params, msg: msg}} #console.error(error) if evt then evt.emit('error', error) if cb then cb(error, null) return error # Result handler that emits data event and initializes callback with results emitResults: (err, results, entity, caller, params, aryMod, evt = null, cb = null, cbParams = null, instance = null, related = null) => return @emitError({action: caller, params: params}, err, evt, cb) if err resultsOut = [] emitWhenReady = -> resultsOut = resultsOut[aryMod]() if aryMod && aryMod in ['first', 'last'] if evt then evt.emit('data', resultsOut, cbParams); evt.emit('success', true) if cb then cb(null, resultsOut, cbParams) if !results || ( (isAry = results instanceof Array) && results.isZeroLength() ) emitWhenReady() else buildInstance = (result) => bIEvt = new Event() instance ?= new SfwEntity.entityInstance(entity) instance[k] = v for k, v of result instance.id = instance._id related = entity.keys.filter((key) => key.relatedEntity if @relatedKeyNotEmpty(instance[key.keyName])) processInstance = => if related.isZeroLength() bIEvt.emit('data', instance) else @nestRelatedInstances(instance, related) .on 'error', (nestErr) => @emitError({action: caller, params: params}, nestErr, evt, cb); return .on 'success', -> bIEvt.emit 'data', instance setTimeout(processInstance, 0) return bIEvt pushResultEmitIfReady = (bInst) -> resultsOut.push(bInst); emitWhenReady() if !isAry || resultsOut.length == results.length results = [results] unless isAry buildInstance(result).on('data', pushResultEmitIfReady) for result in results return resultsOut sfwExt = new SfwEntityExt() # NeEntity instance extensions class SfwEntityIExt constructor: -> updateInstance: (instance, updateObj) => instance[k] = v for k, v of updateObj when k in instance.entity.keyNames return _update: (instance, evt, hashOrKey, val, cb , cbParams) => evt.on('error', (e) -> console.error(e)) unless evt._events.error if sfwExt.isObject(hashOrKey) query = hashOrKey else if val query = {} query[hashOrKey] = val else return sfwExt.emitError( {action: "#{instance.model}.instance.update()", params: {objectOrKey: hashOrKey, val: val}}, 'params should be (object) or (key, val)', evt, cb) query[k] ?= v for k, v of instance.attributes() doUpdate = (validKeys) => validKeys.model = instance.model related = instance.entity.keys.filter (key) -> key.relatedEntity for relEnt in related validKeys[relEnt.keyName] = validKeys[relEnt.keyName]._PI:KEY:<KEY>END_PI NeDB.update {_id: instance.id}, validKeys, {}, (err, results) => @updateInstance(instance, validKeys) if err then evt.emit('error', err); cb(err, null, cbParams) if cb if results then evt.emit('data', instance); evt.emit('success'); cb(null, true, cbParams) if cb return true sfwExt.validateData(instance.entity, query, false) .on 'error', (vdErr) -> sfwExt.emitError( {action: "#{instance.model}.instance.update()", params: {objectOrKey: hashOrKey, val: val}}, vdErr, evt, cb) .on 'data', doUpdate return _destroy: (instance) => destroyEvt = new Event() doRemove = -> NeDB.remove {_id: instance.id}, {}, (err, results) -> if err then destroyEvt.emit('error', err); return if results then destroyEvt.emit('success', true); return setTimeout(doRemove, 0) return destroyEvt
[ { "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.9999209046363831, "start": 178, "tag": "EMAIL", "value": "info@chaibio.com" } ]
frontend/javascripts/app/directives/v2/amplification_well_switch.js.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.ChaiBioTech.ngApp.directive 'chartWellSwitch', [ 'AmplificationChartHelper', '$timeout', '$state', '$rootScope', '$stateParams', (AmplificationChartHelper, $timeout, $state, $rootScope, $stateParams) -> restrict: 'EA', require: 'ngModel', scope: colorBy: '=' isDual: '=' samples: '=' targets: '=' initSampleColor: '=' buttonLabelsNum: '=?' #numbe of labels in button labelUnit: '=?' chartType: '@' templateUrl: 'app/views/directives/v2/chart-well-switch.html', link: ($scope, elem, attrs, ngModel) -> COLORS = AmplificationChartHelper.SAMPLE_TARGET_COLORS WELL_COLORS = AmplificationChartHelper.COLORS ACTIVE_BORDER_WIDTH = 2 is_cmd_key_held = false wells = {} $scope.dragging = false $scope.shiftStartIndex = -1 $scope.initTargetSelect = false $scope.wellTypeIcons = positive_control: '/images/ring_plus.svg' negative_control: '/images/ring_neg.svg' standard: '/images/ring_s.svg' unknown: '/images/ring_u.svg' $scope.registerOutsideHover = false; unhighlight_event = '' if !$scope.registerOutsideHover $scope.registerOutsideHover = angular.element(window).on 'mousemove', (e)-> if !angular.element(e.target).parents('.well-switch').length and !angular.element(e.target).parents('.well-item-row').length if unhighlight_event $rootScope.$broadcast unhighlight_event, {} unhighlight_event = '' $scope.$apply() $scope.$on 'keypressed:command', -> is_cmd_key_held = true $scope.$on 'keyreleased:command', -> is_cmd_key_held = false isCtrlKeyHeld = (evt) -> return (evt.ctrlKey or evt.metaKey) and is_cmd_key_held for b in [0...16] by 1 if $scope.colorBy is 'well' well_color = WELL_COLORS[b] else if $scope.colorBy is 'target' well_color = if $scope.targets[i] then $scope.targets[i].color else 'transparent' else if $scope.colorBy is 'sample' well_color = if $scope.samples[i] then $scope.samples[i].color else $scope.initSampleColor if ($scope.isDual and !$scope.targets[b*2].id and !$scope.targets[b*2+1].id) or (!$scope.isDual and !$scope.targets[b].id) well_color = 'transparent' else well_color = '#FFFFFF' wells["well_#{b}"] = selected: true active: false color: well_color well_type: ['', ''] ngModel.$setViewValue wells $scope.wells = wells $scope.row_header_width = 20 $scope.columns = [] $scope.rows = [] for i in [0...8] $scope.columns.push index: i, selected: false for i in [0...2] $scope.rows.push index: i, selected: false $scope.getWidth = -> elem[0].parentElement.offsetWidth $scope.getCellWidth = -> ($scope.getWidth() - $scope.row_header_width) / $scope.columns.length $scope.$watchCollection -> cts = [] for i in [0..15] by 1 cts.push ngModel.$modelValue["well_#{i}"].ct return cts , (cts) -> for ct, i in cts by 1 $scope.wells["well_#{i}"].ct = ct if $scope.wells["well_#{i}"] $scope.$watchCollection -> actives = [] for i in [0..15] by 1 actives.push ngModel.$modelValue["well_#{i}"].active return actives , (actives) -> for a, i in actives by 1 $scope.wells["well_#{i}"].active = a if $scope.wells["well_#{i}"] $scope.$watchCollection -> well_types = [] for i in [0..15] by 1 well_types.push ngModel.$modelValue["well_#{i}"].well_type return well_types , (well_types) -> for a, i in well_types by 1 $scope.wells["well_#{i}"].well_type = a if $scope.wells["well_#{i}"] $scope.$watch 'colorBy', (color_by) -> for i in [0..15] by 1 if color_by is 'well' well_color = WELL_COLORS[i] else if color_by is 'target' well_color = if $scope.targets[i] then $scope.targets[i].color else 'transparent' $scope.wells["well_#{i}"].color = if $scope.targets[i] then $scope.targets[i].color else 'transparent' $scope.wells["well_#{i}"].color1 = if $scope.targets[i*2] then $scope.targets[i*2].color else 'transparent' $scope.wells["well_#{i}"].color2 = if $scope.targets[i*2+1] then $scope.targets[i*2+1].color else 'transparent' else if color_by is 'sample' well_color = if $scope.samples[i] then $scope.samples[i].color else $scope.initSampleColor if ($scope.isDual and !$scope.targets[i*2]?.id and !$scope.targets[i*2+1]?.id) or (!$scope.isDual and !$scope.targets[i]?.id) well_color = 'transparent' # else # well_color = '#75278E' else well_color = '#FFFFFF' selected = true if $scope.targets and (($scope.isDual and (!$scope.targets[i*2] or !$scope.targets[i*2].id) and (!$scope.targets[i*2+1] or !$scope.targets[i*2+1].id)) or (!$scope.isDual and (!$scope.targets[i] or !$scope.targets[i].id))) selected = false # $scope.wells["well_#{i}"].selected = selected $scope.wells["well_#{i}"].color = well_color ngModel.$setViewValue angular.copy($scope.wells) $scope.$watch 'targets', (target) -> if !$scope.initTargetSelect and $scope.targets and $scope.targets.length if $.jStorage.get('selectedExpId') != $stateParams.id for i in [0..15] by 1 selected = true if $scope.targets and (($scope.isDual and (!$scope.targets[i*2] or !$scope.targets[i*2].id) and (!$scope.targets[i*2+1] or !$scope.targets[i*2+1].id)) or (!$scope.isDual and (!$scope.targets[i] or !$scope.targets[i].id))) selected = false $scope.wells["well_#{i}"].selected = selected else selectedWells = $.jStorage.get('selectedWells') for i in [0..15] by 1 if selectedWells $scope.wells["well_#{i}"].selected = selectedWells["well_#{i}"] else selected = true if $scope.targets and (($scope.isDual and (!$scope.targets[i*2] or !$scope.targets[i*2].id) and (!$scope.targets[i*2+1] or !$scope.targets[i*2+1].id)) or (!$scope.isDual and (!$scope.targets[i] or !$scope.targets[i].id))) selected = false $scope.wells["well_#{i}"].selected = selected ngModel.$setViewValue angular.copy($scope.wells) targets = _.filter $scope.targets, (item) -> item and item.id $scope.initTargetSelect = true if targets and targets.length $scope.getStyleForWellBar = (row, col, config, i) -> 'background-color': config.color 'opacity': if config.selected then 1 else 0.25 $scope.getStyleForTarget1Bar = (row, col, config, i) -> 'background-color': config.color1 'opacity': if config.selected then 1 else 0.25 $scope.getStyleForTarget2Bar = (row, col, config, i) -> 'background-color': config.color2 'opacity': if config.selected then 1 else 0.25 $scope.selectAllWells = () -> isAllSelected = true for i in [0..15] by 1 if !$scope.wells["well_" + i].selected isAllSelected = false for i in [0..15] by 1 $scope.wells["well_" + i].selected = !isAllSelected ngModel.$setViewValue(angular.copy($scope.wells)) $rootScope.$broadcast 'event:switch-chart-well', {active: well?.active, index: 0} hoverTarget = null $scope.wellHover = (evt, type, index) -> selectedWell = $scope.wells['well_' + index] wellData = [] currentTarget = null if selectedWell.selected and !$scope.dragging and (!selectedWell.active or hoverTarget) hoverTarget = null if $scope.chartType == 'amplification' $rootScope.$broadcast 'event:amp-highlight-row', { well_datas: [{well: index + 1, channel: 0}], well_index: index } unhighlight_event = 'event:amp-unhighlight-row' else if $scope.chartType == 'melt-curve' $rootScope.$broadcast 'event:melt-highlight-row', { well_datas: [{well: index + 1, channel: 0}], well_index: index } unhighlight_event = 'event:melt-unhighlight-row' else if $scope.chartType == 'standard-curve' $rootScope.$broadcast 'event:std-highlight-row', { well_datas: [{well: index + 1, channel: 0}], well_index: index } unhighlight_event = 'event:std-unhighlight-row' else if !selectedWell.selected and !$scope.dragging if $scope.chartType == 'amplification' $rootScope.$broadcast 'event:amp-unhighlight-row', {well: index + 1, channel: 0} else if $scope.chartType == 'standard-curve' $rootScope.$broadcast 'event:std-unhighlight-row', {well: index + 1, channel: 0} else $rootScope.$broadcast 'event:melt-unhighlight-row', {well: index + 1, channel: 0} unhighlight_event = '' $scope.dragged(evt, type, index) $scope.dragStart = (evt, type, index) -> # type can be 'column', 'row', 'well' or 'corner' # index is index of the type $scope.dragging = true $scope.dragStartingPoint = type: type index: index if $scope.dragStartingPoint.type is 'column' if type is 'well' index = if index >= $scope.columns.length then index - $scope.columns.length else index max = Math.max.apply(Math, [index, $scope.dragStartingPoint.index]) min = if max is index then $scope.dragStartingPoint.index else index $scope.columns.forEach (col) -> col.selected = col.index >= min and col.index <= max $scope.rows.forEach (row) -> well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] if not (isCtrlKeyHeld(evt) and well.selected) well.selected = col.selected if $scope.dragStartingPoint.type is 'row' if type is 'well' index = if index >= 8 then 1 else 0 max = Math.max.apply(Math, [index, $scope.dragStartingPoint.index]) min = if max is index then $scope.dragStartingPoint.index else index $scope.rows.forEach (row) -> row.selected = row.index >= min and row.index <= max $scope.columns.forEach (col) -> well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] # ctrl or command key held if not (isCtrlKeyHeld(evt) and well.selected) well.selected = row.selected #$scope.dragged(evt, type, index) $scope.dragged = (evt, type, index) -> return if !$scope.dragging return if type is $scope.dragStartingPoint.type and index is $scope.dragStartingPoint.index if $scope.dragStartingPoint.type is 'column' if type is 'well' index = if index >= $scope.columns.length then index - $scope.columns.length else index max = Math.max.apply(Math, [index, $scope.dragStartingPoint.index]) min = if max is index then $scope.dragStartingPoint.index else index $scope.columns.forEach (col) -> col.selected = col.index >= min and col.index <= max $scope.rows.forEach (row) -> well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] if not (isCtrlKeyHeld(evt) and well.selected) well.selected = col.selected if $scope.dragStartingPoint.type is 'row' if type is 'well' index = if index >= 8 then 1 else 0 max = Math.max.apply(Math, [index, $scope.dragStartingPoint.index]) min = if max is index then $scope.dragStartingPoint.index else index $scope.rows.forEach (row) -> row.selected = row.index >= min and row.index <= max $scope.columns.forEach (col) -> well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] # ctrl or command key held if not (isCtrlKeyHeld(evt) and well.selected) well.selected = row.selected if $scope.dragStartingPoint.type is 'well' if type is 'well' row1 = Math.floor($scope.dragStartingPoint.index / $scope.columns.length) col1 = $scope.dragStartingPoint.index - row1 * $scope.columns.length row2 = Math.floor(index / $scope.columns.length) col2 = index - row2 * $scope.columns.length max_row = Math.max.apply(Math, [row1, row2]) min_row = if max_row is row1 then row2 else row1 max_col = Math.max.apply(Math, [col1, col2]) min_col = if max_col is col1 then col2 else col1 $scope.rows.forEach (row) -> $scope.columns.forEach (col) -> selected = (row.index >= min_row and row.index <= max_row) and (col.index >= min_col and col.index <= max_col) well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] if not (isCtrlKeyHeld(evt) and well.selected) well.selected = selected $scope.dragStop = (evt, type, index) -> return if !$scope.dragging $scope.dragging = false # remove selected from columns and row headers $scope.columns.forEach (col) -> col.selected = false $scope.rows.forEach (row) -> row.selected = false if type is 'well' and index is $scope.dragStartingPoint.index # deselect all other wells if ctrl/cmd key is not held if !isCtrlKeyHeld(evt) $scope.rows.forEach (r) -> $scope.columns.forEach (c) -> $scope.wells["well_#{r.index * $scope.columns.length + c.index}"].selected = false # toggle selected state well = $scope.wells["well_#{index}"] well.selected = if isCtrlKeyHeld(evt) then !well.selected else true if $scope.dragStartingPoint.type is 'well' and $scope.shiftStartIndex >= 0 if type is 'well' row1 = Math.floor($scope.shiftStartIndex / $scope.columns.length) col1 = $scope.shiftStartIndex - row1 * $scope.columns.length row2 = Math.floor(index / $scope.columns.length) col2 = index - row2 * $scope.columns.length max_row = Math.max.apply(Math, [row1, row2]) min_row = if max_row is row1 then row2 else row1 max_col = Math.max.apply(Math, [col1, col2]) min_col = if max_col is col1 then col2 else col1 $scope.rows.forEach (row) -> $scope.columns.forEach (col) -> selected = (row.index >= min_row && row.index <= max_row) && (col.index >= min_col && col.index <= max_col) well = $scope.wells["well_" + (row.index * $scope.columns.length + col.index)] if evt.shiftKey well.selected = selected if not evt.shiftKey then $scope.shiftStartIndex = index ngModel.$setViewValue(angular.copy($scope.wells)) $rootScope.$broadcast 'event:switch-chart-well', {active: well?.active, index: index} $scope.getWellStyle = (row, col, well, index) -> return {} if well.active well_left_index = if (col.index + 1) % $scope.columns.length is 1 then null else index - 1 well_right_index = if (col.index + 1) % $scope.columns.length is 0 then null else index + 1 well_top_index = if (row.index + 1) % $scope.rows.length is 1 then null else index - $scope.columns.length well_bottom_index = if (row.index + 1) % $scope.rows.length is 0 then null else index + $scope.columns.length well_left = $scope.wells["well_#{well_left_index}"] well_right = $scope.wells["well_#{well_right_index}"] well_top = $scope.wells["well_#{well_top_index}"] well_bottom = $scope.wells["well_#{well_bottom_index}"] style = {} border = '1px solid #000' if well.selected if !(well_left?.selected) style['border-left'] = border if !(well_right?.selected) style['border-right'] = border if !(well_top?.selected) style['border-top'] = border if !(well_bottom?.selected) style['border-bottom'] = border return style $scope.getWellContainerStyle = (row, col, well, i) -> style = {} style.height = "100%" style.background = 'inherit' if well.active && well.selected style.width = "#{Math.round(@getCellWidth() + ACTIVE_BORDER_WIDTH * 4)}px" else style.width = "#{Math.round(@getCellWidth()) - 2}px" return style $scope.displayCt = (ct) -> if ct and angular.isNumber(ct * 1) and !window.isNaN(ct * 1) parseFloat(ct).toFixed(2) else '' ]
98575
### 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.ChaiBioTech.ngApp.directive 'chartWellSwitch', [ 'AmplificationChartHelper', '$timeout', '$state', '$rootScope', '$stateParams', (AmplificationChartHelper, $timeout, $state, $rootScope, $stateParams) -> restrict: 'EA', require: 'ngModel', scope: colorBy: '=' isDual: '=' samples: '=' targets: '=' initSampleColor: '=' buttonLabelsNum: '=?' #numbe of labels in button labelUnit: '=?' chartType: '@' templateUrl: 'app/views/directives/v2/chart-well-switch.html', link: ($scope, elem, attrs, ngModel) -> COLORS = AmplificationChartHelper.SAMPLE_TARGET_COLORS WELL_COLORS = AmplificationChartHelper.COLORS ACTIVE_BORDER_WIDTH = 2 is_cmd_key_held = false wells = {} $scope.dragging = false $scope.shiftStartIndex = -1 $scope.initTargetSelect = false $scope.wellTypeIcons = positive_control: '/images/ring_plus.svg' negative_control: '/images/ring_neg.svg' standard: '/images/ring_s.svg' unknown: '/images/ring_u.svg' $scope.registerOutsideHover = false; unhighlight_event = '' if !$scope.registerOutsideHover $scope.registerOutsideHover = angular.element(window).on 'mousemove', (e)-> if !angular.element(e.target).parents('.well-switch').length and !angular.element(e.target).parents('.well-item-row').length if unhighlight_event $rootScope.$broadcast unhighlight_event, {} unhighlight_event = '' $scope.$apply() $scope.$on 'keypressed:command', -> is_cmd_key_held = true $scope.$on 'keyreleased:command', -> is_cmd_key_held = false isCtrlKeyHeld = (evt) -> return (evt.ctrlKey or evt.metaKey) and is_cmd_key_held for b in [0...16] by 1 if $scope.colorBy is 'well' well_color = WELL_COLORS[b] else if $scope.colorBy is 'target' well_color = if $scope.targets[i] then $scope.targets[i].color else 'transparent' else if $scope.colorBy is 'sample' well_color = if $scope.samples[i] then $scope.samples[i].color else $scope.initSampleColor if ($scope.isDual and !$scope.targets[b*2].id and !$scope.targets[b*2+1].id) or (!$scope.isDual and !$scope.targets[b].id) well_color = 'transparent' else well_color = '#FFFFFF' wells["well_#{b}"] = selected: true active: false color: well_color well_type: ['', ''] ngModel.$setViewValue wells $scope.wells = wells $scope.row_header_width = 20 $scope.columns = [] $scope.rows = [] for i in [0...8] $scope.columns.push index: i, selected: false for i in [0...2] $scope.rows.push index: i, selected: false $scope.getWidth = -> elem[0].parentElement.offsetWidth $scope.getCellWidth = -> ($scope.getWidth() - $scope.row_header_width) / $scope.columns.length $scope.$watchCollection -> cts = [] for i in [0..15] by 1 cts.push ngModel.$modelValue["well_#{i}"].ct return cts , (cts) -> for ct, i in cts by 1 $scope.wells["well_#{i}"].ct = ct if $scope.wells["well_#{i}"] $scope.$watchCollection -> actives = [] for i in [0..15] by 1 actives.push ngModel.$modelValue["well_#{i}"].active return actives , (actives) -> for a, i in actives by 1 $scope.wells["well_#{i}"].active = a if $scope.wells["well_#{i}"] $scope.$watchCollection -> well_types = [] for i in [0..15] by 1 well_types.push ngModel.$modelValue["well_#{i}"].well_type return well_types , (well_types) -> for a, i in well_types by 1 $scope.wells["well_#{i}"].well_type = a if $scope.wells["well_#{i}"] $scope.$watch 'colorBy', (color_by) -> for i in [0..15] by 1 if color_by is 'well' well_color = WELL_COLORS[i] else if color_by is 'target' well_color = if $scope.targets[i] then $scope.targets[i].color else 'transparent' $scope.wells["well_#{i}"].color = if $scope.targets[i] then $scope.targets[i].color else 'transparent' $scope.wells["well_#{i}"].color1 = if $scope.targets[i*2] then $scope.targets[i*2].color else 'transparent' $scope.wells["well_#{i}"].color2 = if $scope.targets[i*2+1] then $scope.targets[i*2+1].color else 'transparent' else if color_by is 'sample' well_color = if $scope.samples[i] then $scope.samples[i].color else $scope.initSampleColor if ($scope.isDual and !$scope.targets[i*2]?.id and !$scope.targets[i*2+1]?.id) or (!$scope.isDual and !$scope.targets[i]?.id) well_color = 'transparent' # else # well_color = '#75278E' else well_color = '#FFFFFF' selected = true if $scope.targets and (($scope.isDual and (!$scope.targets[i*2] or !$scope.targets[i*2].id) and (!$scope.targets[i*2+1] or !$scope.targets[i*2+1].id)) or (!$scope.isDual and (!$scope.targets[i] or !$scope.targets[i].id))) selected = false # $scope.wells["well_#{i}"].selected = selected $scope.wells["well_#{i}"].color = well_color ngModel.$setViewValue angular.copy($scope.wells) $scope.$watch 'targets', (target) -> if !$scope.initTargetSelect and $scope.targets and $scope.targets.length if $.jStorage.get('selectedExpId') != $stateParams.id for i in [0..15] by 1 selected = true if $scope.targets and (($scope.isDual and (!$scope.targets[i*2] or !$scope.targets[i*2].id) and (!$scope.targets[i*2+1] or !$scope.targets[i*2+1].id)) or (!$scope.isDual and (!$scope.targets[i] or !$scope.targets[i].id))) selected = false $scope.wells["well_#{i}"].selected = selected else selectedWells = $.jStorage.get('selectedWells') for i in [0..15] by 1 if selectedWells $scope.wells["well_#{i}"].selected = selectedWells["well_#{i}"] else selected = true if $scope.targets and (($scope.isDual and (!$scope.targets[i*2] or !$scope.targets[i*2].id) and (!$scope.targets[i*2+1] or !$scope.targets[i*2+1].id)) or (!$scope.isDual and (!$scope.targets[i] or !$scope.targets[i].id))) selected = false $scope.wells["well_#{i}"].selected = selected ngModel.$setViewValue angular.copy($scope.wells) targets = _.filter $scope.targets, (item) -> item and item.id $scope.initTargetSelect = true if targets and targets.length $scope.getStyleForWellBar = (row, col, config, i) -> 'background-color': config.color 'opacity': if config.selected then 1 else 0.25 $scope.getStyleForTarget1Bar = (row, col, config, i) -> 'background-color': config.color1 'opacity': if config.selected then 1 else 0.25 $scope.getStyleForTarget2Bar = (row, col, config, i) -> 'background-color': config.color2 'opacity': if config.selected then 1 else 0.25 $scope.selectAllWells = () -> isAllSelected = true for i in [0..15] by 1 if !$scope.wells["well_" + i].selected isAllSelected = false for i in [0..15] by 1 $scope.wells["well_" + i].selected = !isAllSelected ngModel.$setViewValue(angular.copy($scope.wells)) $rootScope.$broadcast 'event:switch-chart-well', {active: well?.active, index: 0} hoverTarget = null $scope.wellHover = (evt, type, index) -> selectedWell = $scope.wells['well_' + index] wellData = [] currentTarget = null if selectedWell.selected and !$scope.dragging and (!selectedWell.active or hoverTarget) hoverTarget = null if $scope.chartType == 'amplification' $rootScope.$broadcast 'event:amp-highlight-row', { well_datas: [{well: index + 1, channel: 0}], well_index: index } unhighlight_event = 'event:amp-unhighlight-row' else if $scope.chartType == 'melt-curve' $rootScope.$broadcast 'event:melt-highlight-row', { well_datas: [{well: index + 1, channel: 0}], well_index: index } unhighlight_event = 'event:melt-unhighlight-row' else if $scope.chartType == 'standard-curve' $rootScope.$broadcast 'event:std-highlight-row', { well_datas: [{well: index + 1, channel: 0}], well_index: index } unhighlight_event = 'event:std-unhighlight-row' else if !selectedWell.selected and !$scope.dragging if $scope.chartType == 'amplification' $rootScope.$broadcast 'event:amp-unhighlight-row', {well: index + 1, channel: 0} else if $scope.chartType == 'standard-curve' $rootScope.$broadcast 'event:std-unhighlight-row', {well: index + 1, channel: 0} else $rootScope.$broadcast 'event:melt-unhighlight-row', {well: index + 1, channel: 0} unhighlight_event = '' $scope.dragged(evt, type, index) $scope.dragStart = (evt, type, index) -> # type can be 'column', 'row', 'well' or 'corner' # index is index of the type $scope.dragging = true $scope.dragStartingPoint = type: type index: index if $scope.dragStartingPoint.type is 'column' if type is 'well' index = if index >= $scope.columns.length then index - $scope.columns.length else index max = Math.max.apply(Math, [index, $scope.dragStartingPoint.index]) min = if max is index then $scope.dragStartingPoint.index else index $scope.columns.forEach (col) -> col.selected = col.index >= min and col.index <= max $scope.rows.forEach (row) -> well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] if not (isCtrlKeyHeld(evt) and well.selected) well.selected = col.selected if $scope.dragStartingPoint.type is 'row' if type is 'well' index = if index >= 8 then 1 else 0 max = Math.max.apply(Math, [index, $scope.dragStartingPoint.index]) min = if max is index then $scope.dragStartingPoint.index else index $scope.rows.forEach (row) -> row.selected = row.index >= min and row.index <= max $scope.columns.forEach (col) -> well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] # ctrl or command key held if not (isCtrlKeyHeld(evt) and well.selected) well.selected = row.selected #$scope.dragged(evt, type, index) $scope.dragged = (evt, type, index) -> return if !$scope.dragging return if type is $scope.dragStartingPoint.type and index is $scope.dragStartingPoint.index if $scope.dragStartingPoint.type is 'column' if type is 'well' index = if index >= $scope.columns.length then index - $scope.columns.length else index max = Math.max.apply(Math, [index, $scope.dragStartingPoint.index]) min = if max is index then $scope.dragStartingPoint.index else index $scope.columns.forEach (col) -> col.selected = col.index >= min and col.index <= max $scope.rows.forEach (row) -> well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] if not (isCtrlKeyHeld(evt) and well.selected) well.selected = col.selected if $scope.dragStartingPoint.type is 'row' if type is 'well' index = if index >= 8 then 1 else 0 max = Math.max.apply(Math, [index, $scope.dragStartingPoint.index]) min = if max is index then $scope.dragStartingPoint.index else index $scope.rows.forEach (row) -> row.selected = row.index >= min and row.index <= max $scope.columns.forEach (col) -> well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] # ctrl or command key held if not (isCtrlKeyHeld(evt) and well.selected) well.selected = row.selected if $scope.dragStartingPoint.type is 'well' if type is 'well' row1 = Math.floor($scope.dragStartingPoint.index / $scope.columns.length) col1 = $scope.dragStartingPoint.index - row1 * $scope.columns.length row2 = Math.floor(index / $scope.columns.length) col2 = index - row2 * $scope.columns.length max_row = Math.max.apply(Math, [row1, row2]) min_row = if max_row is row1 then row2 else row1 max_col = Math.max.apply(Math, [col1, col2]) min_col = if max_col is col1 then col2 else col1 $scope.rows.forEach (row) -> $scope.columns.forEach (col) -> selected = (row.index >= min_row and row.index <= max_row) and (col.index >= min_col and col.index <= max_col) well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] if not (isCtrlKeyHeld(evt) and well.selected) well.selected = selected $scope.dragStop = (evt, type, index) -> return if !$scope.dragging $scope.dragging = false # remove selected from columns and row headers $scope.columns.forEach (col) -> col.selected = false $scope.rows.forEach (row) -> row.selected = false if type is 'well' and index is $scope.dragStartingPoint.index # deselect all other wells if ctrl/cmd key is not held if !isCtrlKeyHeld(evt) $scope.rows.forEach (r) -> $scope.columns.forEach (c) -> $scope.wells["well_#{r.index * $scope.columns.length + c.index}"].selected = false # toggle selected state well = $scope.wells["well_#{index}"] well.selected = if isCtrlKeyHeld(evt) then !well.selected else true if $scope.dragStartingPoint.type is 'well' and $scope.shiftStartIndex >= 0 if type is 'well' row1 = Math.floor($scope.shiftStartIndex / $scope.columns.length) col1 = $scope.shiftStartIndex - row1 * $scope.columns.length row2 = Math.floor(index / $scope.columns.length) col2 = index - row2 * $scope.columns.length max_row = Math.max.apply(Math, [row1, row2]) min_row = if max_row is row1 then row2 else row1 max_col = Math.max.apply(Math, [col1, col2]) min_col = if max_col is col1 then col2 else col1 $scope.rows.forEach (row) -> $scope.columns.forEach (col) -> selected = (row.index >= min_row && row.index <= max_row) && (col.index >= min_col && col.index <= max_col) well = $scope.wells["well_" + (row.index * $scope.columns.length + col.index)] if evt.shiftKey well.selected = selected if not evt.shiftKey then $scope.shiftStartIndex = index ngModel.$setViewValue(angular.copy($scope.wells)) $rootScope.$broadcast 'event:switch-chart-well', {active: well?.active, index: index} $scope.getWellStyle = (row, col, well, index) -> return {} if well.active well_left_index = if (col.index + 1) % $scope.columns.length is 1 then null else index - 1 well_right_index = if (col.index + 1) % $scope.columns.length is 0 then null else index + 1 well_top_index = if (row.index + 1) % $scope.rows.length is 1 then null else index - $scope.columns.length well_bottom_index = if (row.index + 1) % $scope.rows.length is 0 then null else index + $scope.columns.length well_left = $scope.wells["well_#{well_left_index}"] well_right = $scope.wells["well_#{well_right_index}"] well_top = $scope.wells["well_#{well_top_index}"] well_bottom = $scope.wells["well_#{well_bottom_index}"] style = {} border = '1px solid #000' if well.selected if !(well_left?.selected) style['border-left'] = border if !(well_right?.selected) style['border-right'] = border if !(well_top?.selected) style['border-top'] = border if !(well_bottom?.selected) style['border-bottom'] = border return style $scope.getWellContainerStyle = (row, col, well, i) -> style = {} style.height = "100%" style.background = 'inherit' if well.active && well.selected style.width = "#{Math.round(@getCellWidth() + ACTIVE_BORDER_WIDTH * 4)}px" else style.width = "#{Math.round(@getCellWidth()) - 2}px" return style $scope.displayCt = (ct) -> if ct and angular.isNumber(ct * 1) and !window.isNaN(ct * 1) parseFloat(ct).toFixed(2) else '' ]
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.ChaiBioTech.ngApp.directive 'chartWellSwitch', [ 'AmplificationChartHelper', '$timeout', '$state', '$rootScope', '$stateParams', (AmplificationChartHelper, $timeout, $state, $rootScope, $stateParams) -> restrict: 'EA', require: 'ngModel', scope: colorBy: '=' isDual: '=' samples: '=' targets: '=' initSampleColor: '=' buttonLabelsNum: '=?' #numbe of labels in button labelUnit: '=?' chartType: '@' templateUrl: 'app/views/directives/v2/chart-well-switch.html', link: ($scope, elem, attrs, ngModel) -> COLORS = AmplificationChartHelper.SAMPLE_TARGET_COLORS WELL_COLORS = AmplificationChartHelper.COLORS ACTIVE_BORDER_WIDTH = 2 is_cmd_key_held = false wells = {} $scope.dragging = false $scope.shiftStartIndex = -1 $scope.initTargetSelect = false $scope.wellTypeIcons = positive_control: '/images/ring_plus.svg' negative_control: '/images/ring_neg.svg' standard: '/images/ring_s.svg' unknown: '/images/ring_u.svg' $scope.registerOutsideHover = false; unhighlight_event = '' if !$scope.registerOutsideHover $scope.registerOutsideHover = angular.element(window).on 'mousemove', (e)-> if !angular.element(e.target).parents('.well-switch').length and !angular.element(e.target).parents('.well-item-row').length if unhighlight_event $rootScope.$broadcast unhighlight_event, {} unhighlight_event = '' $scope.$apply() $scope.$on 'keypressed:command', -> is_cmd_key_held = true $scope.$on 'keyreleased:command', -> is_cmd_key_held = false isCtrlKeyHeld = (evt) -> return (evt.ctrlKey or evt.metaKey) and is_cmd_key_held for b in [0...16] by 1 if $scope.colorBy is 'well' well_color = WELL_COLORS[b] else if $scope.colorBy is 'target' well_color = if $scope.targets[i] then $scope.targets[i].color else 'transparent' else if $scope.colorBy is 'sample' well_color = if $scope.samples[i] then $scope.samples[i].color else $scope.initSampleColor if ($scope.isDual and !$scope.targets[b*2].id and !$scope.targets[b*2+1].id) or (!$scope.isDual and !$scope.targets[b].id) well_color = 'transparent' else well_color = '#FFFFFF' wells["well_#{b}"] = selected: true active: false color: well_color well_type: ['', ''] ngModel.$setViewValue wells $scope.wells = wells $scope.row_header_width = 20 $scope.columns = [] $scope.rows = [] for i in [0...8] $scope.columns.push index: i, selected: false for i in [0...2] $scope.rows.push index: i, selected: false $scope.getWidth = -> elem[0].parentElement.offsetWidth $scope.getCellWidth = -> ($scope.getWidth() - $scope.row_header_width) / $scope.columns.length $scope.$watchCollection -> cts = [] for i in [0..15] by 1 cts.push ngModel.$modelValue["well_#{i}"].ct return cts , (cts) -> for ct, i in cts by 1 $scope.wells["well_#{i}"].ct = ct if $scope.wells["well_#{i}"] $scope.$watchCollection -> actives = [] for i in [0..15] by 1 actives.push ngModel.$modelValue["well_#{i}"].active return actives , (actives) -> for a, i in actives by 1 $scope.wells["well_#{i}"].active = a if $scope.wells["well_#{i}"] $scope.$watchCollection -> well_types = [] for i in [0..15] by 1 well_types.push ngModel.$modelValue["well_#{i}"].well_type return well_types , (well_types) -> for a, i in well_types by 1 $scope.wells["well_#{i}"].well_type = a if $scope.wells["well_#{i}"] $scope.$watch 'colorBy', (color_by) -> for i in [0..15] by 1 if color_by is 'well' well_color = WELL_COLORS[i] else if color_by is 'target' well_color = if $scope.targets[i] then $scope.targets[i].color else 'transparent' $scope.wells["well_#{i}"].color = if $scope.targets[i] then $scope.targets[i].color else 'transparent' $scope.wells["well_#{i}"].color1 = if $scope.targets[i*2] then $scope.targets[i*2].color else 'transparent' $scope.wells["well_#{i}"].color2 = if $scope.targets[i*2+1] then $scope.targets[i*2+1].color else 'transparent' else if color_by is 'sample' well_color = if $scope.samples[i] then $scope.samples[i].color else $scope.initSampleColor if ($scope.isDual and !$scope.targets[i*2]?.id and !$scope.targets[i*2+1]?.id) or (!$scope.isDual and !$scope.targets[i]?.id) well_color = 'transparent' # else # well_color = '#75278E' else well_color = '#FFFFFF' selected = true if $scope.targets and (($scope.isDual and (!$scope.targets[i*2] or !$scope.targets[i*2].id) and (!$scope.targets[i*2+1] or !$scope.targets[i*2+1].id)) or (!$scope.isDual and (!$scope.targets[i] or !$scope.targets[i].id))) selected = false # $scope.wells["well_#{i}"].selected = selected $scope.wells["well_#{i}"].color = well_color ngModel.$setViewValue angular.copy($scope.wells) $scope.$watch 'targets', (target) -> if !$scope.initTargetSelect and $scope.targets and $scope.targets.length if $.jStorage.get('selectedExpId') != $stateParams.id for i in [0..15] by 1 selected = true if $scope.targets and (($scope.isDual and (!$scope.targets[i*2] or !$scope.targets[i*2].id) and (!$scope.targets[i*2+1] or !$scope.targets[i*2+1].id)) or (!$scope.isDual and (!$scope.targets[i] or !$scope.targets[i].id))) selected = false $scope.wells["well_#{i}"].selected = selected else selectedWells = $.jStorage.get('selectedWells') for i in [0..15] by 1 if selectedWells $scope.wells["well_#{i}"].selected = selectedWells["well_#{i}"] else selected = true if $scope.targets and (($scope.isDual and (!$scope.targets[i*2] or !$scope.targets[i*2].id) and (!$scope.targets[i*2+1] or !$scope.targets[i*2+1].id)) or (!$scope.isDual and (!$scope.targets[i] or !$scope.targets[i].id))) selected = false $scope.wells["well_#{i}"].selected = selected ngModel.$setViewValue angular.copy($scope.wells) targets = _.filter $scope.targets, (item) -> item and item.id $scope.initTargetSelect = true if targets and targets.length $scope.getStyleForWellBar = (row, col, config, i) -> 'background-color': config.color 'opacity': if config.selected then 1 else 0.25 $scope.getStyleForTarget1Bar = (row, col, config, i) -> 'background-color': config.color1 'opacity': if config.selected then 1 else 0.25 $scope.getStyleForTarget2Bar = (row, col, config, i) -> 'background-color': config.color2 'opacity': if config.selected then 1 else 0.25 $scope.selectAllWells = () -> isAllSelected = true for i in [0..15] by 1 if !$scope.wells["well_" + i].selected isAllSelected = false for i in [0..15] by 1 $scope.wells["well_" + i].selected = !isAllSelected ngModel.$setViewValue(angular.copy($scope.wells)) $rootScope.$broadcast 'event:switch-chart-well', {active: well?.active, index: 0} hoverTarget = null $scope.wellHover = (evt, type, index) -> selectedWell = $scope.wells['well_' + index] wellData = [] currentTarget = null if selectedWell.selected and !$scope.dragging and (!selectedWell.active or hoverTarget) hoverTarget = null if $scope.chartType == 'amplification' $rootScope.$broadcast 'event:amp-highlight-row', { well_datas: [{well: index + 1, channel: 0}], well_index: index } unhighlight_event = 'event:amp-unhighlight-row' else if $scope.chartType == 'melt-curve' $rootScope.$broadcast 'event:melt-highlight-row', { well_datas: [{well: index + 1, channel: 0}], well_index: index } unhighlight_event = 'event:melt-unhighlight-row' else if $scope.chartType == 'standard-curve' $rootScope.$broadcast 'event:std-highlight-row', { well_datas: [{well: index + 1, channel: 0}], well_index: index } unhighlight_event = 'event:std-unhighlight-row' else if !selectedWell.selected and !$scope.dragging if $scope.chartType == 'amplification' $rootScope.$broadcast 'event:amp-unhighlight-row', {well: index + 1, channel: 0} else if $scope.chartType == 'standard-curve' $rootScope.$broadcast 'event:std-unhighlight-row', {well: index + 1, channel: 0} else $rootScope.$broadcast 'event:melt-unhighlight-row', {well: index + 1, channel: 0} unhighlight_event = '' $scope.dragged(evt, type, index) $scope.dragStart = (evt, type, index) -> # type can be 'column', 'row', 'well' or 'corner' # index is index of the type $scope.dragging = true $scope.dragStartingPoint = type: type index: index if $scope.dragStartingPoint.type is 'column' if type is 'well' index = if index >= $scope.columns.length then index - $scope.columns.length else index max = Math.max.apply(Math, [index, $scope.dragStartingPoint.index]) min = if max is index then $scope.dragStartingPoint.index else index $scope.columns.forEach (col) -> col.selected = col.index >= min and col.index <= max $scope.rows.forEach (row) -> well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] if not (isCtrlKeyHeld(evt) and well.selected) well.selected = col.selected if $scope.dragStartingPoint.type is 'row' if type is 'well' index = if index >= 8 then 1 else 0 max = Math.max.apply(Math, [index, $scope.dragStartingPoint.index]) min = if max is index then $scope.dragStartingPoint.index else index $scope.rows.forEach (row) -> row.selected = row.index >= min and row.index <= max $scope.columns.forEach (col) -> well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] # ctrl or command key held if not (isCtrlKeyHeld(evt) and well.selected) well.selected = row.selected #$scope.dragged(evt, type, index) $scope.dragged = (evt, type, index) -> return if !$scope.dragging return if type is $scope.dragStartingPoint.type and index is $scope.dragStartingPoint.index if $scope.dragStartingPoint.type is 'column' if type is 'well' index = if index >= $scope.columns.length then index - $scope.columns.length else index max = Math.max.apply(Math, [index, $scope.dragStartingPoint.index]) min = if max is index then $scope.dragStartingPoint.index else index $scope.columns.forEach (col) -> col.selected = col.index >= min and col.index <= max $scope.rows.forEach (row) -> well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] if not (isCtrlKeyHeld(evt) and well.selected) well.selected = col.selected if $scope.dragStartingPoint.type is 'row' if type is 'well' index = if index >= 8 then 1 else 0 max = Math.max.apply(Math, [index, $scope.dragStartingPoint.index]) min = if max is index then $scope.dragStartingPoint.index else index $scope.rows.forEach (row) -> row.selected = row.index >= min and row.index <= max $scope.columns.forEach (col) -> well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] # ctrl or command key held if not (isCtrlKeyHeld(evt) and well.selected) well.selected = row.selected if $scope.dragStartingPoint.type is 'well' if type is 'well' row1 = Math.floor($scope.dragStartingPoint.index / $scope.columns.length) col1 = $scope.dragStartingPoint.index - row1 * $scope.columns.length row2 = Math.floor(index / $scope.columns.length) col2 = index - row2 * $scope.columns.length max_row = Math.max.apply(Math, [row1, row2]) min_row = if max_row is row1 then row2 else row1 max_col = Math.max.apply(Math, [col1, col2]) min_col = if max_col is col1 then col2 else col1 $scope.rows.forEach (row) -> $scope.columns.forEach (col) -> selected = (row.index >= min_row and row.index <= max_row) and (col.index >= min_col and col.index <= max_col) well = $scope.wells["well_#{row.index * $scope.columns.length + col.index}"] if not (isCtrlKeyHeld(evt) and well.selected) well.selected = selected $scope.dragStop = (evt, type, index) -> return if !$scope.dragging $scope.dragging = false # remove selected from columns and row headers $scope.columns.forEach (col) -> col.selected = false $scope.rows.forEach (row) -> row.selected = false if type is 'well' and index is $scope.dragStartingPoint.index # deselect all other wells if ctrl/cmd key is not held if !isCtrlKeyHeld(evt) $scope.rows.forEach (r) -> $scope.columns.forEach (c) -> $scope.wells["well_#{r.index * $scope.columns.length + c.index}"].selected = false # toggle selected state well = $scope.wells["well_#{index}"] well.selected = if isCtrlKeyHeld(evt) then !well.selected else true if $scope.dragStartingPoint.type is 'well' and $scope.shiftStartIndex >= 0 if type is 'well' row1 = Math.floor($scope.shiftStartIndex / $scope.columns.length) col1 = $scope.shiftStartIndex - row1 * $scope.columns.length row2 = Math.floor(index / $scope.columns.length) col2 = index - row2 * $scope.columns.length max_row = Math.max.apply(Math, [row1, row2]) min_row = if max_row is row1 then row2 else row1 max_col = Math.max.apply(Math, [col1, col2]) min_col = if max_col is col1 then col2 else col1 $scope.rows.forEach (row) -> $scope.columns.forEach (col) -> selected = (row.index >= min_row && row.index <= max_row) && (col.index >= min_col && col.index <= max_col) well = $scope.wells["well_" + (row.index * $scope.columns.length + col.index)] if evt.shiftKey well.selected = selected if not evt.shiftKey then $scope.shiftStartIndex = index ngModel.$setViewValue(angular.copy($scope.wells)) $rootScope.$broadcast 'event:switch-chart-well', {active: well?.active, index: index} $scope.getWellStyle = (row, col, well, index) -> return {} if well.active well_left_index = if (col.index + 1) % $scope.columns.length is 1 then null else index - 1 well_right_index = if (col.index + 1) % $scope.columns.length is 0 then null else index + 1 well_top_index = if (row.index + 1) % $scope.rows.length is 1 then null else index - $scope.columns.length well_bottom_index = if (row.index + 1) % $scope.rows.length is 0 then null else index + $scope.columns.length well_left = $scope.wells["well_#{well_left_index}"] well_right = $scope.wells["well_#{well_right_index}"] well_top = $scope.wells["well_#{well_top_index}"] well_bottom = $scope.wells["well_#{well_bottom_index}"] style = {} border = '1px solid #000' if well.selected if !(well_left?.selected) style['border-left'] = border if !(well_right?.selected) style['border-right'] = border if !(well_top?.selected) style['border-top'] = border if !(well_bottom?.selected) style['border-bottom'] = border return style $scope.getWellContainerStyle = (row, col, well, i) -> style = {} style.height = "100%" style.background = 'inherit' if well.active && well.selected style.width = "#{Math.round(@getCellWidth() + ACTIVE_BORDER_WIDTH * 4)}px" else style.width = "#{Math.round(@getCellWidth()) - 2}px" return style $scope.displayCt = (ct) -> if ct and angular.isNumber(ct * 1) and !window.isNaN(ct * 1) parseFloat(ct).toFixed(2) else '' ]
[ { "context": ">\n obj =\n id: 10\n name: 'jean'\n addresses: [\n city: 'lyon'\n", "end": 13412, "score": 0.9995889067649841, "start": 13408, "tag": "NAME", "value": "jean" }, { "context": ">\n obj =\n id: 10\n name...
test/apiValidation.coffee
worldline/swagger-jack
20
require 'js-yaml' express = require 'express' assert = require('chai').assert request = require 'request' http = require 'http' fs = require 'fs' swagger = require '../' pathUtils = require 'path' _ = require 'underscore' server = null host = 'localhost' port = 8090 root = "http://#{host}:#{port}" validator = null # test function: send an Http request (a get) and expect a status and a json body. getApi = (name, params, headers, status, expectedBody, done, extra) -> request.get url: "#{root}/#{name}" qs: params headers: headers json: true , (err, res, body) -> return done err if err? assert.equal res.statusCode, status, "unexpected status when getting #{root}/#{name}, body:\n#{JSON.stringify body}" if _.isFunction extra extra res, body, done else assert.deepEqual body, expectedBody, "unexpected body when getting #{root}/#{name}" done() # test function: send an Http request (a post) and expect a status and a json body. postApi = (name, headers, body, status, expectedBody, done) -> request.post url: "#{root}/#{name}" headers: headers body: body encoding: 'utf8' , (err, res, body) -> return done err if err? try body = JSON.parse body catch err return done "failed to parse body:#{err}\n#{body}" assert.equal res.statusCode, status, "unexpected status when getting #{root}/#{name}, body:\n#{JSON.stringify body}" assert.deepEqual body, expectedBody, "unexpected body when getting #{root}/#{name}" done() # test function: send an Http request (a post) and expect a status and a json body. uploadFilePostApi = (name, file, partName, status, expectedBody, done) -> req = request.post url: "#{root}/#{name}" , (err, res, body) -> return done err if err? assert.equal res.statusCode, status, "unexpected status when getting #{root}/#{name}, body:\n#{JSON.stringify body}" assert.deepEqual JSON.parse(body), expectedBody, "unexpected body when getting #{root}/#{name}" done() req.form().append partName, fs.createReadStream file # test function: send an Http request (a post multipart/form-data) and expect a status and a json body. multipartApi = (name, formdata, parts, status, expectedBody, done) -> req = url: "#{root}/#{name}" multipart: [] encoding: 'utf8' if formdata req.headers = 'content-type': 'multipart/form-data' for part in parts obj = body: part.body obj['content-disposition'] = "form-data; name=\"#{part.name}\"" if part.name? req.multipart.push obj request.post req, (err, res, body) -> return done err if err? try body = JSON.parse(body); catch err return done "failed to parse body:#{err}\n#{body}" assert.equal res.statusCode, status, "unexpected status when getting #{root}/#{name}, body:\n#{JSON.stringify body }" assert.deepEqual body, expectedBody, "unexpected body when getting #{root}/#{name}" done() describe 'API validation tests', -> it 'should fail if no express application is provided', -> assert.throws -> swagger.validator {} , /No Express application provided/ it 'should fail if provided applicatino was not analyzed', -> assert.throws -> swagger.validator express() , /No Swagger descriptor found within express application/ it 'should circular references be detected at statup', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/circular.yml' controller: returnBody: (req, res) -> res.json body:req.body ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /Circular reference detected: CircularUser > AddressBook > CircularUser/ describe 'given a basePath configured server', -> # given a started server before (done) -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: "#{root}/basepath" , [ api: require './fixtures/listApi.yml' controller: returnParams: (req, res) -> res.json req.input ]) .use(validator = swagger.validator app) .use(swagger.errorHandler()) server = http.createServer app server.listen port, host, _.defer(done) after (done) -> server.close() done() it 'should api be validated', (done) -> # when requesting the API getApi 'basepath/api/queryparams', null, {}, 400, {message: 'query parameter param1 is required'}, done it 'should api be invpked', (done) -> # when requesting the API getApi 'basepath/api/queryparams?param1=2', null, {}, 200, {param1: 2}, done describe 'given an allowableValues parameter', -> it 'should a properly configured allowableValues range be validated', -> assert.doesNotThrow -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/rangeApi.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) it 'should an allowableValues range without min value failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badRangeApi.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /missing allowableValues.min and\/or allowableValues.max parameters for allowableValues.range of/ it 'should an allowableValues range without max value failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badRangeApi2.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /missing allowableValues.min and\/or allowableValues.max parameters for allowableValues.range of/ it 'should an allowableValues range with min greater than max failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badRangeApi3.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /min value should not be greater tha max value in/ it 'should a properly configured allowableValues list be validated', -> assert.doesNotThrow -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/listApi.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) it 'should an allowableValues list without values failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badListApi.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /allowableValues.values is missing or is not an array for allowableValues.list of/ it 'should an allowableValues range with values which is not an array failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badListApi2.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /allowableValues.values is missing or is not an array for allowableValues.list of/ describe 'given a properly configured and started server', -> # given a started server before (done) -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/validatedApi.yml' controller: passed: (req, res) -> res.json status: 'passed' returnParams: (req, res) -> res.json req.input returnBody: (req, res) -> res.json body:req.body ]) .use(validator = swagger.validator app) .use(swagger.errorHandler()) app.get "/unvalidated", (req, res) -> res.json status:'passed' server = http.createServer app server.listen port, host, _.defer(done) after (done) -> server.close() done() it 'should unvalidated API be available', (done) -> getApi 'unvalidated', null, {}, 200, {status:'passed'}, done it 'should validated API without parameters be available', (done) -> getApi 'api/noparams/18', null, {}, 200, {status:'passed'}, done it 'should validation function be called manually', (done) -> casted = {} url = '/api/queryparams' # method, Express path, url, query, headers, body, casted, callback validator.validate 'GET', url, url, {param1:"-2", param2:"5.5"}, {}, {}, casted, (err) -> return done err if err? assert.equal casted.param1, -2 assert.equal casted.param2, 5.5 done() describe 'given an api accepting query parameters', -> it 'should required be checked', (done) -> getApi 'api/queryparams', null, {}, 400, {message: 'query parameter param1 is required'}, done it 'should optionnal be allowed', (done) -> query = param1:10 getApi 'api/queryparams', query, {}, 200, query, done it 'should integer and float be parsed', (done) -> query = param1:-2, param2:5.5 getApi 'api/queryparams', query, {}, 200, query, done it 'should float not accepted as integer', (done) -> getApi 'api/queryparams', {param1:3.2}, {}, 400, {message: 'query parameter param1 is a number when it should be an integer'}, done it 'should malformed number not accepted as integer', (done) -> getApi 'api/queryparams', {param1:'3x'}, {}, 400, {message: 'query parameter param1 is a string when it should be an integer'}, done it 'should empty string not accepted for a number', (done) -> getApi 'api/queryparams?param1=', null, {}, 400, {message: 'query parameter param1 is a string when it should be an integer'}, done it 'should string not accepted for a number', (done) -> getApi 'api/queryparams', {param1:'yeah'}, {}, 400, {message: 'query parameter param1 is a string when it should be an integer'}, done it 'should multiple parameter accept single value', (done) -> getApi 'api/queryparams', {param1:0, param3:true}, {}, 200, {param1: 0, param3: [true]}, done it 'should multiple parameter accept multiple value', (done) -> getApi 'api/queryparams?param1=0&param3=true&param3=false', {}, {}, 200, {param1: 0, param3: [true, false]}, done it 'should multiple parameter accept coma-separated value', (done) -> getApi 'api/queryparams', {param1:0, param3:'true,false'}, {}, 200, {param1: 0, param3: [true, false]}, done it 'should multiple be checked', (done) -> getApi 'api/queryparams', {param1:0, param3: [true, 'toto']}, {}, 400, {message: 'query parameter param3 property \'[1]\' is a string when it should be a boolean'}, done it 'should complex json be parsed', (done) -> obj = id: 10 name: 'jean' addresses: [ city: 'lyon' street: 'bd vivier merles' zipcode: 69006 ] getApi 'api/complexqueryparam', {user:JSON.stringify obj}, {}, 200, {user:obj}, done describe 'given an api accepting header parameters', -> it 'should required be checked', (done) -> getApi 'api/headerparams', null, {}, 400, {message: 'header param1 is required'}, done it 'should optionnal be allowed', (done) -> headers = param1: 10 getApi 'api/headerparams', null, headers, 200, headers, done it 'should long and boolean be parsed', (done) -> headers = param1: -2 param2: false getApi 'api/headerparams', null, headers, 200, headers, done it 'should double not accepted as integer', (done) -> getApi 'api/headerparams', null, {param1:3.2}, 400, {message: 'header param1 is a number when it should be an integer'}, done it 'should empty string not accepted for a boolean', (done) -> getApi 'api/headerparams', null, {param1: 0, param2:''}, 400, {message: 'header param2 is a string when it should be a boolean'}, done it 'should string not accepted for a boolean', (done) -> getApi 'api/headerparams', null, {param1: 0, param2:'yeah'}, 400, {message: 'header param2 is a string when it should be a boolean'}, done it 'should multiple parameter accept single value', (done) -> getApi 'api/headerparams', null, {param1:0, param3:1.5}, 200, {param1: 0, param3: [1.5]}, done it 'should multiple parameter accept multiple value', (done) -> getApi 'api/headerparams', null, {param1:-2, param3: '2.1, -4.6'}, 200, {param1:-2, param3: [2.1, -4.6]}, done it 'should multiple be checked', (done) -> getApi 'api/headerparams', null, {param1:0, param3: [true, 1.5]}, 400, {message: 'header param3 property \'[0]\' is a string when it should be a number'}, done it 'should complex json be parsed', (done) -> obj = id: 10 name: 'jean' addresses: [ city: 'lyon' street: 'bd vivier merles' zipcode: 69006 ] getApi 'api/complexheaderparam', null, {user:JSON.stringify obj}, 200, {user:obj}, done describe 'given an api accepting path parameters', -> it 'should required be checked', (done) -> getApi 'api/pathparams', null, {}, 404, 'Cannot GET /api/pathparams', done it 'should int and boolean be parsed', (done) -> getApi 'api/pathparams/10/true', null, {}, 200, {param1:10, param2:true}, done it 'should take wildcard path param', (done) -> getApi 'api/pathparams/10/foo/bar/suffix', null, {}, 200, {param1:'10', 'param2*':'foo/bar'}, done describe 'given an api accepting body parameters', -> it 'should plain text body be parsed', (done) -> postApi 'api/singleintbody', {'Content-Type': 'text/plain'}, '1000', 200, {body:1000}, done it 'should plain text body be checked', (done) -> postApi 'api/singleintbody', {'Content-Type': 'text/plain'}, 'toto', 400, {message: 'body is a string when it should be an integer'}, done it 'should plain text body be required', (done) -> postApi 'api/singleintbody', {'Content-Type': 'text/plain'}, undefined, 400, {message: 'body is required'}, done it 'should primitive json body be parsed', (done) -> postApi 'api/singleintbody', {'Content-Type': 'application/json'}, '[-500]', 200, {body:-500}, done it 'should primitive json body be checked', (done) -> postApi 'api/singleintbody', {'Content-Type': 'application/json'}, '[true]', 400, {message: 'body is an array when it should be an integer'}, done it 'should primitive json body be required', (done) -> postApi 'api/singleintbody', {'Content-Type': 'application/json'}, undefined, 400, {message: 'Bad Request'}, done it 'should body parameter be optionnal', (done) -> postApi 'api/optionnalbody', null, undefined, 200, {}, done it 'should form-encoded body be required', (done) -> postApi 'api/multiplebody', {'Content-Type': 'application/x-www-form-urlencoded'}, undefined, 400, {message: 'body parameter param1 is required'}, done it 'should multi-part body be required', (done) -> multipartApi 'api/multiplebody', true, [{name: 'param', body: 'toto'}], 400, {message: 'body parameter param1 is required'}, done it 'should form-encoded body be parsed and casted down', (done) -> postApi 'api/multiplebody', {'Content-Type': 'application/x-www-form-urlencoded'}, 'param1=10&param2=true,false', 200, {body:{param1: 10, param2: [true, false]}}, done it 'should multi-part/related body not be parsed', (done) -> multipartApi 'api/multiplebody', false, [ name: 'param1' body: '-5' , name: 'param2' body: 'false,true' ], 400, {message: 'body parameter param1 is required'}, done it 'should multi-part/form-data body be parsed and casted down', (done) -> multipartApi 'api/multiplebody', true, [ name: 'param1' body: '-5' , name: 'param2' body: 'false,true' ], 200, {body:{param1: -5, param2: [false, true]}}, done it 'should multi-part body parameter be optionnal', (done) -> multipartApi 'api/multiplebody', true, [{name: 'param1', body: '0'}], 200, {body:{param1: 0}}, done it 'should complex json body be parsed', (done) -> obj = id: 10 name: 'jean' addresses: [ city: 'lyon' street: 'bd vivier merle' zipcode: 69006 ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body:obj}, done it 'should multiple anonymous optionnal body accept one value', (done) -> postApi 'api/multipleanonymousbody', undefined, '1', 200, {body: [1]}, done it 'should multiple anonymous optionnal body accept multiple values', (done) -> postApi 'api/multipleanonymousbody', undefined, '1,2,3', 200, {body: [1,2,3]}, done it 'should multiple anonymous optionnal body accept no values', (done) -> postApi 'api/multipleanonymousbody', undefined, undefined, 200, {}, done it 'should multiple anonymous optionnal body accept one json value', (done) -> postApi 'api/multipleanonymousbody', {'Content-Type': 'application/json'}, '[1]', 200, {body: [1]}, done it 'should multiple anonymous optionnal body accept multiple json values', (done) -> postApi 'api/multipleanonymousbody', {'Content-Type': 'application/json'}, '[1,2,3]', 200, {body: [1,2,3]}, done it 'should multiple complex optionnal body accept no values', (done) -> postApi 'api/multiplecomplexbody', undefined, undefined, 200, {}, done it 'should multiple complex optionnal body accept one json value', (done) -> postApi 'api/multiplecomplexbody', {'Content-Type': 'application/json'}, '{"id":1, "name":"jean"}', 200, {body: [{id:1, name:'jean'}]}, done it 'should multiple complex optionnal body accept multiple json values', (done) -> postApi 'api/multiplecomplexbody', {'Content-Type': 'application/json'}, '[{"id":1, "name":"jean"},{"id":2, "name":"paul"}]', 200, {body: [ {id:1, name:'jean'}, {id:2, name:'paul'} ]}, done describe 'given an api accepting model parameter', -> it 'should complex json body be checked', (done) -> obj = id: 11 firstName: 'jean' lastName: 'dupond' addresses: [] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'firstName' is not explicitly defined and therefore not allowed"}, done it 'should complex json body refs be checked', (done) -> obj = id: 12 name: 'Damien' addresses: [ ville: 'lyon', street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'addresses.[0].ville' is not explicitly defined and therefore not allowed"}, done it 'should range list value be checked', (done) -> obj = id: 12 name: 'Damien' addresses: [ city: 'strasbourd' zipcode: 67000 street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'addresses.[0].city' is not in enum"}, done it 'should range interval value be checked', (done) -> obj = id: 12 name: 'Damien' addresses: [ city: 'lyon' zipcode: 100000 street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'addresses.[0].zipcode' is 100000 when it should be at most 99999"}, done it 'should required attributes be checked', (done) -> obj = name: 'Damien' addresses: [ city: 'lyon' zipcode: 69003 street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'id' is required"}, done it 'should primitive values be parsed', (done) -> obj = id: true name: 'Damien' addresses: [ city: 'lyon' zipcode: 69003 street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'id' is a boolean when it should be an integer"}, done it 'should additionnal attribute not be allowed', (done) -> obj = id: 20 name: 'Damien' addresses: [ city: 'lyon' zipcode: 69003 street: 'bd vivier merle' other: 'coucou' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'addresses.[0].other' is not explicitly defined and therefore not allowed"}, done it 'should optionnal attribute be allowed', (done) -> obj = id: 30 postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body: obj}, done it 'should complex attribute not be checked', (done) -> obj = id: 20 name: 'Damien' stuff: name: 10 addresses: [ city: 'lyon' zipcode: 69003 street: 'bd vivier merle' other: 'coucou' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'stuff.name' is an integer when it should be a string"}, done it 'should classical json-schema specification be usabled', (done) -> obj = id: 20 other: 'Damien' phone: '000-1234' postApi 'api/jsonschemabody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'phone' does not match pattern"}, done it 'should any be accepted as type within models', (done) -> obj = id: 20 name: [] phone: '00000-1234' postApi 'api/jsonschemabody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body:obj}, done it 'should accept union type', (done) -> obj = id: 1 name: first: 'jean' last: 'dupond' postApi 'api/unionbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body:obj}, (err) -> return done err if err? obj.name = 'jean dupond' postApi 'api/unionbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body:obj}, done it 'should accept upload file', (done) -> file = pathUtils.join __dirname, 'fixtures', 'circular.yml' uploadFilePostApi 'api/upload', file, 'file', 200, {status:'passed'}, done it 'should reject when passing file not in multipart', (done) -> file = pathUtils.join __dirname, 'fixtures/circular.yml' postApi 'api/upload', {'Content-Type': 'application/json'}, JSON.stringify(file:file.toString()), 400, {message: "body parameter file is required"}, done it 'should fail on missing body file', (done) -> file = pathUtils.join __dirname, 'fixtures/circular.yml' uploadFilePostApi 'api/upload', file, 'other', 400, {message: "body parameter file is required"}, done # TODO post, put, delete, model list-set-arrays
194758
require 'js-yaml' express = require 'express' assert = require('chai').assert request = require 'request' http = require 'http' fs = require 'fs' swagger = require '../' pathUtils = require 'path' _ = require 'underscore' server = null host = 'localhost' port = 8090 root = "http://#{host}:#{port}" validator = null # test function: send an Http request (a get) and expect a status and a json body. getApi = (name, params, headers, status, expectedBody, done, extra) -> request.get url: "#{root}/#{name}" qs: params headers: headers json: true , (err, res, body) -> return done err if err? assert.equal res.statusCode, status, "unexpected status when getting #{root}/#{name}, body:\n#{JSON.stringify body}" if _.isFunction extra extra res, body, done else assert.deepEqual body, expectedBody, "unexpected body when getting #{root}/#{name}" done() # test function: send an Http request (a post) and expect a status and a json body. postApi = (name, headers, body, status, expectedBody, done) -> request.post url: "#{root}/#{name}" headers: headers body: body encoding: 'utf8' , (err, res, body) -> return done err if err? try body = JSON.parse body catch err return done "failed to parse body:#{err}\n#{body}" assert.equal res.statusCode, status, "unexpected status when getting #{root}/#{name}, body:\n#{JSON.stringify body}" assert.deepEqual body, expectedBody, "unexpected body when getting #{root}/#{name}" done() # test function: send an Http request (a post) and expect a status and a json body. uploadFilePostApi = (name, file, partName, status, expectedBody, done) -> req = request.post url: "#{root}/#{name}" , (err, res, body) -> return done err if err? assert.equal res.statusCode, status, "unexpected status when getting #{root}/#{name}, body:\n#{JSON.stringify body}" assert.deepEqual JSON.parse(body), expectedBody, "unexpected body when getting #{root}/#{name}" done() req.form().append partName, fs.createReadStream file # test function: send an Http request (a post multipart/form-data) and expect a status and a json body. multipartApi = (name, formdata, parts, status, expectedBody, done) -> req = url: "#{root}/#{name}" multipart: [] encoding: 'utf8' if formdata req.headers = 'content-type': 'multipart/form-data' for part in parts obj = body: part.body obj['content-disposition'] = "form-data; name=\"#{part.name}\"" if part.name? req.multipart.push obj request.post req, (err, res, body) -> return done err if err? try body = JSON.parse(body); catch err return done "failed to parse body:#{err}\n#{body}" assert.equal res.statusCode, status, "unexpected status when getting #{root}/#{name}, body:\n#{JSON.stringify body }" assert.deepEqual body, expectedBody, "unexpected body when getting #{root}/#{name}" done() describe 'API validation tests', -> it 'should fail if no express application is provided', -> assert.throws -> swagger.validator {} , /No Express application provided/ it 'should fail if provided applicatino was not analyzed', -> assert.throws -> swagger.validator express() , /No Swagger descriptor found within express application/ it 'should circular references be detected at statup', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/circular.yml' controller: returnBody: (req, res) -> res.json body:req.body ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /Circular reference detected: CircularUser > AddressBook > CircularUser/ describe 'given a basePath configured server', -> # given a started server before (done) -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: "#{root}/basepath" , [ api: require './fixtures/listApi.yml' controller: returnParams: (req, res) -> res.json req.input ]) .use(validator = swagger.validator app) .use(swagger.errorHandler()) server = http.createServer app server.listen port, host, _.defer(done) after (done) -> server.close() done() it 'should api be validated', (done) -> # when requesting the API getApi 'basepath/api/queryparams', null, {}, 400, {message: 'query parameter param1 is required'}, done it 'should api be invpked', (done) -> # when requesting the API getApi 'basepath/api/queryparams?param1=2', null, {}, 200, {param1: 2}, done describe 'given an allowableValues parameter', -> it 'should a properly configured allowableValues range be validated', -> assert.doesNotThrow -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/rangeApi.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) it 'should an allowableValues range without min value failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badRangeApi.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /missing allowableValues.min and\/or allowableValues.max parameters for allowableValues.range of/ it 'should an allowableValues range without max value failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badRangeApi2.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /missing allowableValues.min and\/or allowableValues.max parameters for allowableValues.range of/ it 'should an allowableValues range with min greater than max failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badRangeApi3.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /min value should not be greater tha max value in/ it 'should a properly configured allowableValues list be validated', -> assert.doesNotThrow -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/listApi.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) it 'should an allowableValues list without values failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badListApi.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /allowableValues.values is missing or is not an array for allowableValues.list of/ it 'should an allowableValues range with values which is not an array failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badListApi2.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /allowableValues.values is missing or is not an array for allowableValues.list of/ describe 'given a properly configured and started server', -> # given a started server before (done) -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/validatedApi.yml' controller: passed: (req, res) -> res.json status: 'passed' returnParams: (req, res) -> res.json req.input returnBody: (req, res) -> res.json body:req.body ]) .use(validator = swagger.validator app) .use(swagger.errorHandler()) app.get "/unvalidated", (req, res) -> res.json status:'passed' server = http.createServer app server.listen port, host, _.defer(done) after (done) -> server.close() done() it 'should unvalidated API be available', (done) -> getApi 'unvalidated', null, {}, 200, {status:'passed'}, done it 'should validated API without parameters be available', (done) -> getApi 'api/noparams/18', null, {}, 200, {status:'passed'}, done it 'should validation function be called manually', (done) -> casted = {} url = '/api/queryparams' # method, Express path, url, query, headers, body, casted, callback validator.validate 'GET', url, url, {param1:"-2", param2:"5.5"}, {}, {}, casted, (err) -> return done err if err? assert.equal casted.param1, -2 assert.equal casted.param2, 5.5 done() describe 'given an api accepting query parameters', -> it 'should required be checked', (done) -> getApi 'api/queryparams', null, {}, 400, {message: 'query parameter param1 is required'}, done it 'should optionnal be allowed', (done) -> query = param1:10 getApi 'api/queryparams', query, {}, 200, query, done it 'should integer and float be parsed', (done) -> query = param1:-2, param2:5.5 getApi 'api/queryparams', query, {}, 200, query, done it 'should float not accepted as integer', (done) -> getApi 'api/queryparams', {param1:3.2}, {}, 400, {message: 'query parameter param1 is a number when it should be an integer'}, done it 'should malformed number not accepted as integer', (done) -> getApi 'api/queryparams', {param1:'3x'}, {}, 400, {message: 'query parameter param1 is a string when it should be an integer'}, done it 'should empty string not accepted for a number', (done) -> getApi 'api/queryparams?param1=', null, {}, 400, {message: 'query parameter param1 is a string when it should be an integer'}, done it 'should string not accepted for a number', (done) -> getApi 'api/queryparams', {param1:'yeah'}, {}, 400, {message: 'query parameter param1 is a string when it should be an integer'}, done it 'should multiple parameter accept single value', (done) -> getApi 'api/queryparams', {param1:0, param3:true}, {}, 200, {param1: 0, param3: [true]}, done it 'should multiple parameter accept multiple value', (done) -> getApi 'api/queryparams?param1=0&param3=true&param3=false', {}, {}, 200, {param1: 0, param3: [true, false]}, done it 'should multiple parameter accept coma-separated value', (done) -> getApi 'api/queryparams', {param1:0, param3:'true,false'}, {}, 200, {param1: 0, param3: [true, false]}, done it 'should multiple be checked', (done) -> getApi 'api/queryparams', {param1:0, param3: [true, 'toto']}, {}, 400, {message: 'query parameter param3 property \'[1]\' is a string when it should be a boolean'}, done it 'should complex json be parsed', (done) -> obj = id: 10 name: '<NAME>' addresses: [ city: 'lyon' street: 'bd vivier merles' zipcode: 69006 ] getApi 'api/complexqueryparam', {user:JSON.stringify obj}, {}, 200, {user:obj}, done describe 'given an api accepting header parameters', -> it 'should required be checked', (done) -> getApi 'api/headerparams', null, {}, 400, {message: 'header param1 is required'}, done it 'should optionnal be allowed', (done) -> headers = param1: 10 getApi 'api/headerparams', null, headers, 200, headers, done it 'should long and boolean be parsed', (done) -> headers = param1: -2 param2: false getApi 'api/headerparams', null, headers, 200, headers, done it 'should double not accepted as integer', (done) -> getApi 'api/headerparams', null, {param1:3.2}, 400, {message: 'header param1 is a number when it should be an integer'}, done it 'should empty string not accepted for a boolean', (done) -> getApi 'api/headerparams', null, {param1: 0, param2:''}, 400, {message: 'header param2 is a string when it should be a boolean'}, done it 'should string not accepted for a boolean', (done) -> getApi 'api/headerparams', null, {param1: 0, param2:'yeah'}, 400, {message: 'header param2 is a string when it should be a boolean'}, done it 'should multiple parameter accept single value', (done) -> getApi 'api/headerparams', null, {param1:0, param3:1.5}, 200, {param1: 0, param3: [1.5]}, done it 'should multiple parameter accept multiple value', (done) -> getApi 'api/headerparams', null, {param1:-2, param3: '2.1, -4.6'}, 200, {param1:-2, param3: [2.1, -4.6]}, done it 'should multiple be checked', (done) -> getApi 'api/headerparams', null, {param1:0, param3: [true, 1.5]}, 400, {message: 'header param3 property \'[0]\' is a string when it should be a number'}, done it 'should complex json be parsed', (done) -> obj = id: 10 name: '<NAME>' addresses: [ city: 'lyon' street: 'bd vivier merles' zipcode: 69006 ] getApi 'api/complexheaderparam', null, {user:JSON.stringify obj}, 200, {user:obj}, done describe 'given an api accepting path parameters', -> it 'should required be checked', (done) -> getApi 'api/pathparams', null, {}, 404, 'Cannot GET /api/pathparams', done it 'should int and boolean be parsed', (done) -> getApi 'api/pathparams/10/true', null, {}, 200, {param1:10, param2:true}, done it 'should take wildcard path param', (done) -> getApi 'api/pathparams/10/foo/bar/suffix', null, {}, 200, {param1:'10', 'param2*':'foo/bar'}, done describe 'given an api accepting body parameters', -> it 'should plain text body be parsed', (done) -> postApi 'api/singleintbody', {'Content-Type': 'text/plain'}, '1000', 200, {body:1000}, done it 'should plain text body be checked', (done) -> postApi 'api/singleintbody', {'Content-Type': 'text/plain'}, 'toto', 400, {message: 'body is a string when it should be an integer'}, done it 'should plain text body be required', (done) -> postApi 'api/singleintbody', {'Content-Type': 'text/plain'}, undefined, 400, {message: 'body is required'}, done it 'should primitive json body be parsed', (done) -> postApi 'api/singleintbody', {'Content-Type': 'application/json'}, '[-500]', 200, {body:-500}, done it 'should primitive json body be checked', (done) -> postApi 'api/singleintbody', {'Content-Type': 'application/json'}, '[true]', 400, {message: 'body is an array when it should be an integer'}, done it 'should primitive json body be required', (done) -> postApi 'api/singleintbody', {'Content-Type': 'application/json'}, undefined, 400, {message: 'Bad Request'}, done it 'should body parameter be optionnal', (done) -> postApi 'api/optionnalbody', null, undefined, 200, {}, done it 'should form-encoded body be required', (done) -> postApi 'api/multiplebody', {'Content-Type': 'application/x-www-form-urlencoded'}, undefined, 400, {message: 'body parameter param1 is required'}, done it 'should multi-part body be required', (done) -> multipartApi 'api/multiplebody', true, [{name: 'param', body: 'toto'}], 400, {message: 'body parameter param1 is required'}, done it 'should form-encoded body be parsed and casted down', (done) -> postApi 'api/multiplebody', {'Content-Type': 'application/x-www-form-urlencoded'}, 'param1=10&param2=true,false', 200, {body:{param1: 10, param2: [true, false]}}, done it 'should multi-part/related body not be parsed', (done) -> multipartApi 'api/multiplebody', false, [ name: 'param1' body: '-5' , name: 'param2' body: 'false,true' ], 400, {message: 'body parameter param1 is required'}, done it 'should multi-part/form-data body be parsed and casted down', (done) -> multipartApi 'api/multiplebody', true, [ name: 'param1' body: '-5' , name: 'param2' body: 'false,true' ], 200, {body:{param1: -5, param2: [false, true]}}, done it 'should multi-part body parameter be optionnal', (done) -> multipartApi 'api/multiplebody', true, [{name: 'param1', body: '0'}], 200, {body:{param1: 0}}, done it 'should complex json body be parsed', (done) -> obj = id: 10 name: '<NAME>' addresses: [ city: 'lyon' street: 'bd vivier merle' zipcode: 69006 ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body:obj}, done it 'should multiple anonymous optionnal body accept one value', (done) -> postApi 'api/multipleanonymousbody', undefined, '1', 200, {body: [1]}, done it 'should multiple anonymous optionnal body accept multiple values', (done) -> postApi 'api/multipleanonymousbody', undefined, '1,2,3', 200, {body: [1,2,3]}, done it 'should multiple anonymous optionnal body accept no values', (done) -> postApi 'api/multipleanonymousbody', undefined, undefined, 200, {}, done it 'should multiple anonymous optionnal body accept one json value', (done) -> postApi 'api/multipleanonymousbody', {'Content-Type': 'application/json'}, '[1]', 200, {body: [1]}, done it 'should multiple anonymous optionnal body accept multiple json values', (done) -> postApi 'api/multipleanonymousbody', {'Content-Type': 'application/json'}, '[1,2,3]', 200, {body: [1,2,3]}, done it 'should multiple complex optionnal body accept no values', (done) -> postApi 'api/multiplecomplexbody', undefined, undefined, 200, {}, done it 'should multiple complex optionnal body accept one json value', (done) -> postApi 'api/multiplecomplexbody', {'Content-Type': 'application/json'}, '{"id":1, "name":"<NAME>"}', 200, {body: [{id:1, name:'<NAME>'}]}, done it 'should multiple complex optionnal body accept multiple json values', (done) -> postApi 'api/multiplecomplexbody', {'Content-Type': 'application/json'}, '[{"id":1, "name":"<NAME>"},{"id":2, "name":"<NAME>"}]', 200, {body: [ {id:1, name:'<NAME>'}, {id:2, name:'<NAME>'} ]}, done describe 'given an api accepting model parameter', -> it 'should complex json body be checked', (done) -> obj = id: 11 firstName: '<NAME>' lastName: '<NAME>' addresses: [] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'firstName' is not explicitly defined and therefore not allowed"}, done it 'should complex json body refs be checked', (done) -> obj = id: 12 name: '<NAME>' addresses: [ ville: 'lyon', street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'addresses.[0].ville' is not explicitly defined and therefore not allowed"}, done it 'should range list value be checked', (done) -> obj = id: 12 name: '<NAME>' addresses: [ city: 'strasbourd' zipcode: 67000 street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'addresses.[0].city' is not in enum"}, done it 'should range interval value be checked', (done) -> obj = id: 12 name: '<NAME>' addresses: [ city: 'lyon' zipcode: 100000 street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'addresses.[0].zipcode' is 100000 when it should be at most 99999"}, done it 'should required attributes be checked', (done) -> obj = name: '<NAME>' addresses: [ city: 'lyon' zipcode: 69003 street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'id' is required"}, done it 'should primitive values be parsed', (done) -> obj = id: true name: '<NAME>' addresses: [ city: 'lyon' zipcode: 69003 street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'id' is a boolean when it should be an integer"}, done it 'should additionnal attribute not be allowed', (done) -> obj = id: 20 name: '<NAME>' addresses: [ city: 'lyon' zipcode: 69003 street: 'bd vivier merle' other: 'coucou' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'addresses.[0].other' is not explicitly defined and therefore not allowed"}, done it 'should optionnal attribute be allowed', (done) -> obj = id: 30 postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body: obj}, done it 'should complex attribute not be checked', (done) -> obj = id: 20 name: '<NAME>' stuff: name: 10 addresses: [ city: 'lyon' zipcode: 69003 street: 'bd vivier merle' other: 'coucou' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'stuff.name' is an integer when it should be a string"}, done it 'should classical json-schema specification be usabled', (done) -> obj = id: 20 other: '<NAME>' phone: '000-1234' postApi 'api/jsonschemabody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'phone' does not match pattern"}, done it 'should any be accepted as type within models', (done) -> obj = id: 20 name: [] phone: '00000-1234' postApi 'api/jsonschemabody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body:obj}, done it 'should accept union type', (done) -> obj = id: 1 name: first: '<NAME>' last: '<NAME>' postApi 'api/unionbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body:obj}, (err) -> return done err if err? obj.name = '<NAME>' postApi 'api/unionbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body:obj}, done it 'should accept upload file', (done) -> file = pathUtils.join __dirname, 'fixtures', 'circular.yml' uploadFilePostApi 'api/upload', file, 'file', 200, {status:'passed'}, done it 'should reject when passing file not in multipart', (done) -> file = pathUtils.join __dirname, 'fixtures/circular.yml' postApi 'api/upload', {'Content-Type': 'application/json'}, JSON.stringify(file:file.toString()), 400, {message: "body parameter file is required"}, done it 'should fail on missing body file', (done) -> file = pathUtils.join __dirname, 'fixtures/circular.yml' uploadFilePostApi 'api/upload', file, 'other', 400, {message: "body parameter file is required"}, done # TODO post, put, delete, model list-set-arrays
true
require 'js-yaml' express = require 'express' assert = require('chai').assert request = require 'request' http = require 'http' fs = require 'fs' swagger = require '../' pathUtils = require 'path' _ = require 'underscore' server = null host = 'localhost' port = 8090 root = "http://#{host}:#{port}" validator = null # test function: send an Http request (a get) and expect a status and a json body. getApi = (name, params, headers, status, expectedBody, done, extra) -> request.get url: "#{root}/#{name}" qs: params headers: headers json: true , (err, res, body) -> return done err if err? assert.equal res.statusCode, status, "unexpected status when getting #{root}/#{name}, body:\n#{JSON.stringify body}" if _.isFunction extra extra res, body, done else assert.deepEqual body, expectedBody, "unexpected body when getting #{root}/#{name}" done() # test function: send an Http request (a post) and expect a status and a json body. postApi = (name, headers, body, status, expectedBody, done) -> request.post url: "#{root}/#{name}" headers: headers body: body encoding: 'utf8' , (err, res, body) -> return done err if err? try body = JSON.parse body catch err return done "failed to parse body:#{err}\n#{body}" assert.equal res.statusCode, status, "unexpected status when getting #{root}/#{name}, body:\n#{JSON.stringify body}" assert.deepEqual body, expectedBody, "unexpected body when getting #{root}/#{name}" done() # test function: send an Http request (a post) and expect a status and a json body. uploadFilePostApi = (name, file, partName, status, expectedBody, done) -> req = request.post url: "#{root}/#{name}" , (err, res, body) -> return done err if err? assert.equal res.statusCode, status, "unexpected status when getting #{root}/#{name}, body:\n#{JSON.stringify body}" assert.deepEqual JSON.parse(body), expectedBody, "unexpected body when getting #{root}/#{name}" done() req.form().append partName, fs.createReadStream file # test function: send an Http request (a post multipart/form-data) and expect a status and a json body. multipartApi = (name, formdata, parts, status, expectedBody, done) -> req = url: "#{root}/#{name}" multipart: [] encoding: 'utf8' if formdata req.headers = 'content-type': 'multipart/form-data' for part in parts obj = body: part.body obj['content-disposition'] = "form-data; name=\"#{part.name}\"" if part.name? req.multipart.push obj request.post req, (err, res, body) -> return done err if err? try body = JSON.parse(body); catch err return done "failed to parse body:#{err}\n#{body}" assert.equal res.statusCode, status, "unexpected status when getting #{root}/#{name}, body:\n#{JSON.stringify body }" assert.deepEqual body, expectedBody, "unexpected body when getting #{root}/#{name}" done() describe 'API validation tests', -> it 'should fail if no express application is provided', -> assert.throws -> swagger.validator {} , /No Express application provided/ it 'should fail if provided applicatino was not analyzed', -> assert.throws -> swagger.validator express() , /No Swagger descriptor found within express application/ it 'should circular references be detected at statup', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/circular.yml' controller: returnBody: (req, res) -> res.json body:req.body ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /Circular reference detected: CircularUser > AddressBook > CircularUser/ describe 'given a basePath configured server', -> # given a started server before (done) -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: "#{root}/basepath" , [ api: require './fixtures/listApi.yml' controller: returnParams: (req, res) -> res.json req.input ]) .use(validator = swagger.validator app) .use(swagger.errorHandler()) server = http.createServer app server.listen port, host, _.defer(done) after (done) -> server.close() done() it 'should api be validated', (done) -> # when requesting the API getApi 'basepath/api/queryparams', null, {}, 400, {message: 'query parameter param1 is required'}, done it 'should api be invpked', (done) -> # when requesting the API getApi 'basepath/api/queryparams?param1=2', null, {}, 200, {param1: 2}, done describe 'given an allowableValues parameter', -> it 'should a properly configured allowableValues range be validated', -> assert.doesNotThrow -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/rangeApi.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) it 'should an allowableValues range without min value failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badRangeApi.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /missing allowableValues.min and\/or allowableValues.max parameters for allowableValues.range of/ it 'should an allowableValues range without max value failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badRangeApi2.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /missing allowableValues.min and\/or allowableValues.max parameters for allowableValues.range of/ it 'should an allowableValues range with min greater than max failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badRangeApi3.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /min value should not be greater tha max value in/ it 'should a properly configured allowableValues list be validated', -> assert.doesNotThrow -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/listApi.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) it 'should an allowableValues list without values failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badListApi.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /allowableValues.values is missing or is not an array for allowableValues.list of/ it 'should an allowableValues range with values which is not an array failed', -> assert.throws -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/badListApi2.yml' controller: returnParams: (req, res) -> res.json status: 'passed' ]) .use(swagger.validator(app)) .use(swagger.errorHandler()) , /allowableValues.values is missing or is not an array for allowableValues.list of/ describe 'given a properly configured and started server', -> # given a started server before (done) -> app = express() # configured to use swagger generator app.use(express.bodyParser()) .use(express.methodOverride()) .use(swagger.generator app, apiVersion: '1.0' basePath: root , [ api: require './fixtures/validatedApi.yml' controller: passed: (req, res) -> res.json status: 'passed' returnParams: (req, res) -> res.json req.input returnBody: (req, res) -> res.json body:req.body ]) .use(validator = swagger.validator app) .use(swagger.errorHandler()) app.get "/unvalidated", (req, res) -> res.json status:'passed' server = http.createServer app server.listen port, host, _.defer(done) after (done) -> server.close() done() it 'should unvalidated API be available', (done) -> getApi 'unvalidated', null, {}, 200, {status:'passed'}, done it 'should validated API without parameters be available', (done) -> getApi 'api/noparams/18', null, {}, 200, {status:'passed'}, done it 'should validation function be called manually', (done) -> casted = {} url = '/api/queryparams' # method, Express path, url, query, headers, body, casted, callback validator.validate 'GET', url, url, {param1:"-2", param2:"5.5"}, {}, {}, casted, (err) -> return done err if err? assert.equal casted.param1, -2 assert.equal casted.param2, 5.5 done() describe 'given an api accepting query parameters', -> it 'should required be checked', (done) -> getApi 'api/queryparams', null, {}, 400, {message: 'query parameter param1 is required'}, done it 'should optionnal be allowed', (done) -> query = param1:10 getApi 'api/queryparams', query, {}, 200, query, done it 'should integer and float be parsed', (done) -> query = param1:-2, param2:5.5 getApi 'api/queryparams', query, {}, 200, query, done it 'should float not accepted as integer', (done) -> getApi 'api/queryparams', {param1:3.2}, {}, 400, {message: 'query parameter param1 is a number when it should be an integer'}, done it 'should malformed number not accepted as integer', (done) -> getApi 'api/queryparams', {param1:'3x'}, {}, 400, {message: 'query parameter param1 is a string when it should be an integer'}, done it 'should empty string not accepted for a number', (done) -> getApi 'api/queryparams?param1=', null, {}, 400, {message: 'query parameter param1 is a string when it should be an integer'}, done it 'should string not accepted for a number', (done) -> getApi 'api/queryparams', {param1:'yeah'}, {}, 400, {message: 'query parameter param1 is a string when it should be an integer'}, done it 'should multiple parameter accept single value', (done) -> getApi 'api/queryparams', {param1:0, param3:true}, {}, 200, {param1: 0, param3: [true]}, done it 'should multiple parameter accept multiple value', (done) -> getApi 'api/queryparams?param1=0&param3=true&param3=false', {}, {}, 200, {param1: 0, param3: [true, false]}, done it 'should multiple parameter accept coma-separated value', (done) -> getApi 'api/queryparams', {param1:0, param3:'true,false'}, {}, 200, {param1: 0, param3: [true, false]}, done it 'should multiple be checked', (done) -> getApi 'api/queryparams', {param1:0, param3: [true, 'toto']}, {}, 400, {message: 'query parameter param3 property \'[1]\' is a string when it should be a boolean'}, done it 'should complex json be parsed', (done) -> obj = id: 10 name: 'PI:NAME:<NAME>END_PI' addresses: [ city: 'lyon' street: 'bd vivier merles' zipcode: 69006 ] getApi 'api/complexqueryparam', {user:JSON.stringify obj}, {}, 200, {user:obj}, done describe 'given an api accepting header parameters', -> it 'should required be checked', (done) -> getApi 'api/headerparams', null, {}, 400, {message: 'header param1 is required'}, done it 'should optionnal be allowed', (done) -> headers = param1: 10 getApi 'api/headerparams', null, headers, 200, headers, done it 'should long and boolean be parsed', (done) -> headers = param1: -2 param2: false getApi 'api/headerparams', null, headers, 200, headers, done it 'should double not accepted as integer', (done) -> getApi 'api/headerparams', null, {param1:3.2}, 400, {message: 'header param1 is a number when it should be an integer'}, done it 'should empty string not accepted for a boolean', (done) -> getApi 'api/headerparams', null, {param1: 0, param2:''}, 400, {message: 'header param2 is a string when it should be a boolean'}, done it 'should string not accepted for a boolean', (done) -> getApi 'api/headerparams', null, {param1: 0, param2:'yeah'}, 400, {message: 'header param2 is a string when it should be a boolean'}, done it 'should multiple parameter accept single value', (done) -> getApi 'api/headerparams', null, {param1:0, param3:1.5}, 200, {param1: 0, param3: [1.5]}, done it 'should multiple parameter accept multiple value', (done) -> getApi 'api/headerparams', null, {param1:-2, param3: '2.1, -4.6'}, 200, {param1:-2, param3: [2.1, -4.6]}, done it 'should multiple be checked', (done) -> getApi 'api/headerparams', null, {param1:0, param3: [true, 1.5]}, 400, {message: 'header param3 property \'[0]\' is a string when it should be a number'}, done it 'should complex json be parsed', (done) -> obj = id: 10 name: 'PI:NAME:<NAME>END_PI' addresses: [ city: 'lyon' street: 'bd vivier merles' zipcode: 69006 ] getApi 'api/complexheaderparam', null, {user:JSON.stringify obj}, 200, {user:obj}, done describe 'given an api accepting path parameters', -> it 'should required be checked', (done) -> getApi 'api/pathparams', null, {}, 404, 'Cannot GET /api/pathparams', done it 'should int and boolean be parsed', (done) -> getApi 'api/pathparams/10/true', null, {}, 200, {param1:10, param2:true}, done it 'should take wildcard path param', (done) -> getApi 'api/pathparams/10/foo/bar/suffix', null, {}, 200, {param1:'10', 'param2*':'foo/bar'}, done describe 'given an api accepting body parameters', -> it 'should plain text body be parsed', (done) -> postApi 'api/singleintbody', {'Content-Type': 'text/plain'}, '1000', 200, {body:1000}, done it 'should plain text body be checked', (done) -> postApi 'api/singleintbody', {'Content-Type': 'text/plain'}, 'toto', 400, {message: 'body is a string when it should be an integer'}, done it 'should plain text body be required', (done) -> postApi 'api/singleintbody', {'Content-Type': 'text/plain'}, undefined, 400, {message: 'body is required'}, done it 'should primitive json body be parsed', (done) -> postApi 'api/singleintbody', {'Content-Type': 'application/json'}, '[-500]', 200, {body:-500}, done it 'should primitive json body be checked', (done) -> postApi 'api/singleintbody', {'Content-Type': 'application/json'}, '[true]', 400, {message: 'body is an array when it should be an integer'}, done it 'should primitive json body be required', (done) -> postApi 'api/singleintbody', {'Content-Type': 'application/json'}, undefined, 400, {message: 'Bad Request'}, done it 'should body parameter be optionnal', (done) -> postApi 'api/optionnalbody', null, undefined, 200, {}, done it 'should form-encoded body be required', (done) -> postApi 'api/multiplebody', {'Content-Type': 'application/x-www-form-urlencoded'}, undefined, 400, {message: 'body parameter param1 is required'}, done it 'should multi-part body be required', (done) -> multipartApi 'api/multiplebody', true, [{name: 'param', body: 'toto'}], 400, {message: 'body parameter param1 is required'}, done it 'should form-encoded body be parsed and casted down', (done) -> postApi 'api/multiplebody', {'Content-Type': 'application/x-www-form-urlencoded'}, 'param1=10&param2=true,false', 200, {body:{param1: 10, param2: [true, false]}}, done it 'should multi-part/related body not be parsed', (done) -> multipartApi 'api/multiplebody', false, [ name: 'param1' body: '-5' , name: 'param2' body: 'false,true' ], 400, {message: 'body parameter param1 is required'}, done it 'should multi-part/form-data body be parsed and casted down', (done) -> multipartApi 'api/multiplebody', true, [ name: 'param1' body: '-5' , name: 'param2' body: 'false,true' ], 200, {body:{param1: -5, param2: [false, true]}}, done it 'should multi-part body parameter be optionnal', (done) -> multipartApi 'api/multiplebody', true, [{name: 'param1', body: '0'}], 200, {body:{param1: 0}}, done it 'should complex json body be parsed', (done) -> obj = id: 10 name: 'PI:NAME:<NAME>END_PI' addresses: [ city: 'lyon' street: 'bd vivier merle' zipcode: 69006 ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body:obj}, done it 'should multiple anonymous optionnal body accept one value', (done) -> postApi 'api/multipleanonymousbody', undefined, '1', 200, {body: [1]}, done it 'should multiple anonymous optionnal body accept multiple values', (done) -> postApi 'api/multipleanonymousbody', undefined, '1,2,3', 200, {body: [1,2,3]}, done it 'should multiple anonymous optionnal body accept no values', (done) -> postApi 'api/multipleanonymousbody', undefined, undefined, 200, {}, done it 'should multiple anonymous optionnal body accept one json value', (done) -> postApi 'api/multipleanonymousbody', {'Content-Type': 'application/json'}, '[1]', 200, {body: [1]}, done it 'should multiple anonymous optionnal body accept multiple json values', (done) -> postApi 'api/multipleanonymousbody', {'Content-Type': 'application/json'}, '[1,2,3]', 200, {body: [1,2,3]}, done it 'should multiple complex optionnal body accept no values', (done) -> postApi 'api/multiplecomplexbody', undefined, undefined, 200, {}, done it 'should multiple complex optionnal body accept one json value', (done) -> postApi 'api/multiplecomplexbody', {'Content-Type': 'application/json'}, '{"id":1, "name":"PI:NAME:<NAME>END_PI"}', 200, {body: [{id:1, name:'PI:NAME:<NAME>END_PI'}]}, done it 'should multiple complex optionnal body accept multiple json values', (done) -> postApi 'api/multiplecomplexbody', {'Content-Type': 'application/json'}, '[{"id":1, "name":"PI:NAME:<NAME>END_PI"},{"id":2, "name":"PI:NAME:<NAME>END_PI"}]', 200, {body: [ {id:1, name:'PI:NAME:<NAME>END_PI'}, {id:2, name:'PI:NAME:<NAME>END_PI'} ]}, done describe 'given an api accepting model parameter', -> it 'should complex json body be checked', (done) -> obj = id: 11 firstName: 'PI:NAME:<NAME>END_PI' lastName: 'PI:NAME:<NAME>END_PI' addresses: [] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'firstName' is not explicitly defined and therefore not allowed"}, done it 'should complex json body refs be checked', (done) -> obj = id: 12 name: 'PI:NAME:<NAME>END_PI' addresses: [ ville: 'lyon', street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'addresses.[0].ville' is not explicitly defined and therefore not allowed"}, done it 'should range list value be checked', (done) -> obj = id: 12 name: 'PI:NAME:<NAME>END_PI' addresses: [ city: 'strasbourd' zipcode: 67000 street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'addresses.[0].city' is not in enum"}, done it 'should range interval value be checked', (done) -> obj = id: 12 name: 'PI:NAME:<NAME>END_PI' addresses: [ city: 'lyon' zipcode: 100000 street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'addresses.[0].zipcode' is 100000 when it should be at most 99999"}, done it 'should required attributes be checked', (done) -> obj = name: 'PI:NAME:<NAME>END_PI' addresses: [ city: 'lyon' zipcode: 69003 street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'id' is required"}, done it 'should primitive values be parsed', (done) -> obj = id: true name: 'PI:NAME:<NAME>END_PI' addresses: [ city: 'lyon' zipcode: 69003 street: 'bd vivier merle' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'id' is a boolean when it should be an integer"}, done it 'should additionnal attribute not be allowed', (done) -> obj = id: 20 name: 'PI:NAME:<NAME>END_PI' addresses: [ city: 'lyon' zipcode: 69003 street: 'bd vivier merle' other: 'coucou' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'addresses.[0].other' is not explicitly defined and therefore not allowed"}, done it 'should optionnal attribute be allowed', (done) -> obj = id: 30 postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body: obj}, done it 'should complex attribute not be checked', (done) -> obj = id: 20 name: 'PI:NAME:<NAME>END_PI' stuff: name: 10 addresses: [ city: 'lyon' zipcode: 69003 street: 'bd vivier merle' other: 'coucou' ] postApi 'api/complexbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'stuff.name' is an integer when it should be a string"}, done it 'should classical json-schema specification be usabled', (done) -> obj = id: 20 other: 'PI:NAME:<NAME>END_PI' phone: '000-1234' postApi 'api/jsonschemabody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 400, {message: "body property 'phone' does not match pattern"}, done it 'should any be accepted as type within models', (done) -> obj = id: 20 name: [] phone: '00000-1234' postApi 'api/jsonschemabody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body:obj}, done it 'should accept union type', (done) -> obj = id: 1 name: first: 'PI:NAME:<NAME>END_PI' last: 'PI:NAME:<NAME>END_PI' postApi 'api/unionbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body:obj}, (err) -> return done err if err? obj.name = 'PI:NAME:<NAME>END_PI' postApi 'api/unionbody', {'Content-Type': 'application/json'}, JSON.stringify(obj), 200, {body:obj}, done it 'should accept upload file', (done) -> file = pathUtils.join __dirname, 'fixtures', 'circular.yml' uploadFilePostApi 'api/upload', file, 'file', 200, {status:'passed'}, done it 'should reject when passing file not in multipart', (done) -> file = pathUtils.join __dirname, 'fixtures/circular.yml' postApi 'api/upload', {'Content-Type': 'application/json'}, JSON.stringify(file:file.toString()), 400, {message: "body parameter file is required"}, done it 'should fail on missing body file', (done) -> file = pathUtils.join __dirname, 'fixtures/circular.yml' uploadFilePostApi 'api/upload', file, 'other', 400, {message: "body parameter file is required"}, done # TODO post, put, delete, model list-set-arrays
[ { "context": ",\n username: socket.username,\n time: val2.time,", "end": 2491, "score": 0.7567838430404663, "start": 2483, "tag": "USERNAME", "value": "username" }, { "context": ",\n username...
v0.5/server.coffee
KingSann/TinyChat
1
express = require "express" app = express() http = require("http").Server app io = require("socket.io") http fs = require "fs" md5 = require "md5" readline = require "readline" moment = require "moment" moment.locale "zh-cn" gettime = -> moment().format "YYYY-MM-DD HH:mm:ss" # 名单类,用于处理名单 class Roll _roll: {} constructor: (@_roll = {}) -> insert: (key, val) -> if not @_roll[key] then @_roll[key] = val else undefined erase: (key) -> delete @_roll[key] get: (key) -> @_roll[key] exist: (key, val) -> @_roll[key] and @_roll[key] is val # 储物类,用于处理存储 class Cache _cache: [] constructor: (@_cache = []) -> insert: (data) -> @_cache.push data erase: (data) -> @_cache = (dt for dt in @_cache when dt isnt data) exist: (data) -> data in @_cache # 用户类,用于存储用户信息以及sockets class User @sockets = {} # 插入一个用户连接 @insert = (name, socket) -> @sockets[name].insert socket # 删除一个用户连接 @erase = (name, socket) -> @sockets[name].erase socket socket?.disconnect?() @roll = new Roll() # 注册一个用户 @register = (name, password) -> @roll.insert name, password @sockets[name] ?= new Cache() # 注销一个用户 @unregister = (name) -> sck?.disconnect?() for sck in @sockets[name]._cache if @sockets[name] @roll.erase name # 判断一个用户存在性 @exist = (name, password) -> @roll.exist name, password # 房间类,用于存储房间信息以及sockets class Room @hist = {} @sockets = {} @roll = new Roll() # 注册一个房间 @register = (name, password) -> @roll.insert name, password @sockets[name] = new Cache() # 注销一个房间 @unregister = (name) -> @roll.erase name @send name, "sys", time: gettime(), data: "the room #{name} is unregistered", sck?.isjoin = false for sck in @sockets[name]._cache delete @sockets[name] # 判断一个房间存在性 @exist = (name, password) -> @roll.exist name, password # 加入一个用户 @join = (name, socket) -> @sockets[name].insert socket @send name, "sys", time: gettime(), data: "#{socket.username} joined", for key1, val1 of @hist[name] for key2, val2 of val1 if val2.type is "text" socket.emit "new message", username: socket.username, time: val2.time, ishist: true, data: "#{val2.data}".replace /[<>&"]/g, (c) -> ("<": "&lt;", ">": "&gt;", "&": "&amp;", "\"": "&quot;")[c] else if val2.type is "image" socket.emit "new image", username: socket.username, time: val2.time, ishist: true, data: "#{val2.data}", # 离开一个用户 @leave = (name, socket) -> socket.isjoin = false @sockets[name].erase socket @send name, "sys", time: gettime(), data: "#{socket.username} left", # 全体发送消息 @send = (name, ent, data) -> sck?.emit? ent, data for sck in @sockets[name]._cache # 判断房间里一个用户存在性 @existUser = (name, username) -> for sck in @sockets[name]._cache return true if sck?.username is username return false # 保存留言 @insertHist = (name, data) -> @hist[name] ?= {} @hist[name][data.username] ?= [] @hist[name][data.username].push data # 删除留言 @eraseHist = (name, username) -> delete @hist[name]?[username] # 获取在线用户 @getCuruser = (name) -> sck.username for sck in @sockets[name]._cache # 发送所有留言 @sendHist = (name, username, socket) -> for key1, val1 of @hist[name] for key2, val2 of val1 if val2.type is "text" socket.emit "new message", username: socket.username, time: val2.time, ishist: true, data: "#{val2.data}".replace /[<>&"]/g, (c) -> ("<": "&lt;", ">": "&gt;", "&": "&amp;", "\"": "&quot;")[c] else if val2.type is "image" socket.emit "new image", username: socket.username, time: val2.time, ishist: true, data: "#{val2.data}", io.on "connection", (socket) -> # 用户登录 socket.on "login", (data) -> time = gettime() if not socket.islogin if User.exist data.username, data.password User.insert data.username, socket socket.username = data.username socket.password = data.password socket.islogin = true socket.emit "sys", time: time, data: "login succeeded", else socket.emit "sys", time: time, data: "login failed", else socket.emit "sys", time: time, data: "has been logined", # 用户加入房间 socket.on "join", (data) -> time = gettime() if socket.islogin if Room.exist data.roomname, data.roompassword Room.join data.roomname, socket socket.roomname = data.roomname socket.roompassword = data.roompassword socket.isjoin = true socket.emit "sys", time: time, data: "join succeeded", else socket.emit "sys", time: time, data: "join failed", else socket.emit "sys", time: time, data: "please login first", # 用户发言/图 socket.on "message", (data) -> data.username = socket.username # Room.insertHist 使用 data.time = gettime() # Room.insertHist 使用 type = data.type # 类型: text 文字 | image 图片 dt = data.data # 数据 ishist = data.ishist # 是否历史化: true 记录到留言 | false 不记录到留言 time = data.time # 时间 if socket.islogin if socket.isjoin if "#{dt}" isnt "" if type is "text" Room.send socket.roomname, "new message", username: socket.username, time: time, ishist: ishist, data: "#{dt}".replace /[<>&"]/g, (c) -> ("<": "&lt;", ">": "&gt;", "&": "&amp;", "\"": "&quot;")[c] else if type is "image" Room.send socket.roomname, "new image", username: socket.username, time: time, ishist: ishist, data: "#{dt}", Room.insertHist socket.roomname, data if ishist else socket.emit "sys", time: time, data: "please input something", else socket.emit "sys", time: time, data: "please join first", else socket.emit "sys", time: time, data: "please login first", # 用户删除留言 socket.on "eraseHist", -> time = gettime() if socket.islogin if socket.isjoin Room.eraseHist socket.roomname, socket.username socket.emit "sys", time: time, data: "hist erased succeeded", else socket.emit "sys", time: time, data: "please join first", else socket.emit "sys", time: time, data: "please login first", # 用户离开房间 socket.on "leave", -> time = gettime() Room.leave socket.roomname, socket if socket.islogin and socket.isjoin socket.emit "sys", time: time, data: "left room #{socket.roomname}", # 用户登出 socket.on "logout", -> socket.disconnect() # 用户查询信息 socket.on "info", (data) -> time = gettime() if socket.islogin if socket.isjoin switch data.data when "curuser" socket.emit "sys", time: time, data: "#{username} is online" for username in Room.getCuruser socket.roomname when "me" socket.emit "sys", time: time, data: "i am #{socket.username}" when "room" socket.emit "sys", time: time, data: "i am in #{socket.roomname}" when "leftmsg" Room.sendHist socket.roomname, socket.username, socket else socket.emit "sys", time: time, data: "command not found: /info #{data.data}" else socket.emit "sys", time: time, data: "please join first", else socket.emit "sys", time: time, data: "please login first", # 用户断线 socket.on "disconnect", -> if socket.islogin Room.leave socket.roomname, socket if socket.isjoin User.erase socket.username, socket # 初始化 readline.createInterface input: fs.createReadStream "config.txt" .on "line", (line) -> [type, name, password] = line.split(" ") if type is "user" User.register name, password else if type is "room" Room.register name, password .on "close", () -> app.use "/", express.static "#{__dirname}/TinyChat" # http.listen 8080, -> console.log "listening on port 8080" http.listen 2333, -> console.log "listening on port 2333"
164056
express = require "express" app = express() http = require("http").Server app io = require("socket.io") http fs = require "fs" md5 = require "md5" readline = require "readline" moment = require "moment" moment.locale "zh-cn" gettime = -> moment().format "YYYY-MM-DD HH:mm:ss" # 名单类,用于处理名单 class Roll _roll: {} constructor: (@_roll = {}) -> insert: (key, val) -> if not @_roll[key] then @_roll[key] = val else undefined erase: (key) -> delete @_roll[key] get: (key) -> @_roll[key] exist: (key, val) -> @_roll[key] and @_roll[key] is val # 储物类,用于处理存储 class Cache _cache: [] constructor: (@_cache = []) -> insert: (data) -> @_cache.push data erase: (data) -> @_cache = (dt for dt in @_cache when dt isnt data) exist: (data) -> data in @_cache # 用户类,用于存储用户信息以及sockets class User @sockets = {} # 插入一个用户连接 @insert = (name, socket) -> @sockets[name].insert socket # 删除一个用户连接 @erase = (name, socket) -> @sockets[name].erase socket socket?.disconnect?() @roll = new Roll() # 注册一个用户 @register = (name, password) -> @roll.insert name, password @sockets[name] ?= new Cache() # 注销一个用户 @unregister = (name) -> sck?.disconnect?() for sck in @sockets[name]._cache if @sockets[name] @roll.erase name # 判断一个用户存在性 @exist = (name, password) -> @roll.exist name, password # 房间类,用于存储房间信息以及sockets class Room @hist = {} @sockets = {} @roll = new Roll() # 注册一个房间 @register = (name, password) -> @roll.insert name, password @sockets[name] = new Cache() # 注销一个房间 @unregister = (name) -> @roll.erase name @send name, "sys", time: gettime(), data: "the room #{name} is unregistered", sck?.isjoin = false for sck in @sockets[name]._cache delete @sockets[name] # 判断一个房间存在性 @exist = (name, password) -> @roll.exist name, password # 加入一个用户 @join = (name, socket) -> @sockets[name].insert socket @send name, "sys", time: gettime(), data: "#{socket.username} joined", for key1, val1 of @hist[name] for key2, val2 of val1 if val2.type is "text" socket.emit "new message", username: socket.username, time: val2.time, ishist: true, data: "#{val2.data}".replace /[<>&"]/g, (c) -> ("<": "&lt;", ">": "&gt;", "&": "&amp;", "\"": "&quot;")[c] else if val2.type is "image" socket.emit "new image", username: socket.username, time: val2.time, ishist: true, data: "#{val2.data}", # 离开一个用户 @leave = (name, socket) -> socket.isjoin = false @sockets[name].erase socket @send name, "sys", time: gettime(), data: "#{socket.username} left", # 全体发送消息 @send = (name, ent, data) -> sck?.emit? ent, data for sck in @sockets[name]._cache # 判断房间里一个用户存在性 @existUser = (name, username) -> for sck in @sockets[name]._cache return true if sck?.username is username return false # 保存留言 @insertHist = (name, data) -> @hist[name] ?= {} @hist[name][data.username] ?= [] @hist[name][data.username].push data # 删除留言 @eraseHist = (name, username) -> delete @hist[name]?[username] # 获取在线用户 @getCuruser = (name) -> sck.username for sck in @sockets[name]._cache # 发送所有留言 @sendHist = (name, username, socket) -> for key1, val1 of @hist[name] for key2, val2 of val1 if val2.type is "text" socket.emit "new message", username: socket.username, time: val2.time, ishist: true, data: "#{val2.data}".replace /[<>&"]/g, (c) -> ("<": "&lt;", ">": "&gt;", "&": "&amp;", "\"": "&quot;")[c] else if val2.type is "image" socket.emit "new image", username: socket.username, time: val2.time, ishist: true, data: "#{val2.data}", io.on "connection", (socket) -> # 用户登录 socket.on "login", (data) -> time = gettime() if not socket.islogin if User.exist data.username, data.password User.insert data.username, socket socket.username = data.username socket.password = <PASSWORD> socket.islogin = true socket.emit "sys", time: time, data: "login succeeded", else socket.emit "sys", time: time, data: "login failed", else socket.emit "sys", time: time, data: "has been logined", # 用户加入房间 socket.on "join", (data) -> time = gettime() if socket.islogin if Room.exist data.roomname, data.roompassword Room.join data.roomname, socket socket.roomname = data.roomname socket.roompassword = data.roompassword socket.isjoin = true socket.emit "sys", time: time, data: "join succeeded", else socket.emit "sys", time: time, data: "join failed", else socket.emit "sys", time: time, data: "please login first", # 用户发言/图 socket.on "message", (data) -> data.username = socket.username # Room.insertHist 使用 data.time = gettime() # Room.insertHist 使用 type = data.type # 类型: text 文字 | image 图片 dt = data.data # 数据 ishist = data.ishist # 是否历史化: true 记录到留言 | false 不记录到留言 time = data.time # 时间 if socket.islogin if socket.isjoin if "#{dt}" isnt "" if type is "text" Room.send socket.roomname, "new message", username: socket.username, time: time, ishist: ishist, data: "#{dt}".replace /[<>&"]/g, (c) -> ("<": "&lt;", ">": "&gt;", "&": "&amp;", "\"": "&quot;")[c] else if type is "image" Room.send socket.roomname, "new image", username: socket.username, time: time, ishist: ishist, data: "#{dt}", Room.insertHist socket.roomname, data if ishist else socket.emit "sys", time: time, data: "please input something", else socket.emit "sys", time: time, data: "please join first", else socket.emit "sys", time: time, data: "please login first", # 用户删除留言 socket.on "eraseHist", -> time = gettime() if socket.islogin if socket.isjoin Room.eraseHist socket.roomname, socket.username socket.emit "sys", time: time, data: "hist erased succeeded", else socket.emit "sys", time: time, data: "please join first", else socket.emit "sys", time: time, data: "please login first", # 用户离开房间 socket.on "leave", -> time = gettime() Room.leave socket.roomname, socket if socket.islogin and socket.isjoin socket.emit "sys", time: time, data: "left room #{socket.roomname}", # 用户登出 socket.on "logout", -> socket.disconnect() # 用户查询信息 socket.on "info", (data) -> time = gettime() if socket.islogin if socket.isjoin switch data.data when "curuser" socket.emit "sys", time: time, data: "#{username} is online" for username in Room.getCuruser socket.roomname when "me" socket.emit "sys", time: time, data: "i am #{socket.username}" when "room" socket.emit "sys", time: time, data: "i am in #{socket.roomname}" when "leftmsg" Room.sendHist socket.roomname, socket.username, socket else socket.emit "sys", time: time, data: "command not found: /info #{data.data}" else socket.emit "sys", time: time, data: "please join first", else socket.emit "sys", time: time, data: "please login first", # 用户断线 socket.on "disconnect", -> if socket.islogin Room.leave socket.roomname, socket if socket.isjoin User.erase socket.username, socket # 初始化 readline.createInterface input: fs.createReadStream "config.txt" .on "line", (line) -> [type, name, password] = line.split(" ") if type is "user" User.register name, password else if type is "room" Room.register name, password .on "close", () -> app.use "/", express.static "#{__dirname}/TinyChat" # http.listen 8080, -> console.log "listening on port 8080" http.listen 2333, -> console.log "listening on port 2333"
true
express = require "express" app = express() http = require("http").Server app io = require("socket.io") http fs = require "fs" md5 = require "md5" readline = require "readline" moment = require "moment" moment.locale "zh-cn" gettime = -> moment().format "YYYY-MM-DD HH:mm:ss" # 名单类,用于处理名单 class Roll _roll: {} constructor: (@_roll = {}) -> insert: (key, val) -> if not @_roll[key] then @_roll[key] = val else undefined erase: (key) -> delete @_roll[key] get: (key) -> @_roll[key] exist: (key, val) -> @_roll[key] and @_roll[key] is val # 储物类,用于处理存储 class Cache _cache: [] constructor: (@_cache = []) -> insert: (data) -> @_cache.push data erase: (data) -> @_cache = (dt for dt in @_cache when dt isnt data) exist: (data) -> data in @_cache # 用户类,用于存储用户信息以及sockets class User @sockets = {} # 插入一个用户连接 @insert = (name, socket) -> @sockets[name].insert socket # 删除一个用户连接 @erase = (name, socket) -> @sockets[name].erase socket socket?.disconnect?() @roll = new Roll() # 注册一个用户 @register = (name, password) -> @roll.insert name, password @sockets[name] ?= new Cache() # 注销一个用户 @unregister = (name) -> sck?.disconnect?() for sck in @sockets[name]._cache if @sockets[name] @roll.erase name # 判断一个用户存在性 @exist = (name, password) -> @roll.exist name, password # 房间类,用于存储房间信息以及sockets class Room @hist = {} @sockets = {} @roll = new Roll() # 注册一个房间 @register = (name, password) -> @roll.insert name, password @sockets[name] = new Cache() # 注销一个房间 @unregister = (name) -> @roll.erase name @send name, "sys", time: gettime(), data: "the room #{name} is unregistered", sck?.isjoin = false for sck in @sockets[name]._cache delete @sockets[name] # 判断一个房间存在性 @exist = (name, password) -> @roll.exist name, password # 加入一个用户 @join = (name, socket) -> @sockets[name].insert socket @send name, "sys", time: gettime(), data: "#{socket.username} joined", for key1, val1 of @hist[name] for key2, val2 of val1 if val2.type is "text" socket.emit "new message", username: socket.username, time: val2.time, ishist: true, data: "#{val2.data}".replace /[<>&"]/g, (c) -> ("<": "&lt;", ">": "&gt;", "&": "&amp;", "\"": "&quot;")[c] else if val2.type is "image" socket.emit "new image", username: socket.username, time: val2.time, ishist: true, data: "#{val2.data}", # 离开一个用户 @leave = (name, socket) -> socket.isjoin = false @sockets[name].erase socket @send name, "sys", time: gettime(), data: "#{socket.username} left", # 全体发送消息 @send = (name, ent, data) -> sck?.emit? ent, data for sck in @sockets[name]._cache # 判断房间里一个用户存在性 @existUser = (name, username) -> for sck in @sockets[name]._cache return true if sck?.username is username return false # 保存留言 @insertHist = (name, data) -> @hist[name] ?= {} @hist[name][data.username] ?= [] @hist[name][data.username].push data # 删除留言 @eraseHist = (name, username) -> delete @hist[name]?[username] # 获取在线用户 @getCuruser = (name) -> sck.username for sck in @sockets[name]._cache # 发送所有留言 @sendHist = (name, username, socket) -> for key1, val1 of @hist[name] for key2, val2 of val1 if val2.type is "text" socket.emit "new message", username: socket.username, time: val2.time, ishist: true, data: "#{val2.data}".replace /[<>&"]/g, (c) -> ("<": "&lt;", ">": "&gt;", "&": "&amp;", "\"": "&quot;")[c] else if val2.type is "image" socket.emit "new image", username: socket.username, time: val2.time, ishist: true, data: "#{val2.data}", io.on "connection", (socket) -> # 用户登录 socket.on "login", (data) -> time = gettime() if not socket.islogin if User.exist data.username, data.password User.insert data.username, socket socket.username = data.username socket.password = PI:PASSWORD:<PASSWORD>END_PI socket.islogin = true socket.emit "sys", time: time, data: "login succeeded", else socket.emit "sys", time: time, data: "login failed", else socket.emit "sys", time: time, data: "has been logined", # 用户加入房间 socket.on "join", (data) -> time = gettime() if socket.islogin if Room.exist data.roomname, data.roompassword Room.join data.roomname, socket socket.roomname = data.roomname socket.roompassword = data.roompassword socket.isjoin = true socket.emit "sys", time: time, data: "join succeeded", else socket.emit "sys", time: time, data: "join failed", else socket.emit "sys", time: time, data: "please login first", # 用户发言/图 socket.on "message", (data) -> data.username = socket.username # Room.insertHist 使用 data.time = gettime() # Room.insertHist 使用 type = data.type # 类型: text 文字 | image 图片 dt = data.data # 数据 ishist = data.ishist # 是否历史化: true 记录到留言 | false 不记录到留言 time = data.time # 时间 if socket.islogin if socket.isjoin if "#{dt}" isnt "" if type is "text" Room.send socket.roomname, "new message", username: socket.username, time: time, ishist: ishist, data: "#{dt}".replace /[<>&"]/g, (c) -> ("<": "&lt;", ">": "&gt;", "&": "&amp;", "\"": "&quot;")[c] else if type is "image" Room.send socket.roomname, "new image", username: socket.username, time: time, ishist: ishist, data: "#{dt}", Room.insertHist socket.roomname, data if ishist else socket.emit "sys", time: time, data: "please input something", else socket.emit "sys", time: time, data: "please join first", else socket.emit "sys", time: time, data: "please login first", # 用户删除留言 socket.on "eraseHist", -> time = gettime() if socket.islogin if socket.isjoin Room.eraseHist socket.roomname, socket.username socket.emit "sys", time: time, data: "hist erased succeeded", else socket.emit "sys", time: time, data: "please join first", else socket.emit "sys", time: time, data: "please login first", # 用户离开房间 socket.on "leave", -> time = gettime() Room.leave socket.roomname, socket if socket.islogin and socket.isjoin socket.emit "sys", time: time, data: "left room #{socket.roomname}", # 用户登出 socket.on "logout", -> socket.disconnect() # 用户查询信息 socket.on "info", (data) -> time = gettime() if socket.islogin if socket.isjoin switch data.data when "curuser" socket.emit "sys", time: time, data: "#{username} is online" for username in Room.getCuruser socket.roomname when "me" socket.emit "sys", time: time, data: "i am #{socket.username}" when "room" socket.emit "sys", time: time, data: "i am in #{socket.roomname}" when "leftmsg" Room.sendHist socket.roomname, socket.username, socket else socket.emit "sys", time: time, data: "command not found: /info #{data.data}" else socket.emit "sys", time: time, data: "please join first", else socket.emit "sys", time: time, data: "please login first", # 用户断线 socket.on "disconnect", -> if socket.islogin Room.leave socket.roomname, socket if socket.isjoin User.erase socket.username, socket # 初始化 readline.createInterface input: fs.createReadStream "config.txt" .on "line", (line) -> [type, name, password] = line.split(" ") if type is "user" User.register name, password else if type is "room" Room.register name, password .on "close", () -> app.use "/", express.static "#{__dirname}/TinyChat" # http.listen 8080, -> console.log "listening on port 8080" http.listen 2333, -> console.log "listening on port 2333"
[ { "context": "ers.coffee\n# lotto-ionic\n# v0.0.2\n# Copyright 2016 Andreja Tonevski, https://github.com/atonevski/lotto-ionic\n# For l", "end": 75, "score": 0.9998788833618164, "start": 59, "tag": "NAME", "value": "Andreja Tonevski" }, { "context": "pyright 2016 Andreja Tonevski, ht...
www/coffee/winners.coffee
atonevski/lotto-ionic
0
# # winners.coffee # lotto-ionic # v0.0.2 # Copyright 2016 Andreja Tonevski, https://github.com/atonevski/lotto-ionic # For license information see LICENSE in the repository # angular.module 'app.winners', [] .controller 'Winners', ($scope, $http, $ionicLoading) -> # dummy controller console.log 'Winners' .controller 'LottoWinners', ($scope, $http, $ionicLoading , $ionicPosition, $ionicScrollDelegate) -> $scope.bubbleVisible = no $scope.bubble = d3.select '#winners-list' .append 'div' .attr 'class', 'bubble bubble-left' .attr 'id', 'winners-bubble' .on('click', ()-> $scope.bubble.transition().duration 1000 .style 'opacity', 0 $scope.bubbleVisible = no ) .style 'opacity', 0 $scope.showBubble = (event, idx) -> return if $scope.bubbleVisible event.stopPropagation() $scope.bubbleVisible = yes winners = $scope.winners[idx] t = """ <div class='row row-no-padding'> <div class='col col-offset-80 text-right positive'> <small><i class='ion-close-round'></i></small> </div> </div> <h4 style='text-align: center'>#{ idx + 1 }/#{ $scope.winners.length }</h4> <dl class='dl-horizontal'> <dt>Коло:</dt> <dd>#{ winners.draw }</dd> <dt>Дата:</dt> <dd>#{ $scope.dateToDMY winners.date }</dd> <hr /> <dt>Лото:</dt><dd></dd> <hr /> <dt>Уплата:</dt> <dd>#{ $scope.thou_sep winners.lsales }</dd> """ t += """ <dt>Добитници:</dt> <dd> <span style='color: red;'> <strong>#{ winners.lx7 + 'x7' }</strong> </span> <span style='color: orange'> <strong> #{ if winners.lx6p > 0 then winners.lx6p + 'x6<sup><strong>+</strong></sup>' else '' } </strong> </span> #{ if winners.lx6 > 0 then winners.lx6 + 'x6' else '' } #{ $scope.thou_sep winners.lx5 + 'x5' } #{ $scope.thou_sep winners.lx4 + 'x4' } </dd> """ t += """ <dt>Доб. комбинација:</dt> <dd> #{ winners.lwcol[0..6].sort((a, b)-> +a - +b).join(' ') } <span style='color: steelblue'>#{ winners.lwcol[7] }</span> <br /> [ #{ winners.lwcol[0..6].join(' ') } <span style='color: steelblue'>#{ winners.lwcol[7] }</span> ] </dd> """ t += """ <hr /> <dt>Џокер:</dt><dd></dd> <hr /> <dt>Уплата:</dt> <dd>#{ $scope.thou_sep winners.jsales }</dd> """ t += """ <dt>Добитници:</dt> <dd> <span style='color: red'> <strong>#{ if winners.jx6 > 0 then winners.jx6 + 'x6' else '' }</strong> </span> <span style='color: orange'> <strong>#{ if winners.jx5 > 0 then winners.jx5 + 'x5' else '' }</strong> </span> #{ if winners.jx4 > 0 then winners.jx4 + 'x4' else '' } #{ if winners.jx3 > 0 then $scope.thou_sep winners.jx3 + 'x3' else '' } #{ if winners.jx2 > 0 then $scope.thou_sep winners.jx2 + 'x2' else '' } #{ if winners.jx1 > 0 then $scope.thou_sep winners.jx1 + 'x1' else '' } </dd> """ t += """ <dt>Доб. комбинација:</dt> <dd> #{ winners.jwcol.split('').join(' ') } </dd> """ t += "</dl>" id = "\#winners-#{ winners.year }-#{ winners.draw }" el = angular.element document.querySelector id offset = $ionicPosition.offset el new_top = offset.top + $ionicScrollDelegate.getScrollPosition().top $scope.bubble.html t .style 'left', (event.pageX + 10) + 'px' .style 'top', (new_top - 58) + 'px' .style 'opacity', 1 query = """ SELECT * WHERE D > 0 ORDER BY B """ $ionicLoading.show() $http.get $scope.qurl(query) .success (data, status) -> res = $scope.to_json data $scope.winners = res.table.rows.map (r) -> a = $scope.eval_row r { year: a[1].getFullYear() draw: a[0] date: a[1] lsales: a[2] lx7: a[3] lx6p: a[4] lx6: a[5] lx5: a[6] lx4: a[7] lwcol: a[15..22] jsales: a[8] jx6: a[9] jx5: a[10] jx4: a[11] jx3: a[12] jx2: a[13] jx1: a[14] jwcol: a[23] } $ionicLoading.hide() .error (err) -> $ionicLoading.show({ template: "Не може да се вчитаат лото добитниците. Пробај подоцна." duration: 3000 }) .controller 'JokerWinners', ($scope, $http, $ionicLoading , $ionicPosition, $ionicScrollDelegate) -> $scope.bubbleVisible = no $scope.bubble = d3.select '#winners-list' .append 'div' .attr 'class', 'bubble bubble-left' .attr 'id', 'winners-bubble' .on('click', ()-> $scope.bubble.transition().duration 1000 .style 'opacity', 0 $scope.bubbleVisible = no ) .style 'opacity', 0 $scope.showBubble = (event, idx) -> return if $scope.bubbleVisible event.stopPropagation() $scope.bubbleVisible = yes winners = $scope.winners[idx] t = """ <div class='row row-no-padding'> <div class='col col-offset-80 text-right positive'> <small><i class='ion-close-round'></i></small> </div> </div> <h4 style='text-align: center'>#{ idx + 1 }/#{ $scope.winners.length }</h4> <dl class='dl-horizontal'> <dt>Коло:</dt> <dd>#{ winners.draw }</dd> <dt>Дата:</dt> <dd>#{ $scope.dateToDMY winners.date }</dd> <hr /> <dt>Лото:</dt><dd></dd> <hr /> <dt>Уплата:</dt> <dd>#{ $scope.thou_sep winners.lsales }</dd> """ t += """ <dt>Добитници:</dt> <dd> <span style='color: red;'> <strong> #{ if winners.lx7 then winners.lx7 + 'x7' else '' } </strong> </span> <span style='color: orange'> <strong> #{ if winners.lx6p > 0 then winners.lx6p + 'x6<sup><strong>+</strong></sup>' else '' } </strong> </span> #{ if winners.lx6 > 0 then winners.lx6 + 'x6' else '' } #{ $scope.thou_sep winners.lx5 + 'x5' } #{ $scope.thou_sep winners.lx4 + 'x4' } </dd> """ t += """ <dt>Доб. комбинација:</dt> <dd> #{ winners.lwcol[0..6].sort((a, b)-> +a - +b).join(' ') } <span style='color: steelblue'>#{ winners.lwcol[7] }</span> <br /> [ #{ winners.lwcol[0..6].join(' ') } <span style='color: steelblue'>#{ winners.lwcol[7] }</span> ] </dd> """ t += """ <hr /> <dt>Џокер:</dt><dd></dd> <hr /> <dt>Уплата:</dt> <dd>#{ $scope.thou_sep winners.jsales }</dd> """ t += """ <dt>Добитници:</dt> <dd> <span style='color: red'> <strong>#{ if winners.jx6 > 0 then winners.jx6 + 'x6' else '' }</strong> </span> <span style='color: orange'> <strong>#{ if winners.jx5 > 0 then winners.jx5 + 'x5' else '' }</strong> </span> #{ if winners.jx4 > 0 then winners.jx4 + 'x4' else '' } #{ if winners.jx3 > 0 then $scope.thou_sep winners.jx3 + 'x3' else '' } #{ if winners.jx2 > 0 then $scope.thou_sep winners.jx2 + 'x2' else '' } #{ if winners.jx1 > 0 then $scope.thou_sep winners.jx1 + 'x1' else '' } </dd> """ t += """ <dt>Доб. комбинација:</dt> <dd> #{ winners.jwcol.split('').join(' ') } </dd> """ t += "</dl>" id = "\#winners-#{ winners.year }-#{ winners.draw }" el = angular.element document.querySelector id offset = $ionicPosition.offset el new_top = offset.top + $ionicScrollDelegate.getScrollPosition().top $scope.bubble.html t .style 'left', (event.pageX + 10) + 'px' .style 'top', (new_top - 58) + 'px' .style 'opacity', 1 query = """ SELECT * WHERE J > 0 ORDER BY B """ $ionicLoading.show() $http.get $scope.qurl(query) .success (data, status) -> res = $scope.to_json data $scope.winners = res.table.rows.map (r) -> a = $scope.eval_row r { year: a[1].getFullYear() draw: a[0] date: a[1] lsales: a[2] lx7: a[3] lx6p: a[4] lx6: a[5] lx5: a[6] lx4: a[7] lwcol: a[15..22] jsales: a[8] jx6: a[9] jx5: a[10] jx4: a[11] jx3: a[12] jx2: a[13] jx1: a[14] jwcol: a[23] } $ionicLoading.hide() .error (err) -> $ionicLoading.show({ template: "Не може да се вчитаат џокер добитниците. Пробај подоцна." duration: 3000 })
222297
# # winners.coffee # lotto-ionic # v0.0.2 # Copyright 2016 <NAME>, https://github.com/atonevski/lotto-ionic # For license information see LICENSE in the repository # angular.module 'app.winners', [] .controller 'Winners', ($scope, $http, $ionicLoading) -> # dummy controller console.log 'Winners' .controller 'LottoWinners', ($scope, $http, $ionicLoading , $ionicPosition, $ionicScrollDelegate) -> $scope.bubbleVisible = no $scope.bubble = d3.select '#winners-list' .append 'div' .attr 'class', 'bubble bubble-left' .attr 'id', 'winners-bubble' .on('click', ()-> $scope.bubble.transition().duration 1000 .style 'opacity', 0 $scope.bubbleVisible = no ) .style 'opacity', 0 $scope.showBubble = (event, idx) -> return if $scope.bubbleVisible event.stopPropagation() $scope.bubbleVisible = yes winners = $scope.winners[idx] t = """ <div class='row row-no-padding'> <div class='col col-offset-80 text-right positive'> <small><i class='ion-close-round'></i></small> </div> </div> <h4 style='text-align: center'>#{ idx + 1 }/#{ $scope.winners.length }</h4> <dl class='dl-horizontal'> <dt>Коло:</dt> <dd>#{ winners.draw }</dd> <dt>Дата:</dt> <dd>#{ $scope.dateToDMY winners.date }</dd> <hr /> <dt>Лото:</dt><dd></dd> <hr /> <dt>Уплата:</dt> <dd>#{ $scope.thou_sep winners.lsales }</dd> """ t += """ <dt>Добитници:</dt> <dd> <span style='color: red;'> <strong>#{ winners.lx7 + 'x7' }</strong> </span> <span style='color: orange'> <strong> #{ if winners.lx6p > 0 then winners.lx6p + 'x6<sup><strong>+</strong></sup>' else '' } </strong> </span> #{ if winners.lx6 > 0 then winners.lx6 + 'x6' else '' } #{ $scope.thou_sep winners.lx5 + 'x5' } #{ $scope.thou_sep winners.lx4 + 'x4' } </dd> """ t += """ <dt>Доб. комбинација:</dt> <dd> #{ winners.lwcol[0..6].sort((a, b)-> +a - +b).join(' ') } <span style='color: steelblue'>#{ winners.lwcol[7] }</span> <br /> [ #{ winners.lwcol[0..6].join(' ') } <span style='color: steelblue'>#{ winners.lwcol[7] }</span> ] </dd> """ t += """ <hr /> <dt>Џокер:</dt><dd></dd> <hr /> <dt>Уплата:</dt> <dd>#{ $scope.thou_sep winners.jsales }</dd> """ t += """ <dt>Добитници:</dt> <dd> <span style='color: red'> <strong>#{ if winners.jx6 > 0 then winners.jx6 + 'x6' else '' }</strong> </span> <span style='color: orange'> <strong>#{ if winners.jx5 > 0 then winners.jx5 + 'x5' else '' }</strong> </span> #{ if winners.jx4 > 0 then winners.jx4 + 'x4' else '' } #{ if winners.jx3 > 0 then $scope.thou_sep winners.jx3 + 'x3' else '' } #{ if winners.jx2 > 0 then $scope.thou_sep winners.jx2 + 'x2' else '' } #{ if winners.jx1 > 0 then $scope.thou_sep winners.jx1 + 'x1' else '' } </dd> """ t += """ <dt><NAME>:</dt> <dd> #{ winners.jwcol.split('').join(' ') } </dd> """ t += "</dl>" id = "\#winners-#{ winners.year }-#{ winners.draw }" el = angular.element document.querySelector id offset = $ionicPosition.offset el new_top = offset.top + $ionicScrollDelegate.getScrollPosition().top $scope.bubble.html t .style 'left', (event.pageX + 10) + 'px' .style 'top', (new_top - 58) + 'px' .style 'opacity', 1 query = """ SELECT * WHERE D > 0 ORDER BY B """ $ionicLoading.show() $http.get $scope.qurl(query) .success (data, status) -> res = $scope.to_json data $scope.winners = res.table.rows.map (r) -> a = $scope.eval_row r { year: a[1].getFullYear() draw: a[0] date: a[1] lsales: a[2] lx7: a[3] lx6p: a[4] lx6: a[5] lx5: a[6] lx4: a[7] lwcol: a[15..22] jsales: a[8] jx6: a[9] jx5: a[10] jx4: a[11] jx3: a[12] jx2: a[13] jx1: a[14] jwcol: a[23] } $ionicLoading.hide() .error (err) -> $ionicLoading.show({ template: "Не може да се вчитаат лото добитниците. Пробај подоцна." duration: 3000 }) .controller 'JokerWinners', ($scope, $http, $ionicLoading , $ionicPosition, $ionicScrollDelegate) -> $scope.bubbleVisible = no $scope.bubble = d3.select '#winners-list' .append 'div' .attr 'class', 'bubble bubble-left' .attr 'id', 'winners-bubble' .on('click', ()-> $scope.bubble.transition().duration 1000 .style 'opacity', 0 $scope.bubbleVisible = no ) .style 'opacity', 0 $scope.showBubble = (event, idx) -> return if $scope.bubbleVisible event.stopPropagation() $scope.bubbleVisible = yes winners = $scope.winners[idx] t = """ <div class='row row-no-padding'> <div class='col col-offset-80 text-right positive'> <small><i class='ion-close-round'></i></small> </div> </div> <h4 style='text-align: center'>#{ idx + 1 }/#{ $scope.winners.length }</h4> <dl class='dl-horizontal'> <dt>Коло:</dt> <dd>#{ winners.draw }</dd> <dt>Дата:</dt> <dd>#{ $scope.dateToDMY winners.date }</dd> <hr /> <dt>Лото:</dt><dd></dd> <hr /> <dt>Уплата:</dt> <dd>#{ $scope.thou_sep winners.lsales }</dd> """ t += """ <dt>Добитници:</dt> <dd> <span style='color: red;'> <strong> #{ if winners.lx7 then winners.lx7 + 'x7' else '' } </strong> </span> <span style='color: orange'> <strong> #{ if winners.lx6p > 0 then winners.lx6p + 'x6<sup><strong>+</strong></sup>' else '' } </strong> </span> #{ if winners.lx6 > 0 then winners.lx6 + 'x6' else '' } #{ $scope.thou_sep winners.lx5 + 'x5' } #{ $scope.thou_sep winners.lx4 + 'x4' } </dd> """ t += """ <dt>Доб. комбинација:</dt> <dd> #{ winners.lwcol[0..6].sort((a, b)-> +a - +b).join(' ') } <span style='color: steelblue'>#{ winners.lwcol[7] }</span> <br /> [ #{ winners.lwcol[0..6].join(' ') } <span style='color: steelblue'>#{ winners.lwcol[7] }</span> ] </dd> """ t += """ <hr /> <dt>Џокер:</dt><dd></dd> <hr /> <dt>Уплата:</dt> <dd>#{ $scope.thou_sep winners.jsales }</dd> """ t += """ <dt>Добитници:</dt> <dd> <span style='color: red'> <strong>#{ if winners.jx6 > 0 then winners.jx6 + 'x6' else '' }</strong> </span> <span style='color: orange'> <strong>#{ if winners.jx5 > 0 then winners.jx5 + 'x5' else '' }</strong> </span> #{ if winners.jx4 > 0 then winners.jx4 + 'x4' else '' } #{ if winners.jx3 > 0 then $scope.thou_sep winners.jx3 + 'x3' else '' } #{ if winners.jx2 > 0 then $scope.thou_sep winners.jx2 + 'x2' else '' } #{ if winners.jx1 > 0 then $scope.thou_sep winners.jx1 + 'x1' else '' } </dd> """ t += """ <dt>Доб. комбинација:</dt> <dd> #{ winners.jwcol.split('').join(' ') } </dd> """ t += "</dl>" id = "\#winners-#{ winners.year }-#{ winners.draw }" el = angular.element document.querySelector id offset = $ionicPosition.offset el new_top = offset.top + $ionicScrollDelegate.getScrollPosition().top $scope.bubble.html t .style 'left', (event.pageX + 10) + 'px' .style 'top', (new_top - 58) + 'px' .style 'opacity', 1 query = """ SELECT * WHERE J > 0 ORDER BY B """ $ionicLoading.show() $http.get $scope.qurl(query) .success (data, status) -> res = $scope.to_json data $scope.winners = res.table.rows.map (r) -> a = $scope.eval_row r { year: a[1].getFullYear() draw: a[0] date: a[1] lsales: a[2] lx7: a[3] lx6p: a[4] lx6: a[5] lx5: a[6] lx4: a[7] lwcol: a[15..22] jsales: a[8] jx6: a[9] jx5: a[10] jx4: a[11] jx3: a[12] jx2: a[13] jx1: a[14] jwcol: a[23] } $ionicLoading.hide() .error (err) -> $ionicLoading.show({ template: "Не може да се вчитаат џокер добитниците. Пробај подоцна." duration: 3000 })
true
# # winners.coffee # lotto-ionic # v0.0.2 # Copyright 2016 PI:NAME:<NAME>END_PI, https://github.com/atonevski/lotto-ionic # For license information see LICENSE in the repository # angular.module 'app.winners', [] .controller 'Winners', ($scope, $http, $ionicLoading) -> # dummy controller console.log 'Winners' .controller 'LottoWinners', ($scope, $http, $ionicLoading , $ionicPosition, $ionicScrollDelegate) -> $scope.bubbleVisible = no $scope.bubble = d3.select '#winners-list' .append 'div' .attr 'class', 'bubble bubble-left' .attr 'id', 'winners-bubble' .on('click', ()-> $scope.bubble.transition().duration 1000 .style 'opacity', 0 $scope.bubbleVisible = no ) .style 'opacity', 0 $scope.showBubble = (event, idx) -> return if $scope.bubbleVisible event.stopPropagation() $scope.bubbleVisible = yes winners = $scope.winners[idx] t = """ <div class='row row-no-padding'> <div class='col col-offset-80 text-right positive'> <small><i class='ion-close-round'></i></small> </div> </div> <h4 style='text-align: center'>#{ idx + 1 }/#{ $scope.winners.length }</h4> <dl class='dl-horizontal'> <dt>Коло:</dt> <dd>#{ winners.draw }</dd> <dt>Дата:</dt> <dd>#{ $scope.dateToDMY winners.date }</dd> <hr /> <dt>Лото:</dt><dd></dd> <hr /> <dt>Уплата:</dt> <dd>#{ $scope.thou_sep winners.lsales }</dd> """ t += """ <dt>Добитници:</dt> <dd> <span style='color: red;'> <strong>#{ winners.lx7 + 'x7' }</strong> </span> <span style='color: orange'> <strong> #{ if winners.lx6p > 0 then winners.lx6p + 'x6<sup><strong>+</strong></sup>' else '' } </strong> </span> #{ if winners.lx6 > 0 then winners.lx6 + 'x6' else '' } #{ $scope.thou_sep winners.lx5 + 'x5' } #{ $scope.thou_sep winners.lx4 + 'x4' } </dd> """ t += """ <dt>Доб. комбинација:</dt> <dd> #{ winners.lwcol[0..6].sort((a, b)-> +a - +b).join(' ') } <span style='color: steelblue'>#{ winners.lwcol[7] }</span> <br /> [ #{ winners.lwcol[0..6].join(' ') } <span style='color: steelblue'>#{ winners.lwcol[7] }</span> ] </dd> """ t += """ <hr /> <dt>Џокер:</dt><dd></dd> <hr /> <dt>Уплата:</dt> <dd>#{ $scope.thou_sep winners.jsales }</dd> """ t += """ <dt>Добитници:</dt> <dd> <span style='color: red'> <strong>#{ if winners.jx6 > 0 then winners.jx6 + 'x6' else '' }</strong> </span> <span style='color: orange'> <strong>#{ if winners.jx5 > 0 then winners.jx5 + 'x5' else '' }</strong> </span> #{ if winners.jx4 > 0 then winners.jx4 + 'x4' else '' } #{ if winners.jx3 > 0 then $scope.thou_sep winners.jx3 + 'x3' else '' } #{ if winners.jx2 > 0 then $scope.thou_sep winners.jx2 + 'x2' else '' } #{ if winners.jx1 > 0 then $scope.thou_sep winners.jx1 + 'x1' else '' } </dd> """ t += """ <dt>PI:NAME:<NAME>END_PI:</dt> <dd> #{ winners.jwcol.split('').join(' ') } </dd> """ t += "</dl>" id = "\#winners-#{ winners.year }-#{ winners.draw }" el = angular.element document.querySelector id offset = $ionicPosition.offset el new_top = offset.top + $ionicScrollDelegate.getScrollPosition().top $scope.bubble.html t .style 'left', (event.pageX + 10) + 'px' .style 'top', (new_top - 58) + 'px' .style 'opacity', 1 query = """ SELECT * WHERE D > 0 ORDER BY B """ $ionicLoading.show() $http.get $scope.qurl(query) .success (data, status) -> res = $scope.to_json data $scope.winners = res.table.rows.map (r) -> a = $scope.eval_row r { year: a[1].getFullYear() draw: a[0] date: a[1] lsales: a[2] lx7: a[3] lx6p: a[4] lx6: a[5] lx5: a[6] lx4: a[7] lwcol: a[15..22] jsales: a[8] jx6: a[9] jx5: a[10] jx4: a[11] jx3: a[12] jx2: a[13] jx1: a[14] jwcol: a[23] } $ionicLoading.hide() .error (err) -> $ionicLoading.show({ template: "Не може да се вчитаат лото добитниците. Пробај подоцна." duration: 3000 }) .controller 'JokerWinners', ($scope, $http, $ionicLoading , $ionicPosition, $ionicScrollDelegate) -> $scope.bubbleVisible = no $scope.bubble = d3.select '#winners-list' .append 'div' .attr 'class', 'bubble bubble-left' .attr 'id', 'winners-bubble' .on('click', ()-> $scope.bubble.transition().duration 1000 .style 'opacity', 0 $scope.bubbleVisible = no ) .style 'opacity', 0 $scope.showBubble = (event, idx) -> return if $scope.bubbleVisible event.stopPropagation() $scope.bubbleVisible = yes winners = $scope.winners[idx] t = """ <div class='row row-no-padding'> <div class='col col-offset-80 text-right positive'> <small><i class='ion-close-round'></i></small> </div> </div> <h4 style='text-align: center'>#{ idx + 1 }/#{ $scope.winners.length }</h4> <dl class='dl-horizontal'> <dt>Коло:</dt> <dd>#{ winners.draw }</dd> <dt>Дата:</dt> <dd>#{ $scope.dateToDMY winners.date }</dd> <hr /> <dt>Лото:</dt><dd></dd> <hr /> <dt>Уплата:</dt> <dd>#{ $scope.thou_sep winners.lsales }</dd> """ t += """ <dt>Добитници:</dt> <dd> <span style='color: red;'> <strong> #{ if winners.lx7 then winners.lx7 + 'x7' else '' } </strong> </span> <span style='color: orange'> <strong> #{ if winners.lx6p > 0 then winners.lx6p + 'x6<sup><strong>+</strong></sup>' else '' } </strong> </span> #{ if winners.lx6 > 0 then winners.lx6 + 'x6' else '' } #{ $scope.thou_sep winners.lx5 + 'x5' } #{ $scope.thou_sep winners.lx4 + 'x4' } </dd> """ t += """ <dt>Доб. комбинација:</dt> <dd> #{ winners.lwcol[0..6].sort((a, b)-> +a - +b).join(' ') } <span style='color: steelblue'>#{ winners.lwcol[7] }</span> <br /> [ #{ winners.lwcol[0..6].join(' ') } <span style='color: steelblue'>#{ winners.lwcol[7] }</span> ] </dd> """ t += """ <hr /> <dt>Џокер:</dt><dd></dd> <hr /> <dt>Уплата:</dt> <dd>#{ $scope.thou_sep winners.jsales }</dd> """ t += """ <dt>Добитници:</dt> <dd> <span style='color: red'> <strong>#{ if winners.jx6 > 0 then winners.jx6 + 'x6' else '' }</strong> </span> <span style='color: orange'> <strong>#{ if winners.jx5 > 0 then winners.jx5 + 'x5' else '' }</strong> </span> #{ if winners.jx4 > 0 then winners.jx4 + 'x4' else '' } #{ if winners.jx3 > 0 then $scope.thou_sep winners.jx3 + 'x3' else '' } #{ if winners.jx2 > 0 then $scope.thou_sep winners.jx2 + 'x2' else '' } #{ if winners.jx1 > 0 then $scope.thou_sep winners.jx1 + 'x1' else '' } </dd> """ t += """ <dt>Доб. комбинација:</dt> <dd> #{ winners.jwcol.split('').join(' ') } </dd> """ t += "</dl>" id = "\#winners-#{ winners.year }-#{ winners.draw }" el = angular.element document.querySelector id offset = $ionicPosition.offset el new_top = offset.top + $ionicScrollDelegate.getScrollPosition().top $scope.bubble.html t .style 'left', (event.pageX + 10) + 'px' .style 'top', (new_top - 58) + 'px' .style 'opacity', 1 query = """ SELECT * WHERE J > 0 ORDER BY B """ $ionicLoading.show() $http.get $scope.qurl(query) .success (data, status) -> res = $scope.to_json data $scope.winners = res.table.rows.map (r) -> a = $scope.eval_row r { year: a[1].getFullYear() draw: a[0] date: a[1] lsales: a[2] lx7: a[3] lx6p: a[4] lx6: a[5] lx5: a[6] lx4: a[7] lwcol: a[15..22] jsales: a[8] jx6: a[9] jx5: a[10] jx4: a[11] jx3: a[12] jx2: a[13] jx1: a[14] jwcol: a[23] } $ionicLoading.hide() .error (err) -> $ionicLoading.show({ template: "Не може да се вчитаат џокер добитниците. Пробај подоцна." duration: 3000 })
[ { "context": "\ttext: '5/8. Drama about midwives in 1960s London. Lucille must win the trust of a mother who is terrified o", "end": 11569, "score": 0.9720962047576904, "start": 11562, "tag": "NAME", "value": "Lucille" }, { "context": "rust of a mother who is terrified of giving birt...
prototypes/closed-pop-one-line.framer/app.coffee
Skinny-Malinky/Skinny-Malinky.github.io
0
#Utils & Config data = JSON.parse Utils.domLoadDataSync 'data/programmeData.json' hyperSpeed = false youviewBlue = '#00a6ff' youviewBlue2 = '#0F5391' youviewBlue3 = 'rgba(0, 51, 102, 0.8);' youviewGrey1 = '#b6b9bf' youviewGrey2 = '#83858a' darkGrey3 = '#505359' black = '#000' white = '#ebebeb' veryDarkGrey4 = '#171717' veryDarkGrey5 = '#0D0D0D' minute = 9.6 document.body.style.cursor = "auto" #Struan Utils convertToPixel = (time) -> return time*minute getDate = (modifier) -> date = new Date() dateInt = date.getUTCDate() if (dateInt + modifier) > 31 or (dateInt + modifier) <= 0 dateInt = (dateInt + modifier)%31 else dateInt+=modifier return dateInt getTime = (modifier) -> date = new Date() time = date.getHours() modifier = modifier + 48*100 if modifier%2#Odd time += ((modifier-1)/2) time = time%24 newTime = String(time) + ":00" else#Even time += (modifier/2 - 1) time = time%24 newTime = String(time) + ":30" return newTime getDay = (modifier) -> if modifier == 0 day = "Today" fontColor = white fontOpacity = 1 fontOpacityDate = 1 return day else dayString = "" today = new Date() dayInt = today.getUTCDay() dayInt += modifier if dayInt < 0 dayInt = (dayInt+7)%7 if dayInt > 6 dayInt%=7 switch dayInt when 0 then dayString = "Sunday" when 1 then dayString = "Monday" when 2 then dayString = "Tuesday" when 3 then dayString = "Wednesday" when 4 then dayString = "Thursday" when 5 then dayString = "Friday" when 6 then dayString = "Saturday" return dayString.substring(0,3) rowEvents = [] eventDivider = [] # eventTextObject = [] for i in [0..data.programmeData.channels.length] rowEvents.push( i ) eventDivider.push( i ) for i in [0..rowEvents.length] rowEvents[i] = [] eventDivider[i] = [] eventTitle = [0,1,2,3,4,5,6] channelIdent = [] dateTrack = [] rowDivider = [] filterSelection = 0 filterSelected = 0 Framer.Defaults.Animation = time: 0.3 channels = [] filterLayer = [] hX = 1 hY = 0 virtualCursor = 300 maxExpansion = 45 tunedChannel = 0 filter = ['All Channels','HD','Entertainment',"Children's",'News','Films','Factual & Lifestyle','Radio','Shopping & Travel','Adult & Dating'] tuned = ['http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4'] Utils.interval 1, -> Framer.Device.setDeviceScale( (Canvas.width/Screen.width) * 1, false ) cellHeight = 60 cellLeftPadding = 8 #Static Layers tvShow = new VideoLayer x:0 width:1280 height:720 backgroundColor: black video:tuned[tunedChannel] index:-1 tvShow.center() tvShow.player.autoplay = true tvShow.player.loop = true tvShow.player.muted = true background = new Layer width:1280 height:720 x:0 backgroundColor:null clip:true background.center() eventParent = new Layer parent:background y:260 width:1280 height:460 index:1 backgroundColor: null clip:true serviceList = new Layer parent:eventParent x:64 y:2 width:224 height:460 index:4 backgroundColor:'rgba(0, 0, 0, 0.5)' divider = new Layer parent:eventParent width:1280 height:2 y:0 index:-1 backgroundColor:veryDarkGrey4 header = new Layer parent:background x:0 width:1280 height:226 dateTrackHeader = new Layer parent:header width:1280 height:162 backgroundColor: 'rgba(0, 48, 109, 0.50)' opacity: 0.85 dateTrackContainer = new Layer parent:background x:40, y:96, index:10 height:32 opacity:1 backgroundColor: "transparent" dayTrack = [] fillDateTrack = () -> dayModifier = -7 for i in [0...15] fontColor = youviewGrey1 fontOpacity = 0.7 fontOpacityDate = 0.4 day = getDay(dayModifier) dateContainer = new Layer parent:dateTrackContainer width:80, height:48 x:i*80 backgroundColor: 'transparent' newDay = new TextLayer name:day+dayModifier parent:dateContainer width:80, height:32 text:day, textAlign: "center", textTransform: "uppercase", fontFamily: "GillSans-Bold", fontSize:16, letterSpacing: 1.92, color:fontColor opacity: fontOpacity dayTrack.push(newDay) date = getDate(dayModifier) newDate = new TextLayer parent:dateContainer y:24, width:80, height:16 text:date, textAlign: "center", textTransform: "uppercase", fontFamily: "GillSans-Bold, GillSans-Bold", fontSize:16, letterSpacing: 1.92, color:white opacity:fontOpacityDate dayModifier++ dateTrack.push(dateContainer) expansionTimeout = 0 nowLineTimeout = 0 legendTimeout = 0 unselectedSecondLineOpacity = 0.3 separatorOpacity = 0.2 #Event Handling fastScroll = 0 captureKeys = () -> document.addEventListener 'keydown', (event) -> keyCode = event.which eventHandler(keyCode) expansionTimeout = 0 dumbVariable = 0 eventHandler = Utils.throttle 0.2, (keyCode) -> thisY = hY thisX = hX if fastScroll == 4 and thisY > 0 engageHyperSpeed(keyCode) else if hyperSpeed == false switch keyCode when 13 if thisY >= 0 tune() else if thisY == -1 selectFilter() when 39 #Right legendTimeout = 0 hideLegend.start() goRight(thisX, thisY) fastScroll++ when 37 #Left legendTimeout = 0 hideLegend.start() goLeft(thisX, thisY) fastScroll++ when 40 #Down legendTimeout = 0 hideLegend.start() goDown(thisX, thisY) when 38 #Up legendTimeout = 0 hideLegend.start() goUp(thisX, thisY) when 71 if thisY >= 0 openGuide() when 82 #R record(thisX, thisY) document.addEventListener 'keyup', (event) -> keyCode = event.which closeHandler(keyCode) closeHandler = (keyCode) -> y = hY x = hX switch keyCode when 39, 37 fastScroll = 0 hyperSpeed = false disengageHyperSpeed(x,y) engageHyperSpeed = (keyCode) -> if trackChanged == true hideEverything() scroll(keyCode) timeElapsed = 1 #Scroll Stuff timeTrack = new Layer height:34, width:1280 y:225 index:6 opacity:0.95 borderColor: 'transparent' backgroundColor: 'rgba(4, 44, 94, 0.4)' timeContainer = new Layer parent:timeTrack backgroundColor: 'transparent' timeContainer.states = hide: opacity:0 show: opacity:0.95 for i in [1..4] times = new TextLayer name:'time' + i parent:timeContainer x:convertToPixel(30)*(i), y:8, index:4 height:18, width:55 text:getTime(i) textAlign:'center' fontSize:16, fontFamily:'GillSans-Bold, GillSans-Bold' color:white #Scrolling Time dateModifier = 0 dayModifier = 0 trackChanged = false selectedDate = 7 scrollingDay = new TextLayer midX:Screen.midX - 27, y:89 text:'Today', textTransform:'uppercase', fontFamily:"GillSans-Bold", color:white, fontSize:24, textAlign:'center' opacity:0 scrollingDate = new TextLayer y: 124, midX:Screen.midX - 27, opacity: 0 text:getDate(0), textTransform:'uppercase', fontFamily:'GillSans-Light', color:white, fontSize:20, textAlign:'center' changeDay = (change) -> if selectedDate <= 13 and selectedDate >= 0 dateTrack[selectedDate].children[1].opacity = 0.4 dateTrack[selectedDate].children[0].opacity = 0.7 selectedDate += change dateTrack[selectedDate].children[1].opacity = 1 dateTrack[selectedDate].children[0].opacity = 1 newDay = parseInt(scrollingDate.text) scrollingDate.text = newDay + change scrollingDay.text = getDay(selectedDate) scroll = (keyCode) -> hyperSpeed = true if trackChanged == false activeTimeTrack() #If right if keyCode == 39 if timeContainer.children[ 1 ].y == -31 timeElapsed+=1 if (getTime( timeElapsed+1 ) == '0:00') changeDay(1) #If left else if keyCode == 37 if timeContainer.children[ 1 ].y == -31 timeElapsed-- if(getTime( timeElapsed+1 ) == '0:00') dayModifier-- changeDay(-1) forEachTime = -1 if timeElapsed % 2 for k in [ 0...timeContainer.children.length ] timeContainer.children[ k ].text = getTime( forEachTime + timeElapsed ) forEachTime++ hideTime = new Animation layer:timeContainer properties: opacity:0 delay:0.1 showTime = hideTime.reverse() activeTimeTrack = () -> hideTime.start() trackChanged = true disengageHyperSpeed = Utils.throttle 1, (x,y) -> hyperSpeed = false scrollingDay.animate opacity:0 options: time:0.5 scrollingDate.animate opacity:0 # scrollingDate.onAnimationStop -> # timeContainer.stateSwitch('hide') # timeTrackDefaults() # showEverything(x,y) # scrollingDate.removeAllListeners trackChanged = false timeTrackDefaults = () -> for i in [ 0..3 ] timeContainer.children[ i ].y = 8 timeContainer.children[ i ].fontSize = 16 timeContainer.children[ i ].color = youviewGrey2 timeContainer.children[ 1 ].opacity = 0.5 timeTrack.opacity = 0.95 timeContainer.stateSwitch('show') hideEverything = Utils.throttle 1, () -> nowline.opacity = 0 for i in [0...channels.length] for j in [0...channels[i].children.length] channels[i].children[j].animate opacity:0 options: time:0.1*i dateTrackContainer.animate opacity: 0 filterContainer.animate opacity: 0 showEverything = Utils.throttle 1, (x,y) -> nowline.opacity = 1 for i in [channels.length-1..0] for j in [channels[i].children.length-1..0] channels[i].children[j].animate opacity:1 options: time:0.1*j styleHighlight(x,y) filterDividerBottom.stateSwitch('show') dateTrackContainer.animate opacity: 1 filterContainer.animate opacity:1 #Fluff openGuide = () -> if background.opacity == 0 background.opacity = 1 else background.opacity = 1 tune = () -> if background.opacity == 1 tunedChannel++ if tunedChannel == tuned.length tunedChannel = 0 tvShow.video = tuned[tunedChannel] background.opacity = 0 #Styling & Expansion styleHighlight = (x,y,xMod,yMod) -> if yMod == NaN then yMod = 0 if xMod == NaN then xMod = 0 popOutHighlight.shadow2.color = 'rgba(0,0,0,0)' channels[selectedRow].backgroundColor = youviewBlue3 channels[selectedRow].opacity = 1 channelIdent[y].opacity = 1 rowEvents[y][x].turnOn() rowEvents[y][x].showOn() eventDivider[y][x].opacity = 0 eventDivider[y][x+1].opacity = 0 if eventDivider[y]?[x+1]? if xMod == 1 or xMod == -1 changeVirtualCursor(x,y) for i in [0...channelIdent.length] for j in [0...channels[i].children.length] channels[i].children[j].turnOff() if rowEvents[y][x].x > serviceList.maxX popOutHighlight.x = rowEvents[y][x].x else popOutHighlight.x = serviceList.maxX popOutHighlight.y = rowEvents[y][x].screenFrame.y popOutHighlight.width = rowEvents[y][x].width popOutHighlight.height = 60 popOutHighlight.borderRadius = 0 highlightTitle.x = 8 highlightTitle.y = 20 synopsis.visible = false highlightStartEnd.visible = false highlightTitle.text = rowEvents[y][x].children[0].text highlightTitle.width = rowEvents[y][x].width - popOutPadding synopsis.width = rowEvents[y][x].width - popOutPadding highlightStartEnd.width = rowEvents[y][x].width - popOutPadding hY = y hX = x popOutPadding = 16 popOutHighlight = new Layer backgroundColor: '#0F5391' height: 60 #94 shadow2: y: 5 blur: 20 color: 'rgba(0,0,0,0)' highlightTitle = new TextLayer parent: popOutHighlight fontFamily: "GillSans" fontSize: 20 truncate: true color: '#ebebeb' x: 8, y: 20 # 34 height: 26 highlightStartEnd = new TextLayer parent: popOutHighlight fontFamily: "GillSans-Bold" fontSize: 16 truncate: true color: youviewGrey1 x: popOutPadding, y: 10 textTransform: 'uppercase' height: 26 text: '6:00 – 9:00PM' visible: false synopsis = new TextLayer parent: popOutHighlight fontFamily: "GillSans" color: youviewGrey1 truncate: true fontSize: 18 visible: false y: 62, x: popOutPadding height: 26 text: '5/8. Drama about midwives in 1960s London. Lucille must win the trust of a mother who is terrified of giving birth. Nurse Crane and Dr Turner encounter a suspected smallpox case. Also in HD.' # Expansion Rules expansionCleverness = (x,y) -> popOutHighlight.borderRadius = 1 popOutHighlight.y -= 14 popOutHighlight.x -= 8 popOutHighlight.height = 94 popOutHighlight.shadow2.y = 5 popOutHighlight.shadow2.blur = 20 popOutHighlight.shadow2.color = 'rgba(0,0,0,0.4)' highlightTitle.x = popOutPadding highlightTitle.y = 34 highlightStartEnd.x = popOutPadding synopsis.x = popOutPadding synopsis.visible = true highlightStartEnd.visible = true if popOutHighlight.width < convertToPixel(maxExpansion) + popOutPadding popOutHighlight.width = convertToPixel(maxExpansion) + popOutPadding highlightTitle.width = convertToPixel(maxExpansion) - popOutPadding synopsis.width = convertToPixel(maxExpansion) - popOutPadding highlightStartEnd.width = convertToPixel(maxExpansion) - popOutPadding # if rowEvents[y][x].x < serviceList.maxX # #This works perfect # popOutHighlight.width = textWidthComparator.width - (rowEvents[y][x].maxX - serviceList.maxX) + popOutPadding # else # #If event is after service list # if ( (popOutHighlight.width + rowEvents[y][x].width) > convertToPixel(maxExpansion) ) # #Full cell width > maxExpansion # popOutHighlight.width = convertToPixel(maxExpansion) - rowEvents[y][x].width # rowEvents[y][x].children[0].width = convertToPixel(maxExpansion) - 10 # else # popOutHighlight.width = textWidthComparator.width - rowEvents[y][x].width + 34 # extension.height = cellHeight # rowEvents[y][x].children[1].width = rowEvents[y][x].children[0].width + 10 #HERE BE EXPANSION COLOUR # extension.backgroundColor = youviewBlue2 # #093459 # extension.shadowColor = 'rgba(0,0,0,0.5)' # extension.shadowBlur = 8 # extension.shadowX = 8 # extension.shadowY = 0 # extension.opacity = 1 # textWidthComparator.destroy() # Navigation & Fixes goRight = (x,y) -> if rowEvents[y]?[x+1]? and y >= 0 if rowEvents[y][x+1].x < 1280 deselectCell(x,y) fixDividers(x,y) x++ styleHighlight(x,y,1) else if y == -1 and filterSelection < filterLayer.length - 1 filterSelection++ highlightFilter(-1) selectedRow = 0 goLeft = (x,y) -> if rowEvents[y]?[x-1]?.maxX > 298 and y >=0 deselectCell(x,y) fixDividers(x,y) x-- styleHighlight(x,y,-1) else if y == -1 and filterSelection > 0 filterSelection-- highlightFilter(1) goDown = (x,y) -> if rowEvents[y+1]?[x]? and y != -1 deselectCell(x,y) channelIdent[y].opacity = 0.5 y++ if selectedRow == 5 and y+3 < rowEvents.length deselectRow(x,y,selectedRow, -1) showNextRow(x,y) else deselectRow(x,y,selectedRow, -1) selectedRow++ x = checkHighlightPos(x,y) styleHighlight(x,y) else if y == -1 y++ menuHighlight.animateStop() menuHighlight.width = 0 filterLayer[filterSelection].color = youviewGrey1 filterLayer[filterSelected].color = youviewBlue2 x = checkHighlightPos(x,y) styleHighlight(x,y) goUp = (x,y) -> if rowEvents[y-1]?[x]? deselectCell(x,y) channelIdent[y].opacity = 0.5 y-- if selectedRow == 1 and y != 0 deselectRow(x,y,selectedRow, 1) showPreviousRow(x,y) else deselectRow(x,y,selectedRow, 1) selectedRow-- x = checkHighlightPos(x,y) styleHighlight(x,y) # else if y == 0 # deselectCell(x,y) # filterSelection = filterSelected # highlightFilter(0) # y-- highlightFilter = (oldFilterMod) -> if filterLayer[filterSelection]? if filterSelection+oldFilterMod != filterSelected filterLayer[filterSelection+oldFilterMod].color = '#505359' else filterLayer[filterSelection+oldFilterMod].color = youviewBlue2 filterLayer[filterSelection].color = youviewBlue menuHighlight.y = 64 menuHighlight.x = filterLayer[filterSelection].midX menuHighlight.width = 0 menuHighlightGlow.width = 0 menuHighlight.opacity = 1 menuHighlight.animationStop menuHighlight.animate properties: width:filterLayer[filterSelection].width x:filterLayer[filterSelection].x time:0.4 selectFilter = () -> y = 0 filterLayer[filterSelected].color = youviewGrey1 filterLayer[filterSelection].color = youviewBlue2 filterSelected = filterSelection styleHighlight(x,y) menuHighlight.animateStop() menuHighlight.width = 0 showNextRow = (x,y) -> for i in [0...channelIdent.length] channelIdent[i].y = channelIdent[i].y - (cellHeight+2) # channelIdent[i].animate # y: channelIdent[i].y - (cellHeight+2) # options: # time:0.3 # curve:'ease-in-out' for j in [0...channels[i].children.length] channels[i].children[j].y -= (cellHeight+2) # channels[i].children[j].animate # y: channels[i].children[j].y - (cellHeight+2) # options: # time:0.3 # curve:'ease-in-out' x = checkHighlightPos(x,y) document.removeAllListeners lastChannel = channelIdent.length - 1 lastEvent = channels[lastChannel].children.length - 1 # channels[lastChannel].children[lastEvent].onAnimationEnd -> styleHighlight(x,y,0,-1) captureKeys() showPreviousRow = (x,y) -> for i in [0...channels.length] channelIdent[i].y += cellHeight+2 # channelIdent[i].animate # y: channelIdent[i].y + (cellHeight+2) # options: # time:0.3 # curve:'ease-in-out' for j in [0...channels[i].children.length] channels[i].children[j].y += cellHeight+2 # channels[i].children[j].animate # y: channels[i].children[j].y + (cellHeight+2) # options: # time:0.3 # curve:'ease-in-out' document.removeAllListeners # Utils.delay 0.4, -> x = checkHighlightPos(x,y) styleHighlight(x,y) captureKeys() # Actions record = (x,y) -> if hY >= 0 rowEvents[y][x].children[0].width -= 42 rowEvents[y][x].children[0].x = 42 deselectCell = (x, y) -> for i in [x+1...rowEvents[y].length] if rowEvents[y]?[i]? rowEvents[y][i].index = 3 if rowEvents[y]?[x]?.x <= serviceList.maxX rowEvents[y][x].children[0].width = rowEvents[y][x].maxX - serviceList.maxX - 14 else rowEvents[y][x].children[0].width = convertToPixel(data.programmeData.channels[y][x].duration) - 14 extension.opacity = 0 for i in [0...rowEvents.length] for j in [0...rowEvents[i].length] # rowEvents[y]?[x]?.stateSwitch('noHighlight') rowEvents[y]?[x]?.turnOff() rowEvents[y]?[x]?.showOff() deselectRow = (x, y, rowIndex, change) -> channels[rowIndex].backgroundColor = '' for i in [0...eventDivider[ y+change ].length] if(rowEvents[ y+change ][ i ].screenFrame.x >= serviceList.maxX + 2) rowEvents[ y+change ][ i ].children[ 2 ].opacity = separatorOpacity else rowEvents[ y+change ][ i ].children[ 2 ].opacity = 0 changeVirtualCursor = (x,y) -> if rowEvents[y][x].x <= (serviceList.screenFrame.x + serviceList.width) virtualCursor = serviceList.screenFrame.x + serviceList.width + convertToPixel(15) else virtualCursor = Utils.round(rowEvents[y][x].x, 0) + 2 checkHighlightPos = (x,y) -> for i in [0...rowEvents[y].length] if( (virtualCursor >= rowEvents[y][i].x) and (virtualCursor <= rowEvents[y][i].maxX) ) break return i fixDividers = (x,y) -> if(rowEvents[y][x].x > serviceList.maxX+2) eventDivider[y][x].opacity = 0.1 eventDivider[y][x+1].opacity = 0.1 if eventDivider[y]?[x+1]? #Initial Draw #Fill rows nextX = 0 fillRows = () -> for i in [0...data.programmeData.channels.length] rowContainer = new Layer parent:eventParent width:1280 height:cellHeight y:i * (cellHeight+2) + 2 backgroundColor:'' index:3 divider = new Layer parent:eventParent width:1280 height:2 index:0 y:rowContainer.y+cellHeight backgroundColor:'rgba(18, 44, 54, 1)' service = new Layer parent:serviceList x:96, midY:rowContainer.midY + 80 opacity:0.5 backgroundColor:'' html: "<div style='display:flex;justify-content:center;align-items:center;width:90px;height:38px;'><img src = 'images/channel_" + (i) + ".png'></div>" serviceNumber = new TextLayer parent:service x:-70, y:8 text:'00' + (i + 1) textAlign:'center' fontSize:20 letterSpacing:0.42 fontFamily:"GillSans" index:4 color:white opacity:0.5 channelIdent.push( service ) channels.push( rowContainer ) rowDivider.push( divider ) for j in [0...data.programmeData.channels[i].length] event = new Layer parent:channels[i] x:nextX width:convertToPixel(data.programmeData.channels[i][j].duration) height:cellHeight backgroundColor: '' event.turnOn = -> @.isOn = true event.turnOff = -> @.isOn = false event.showOn = -> @backgroundColor = youviewBlue2 event.showOff = -> @backgroundColor = "" event.toggleHighlight = -> if @isOn == true then @isOn = false else if @isOn == false then @isOn = true # event.states = # highlight: # backgroundColor: youviewBlue2 # options: # time:0.2 # noHighlight: # backgroundColor: "" # options: # time:0.3 rowEvents[i].push( event ) nextX = event.maxX if( event.maxX > serviceList.maxX ) # This is problem causer title = drawTitle( 1, i, j ) else title = drawTitle( 0, i, j ) if( event.x > serviceList.maxX + 64 ) separator = drawSeparator( 0.1, i, j ) else separator = drawSeparator( 0, i, j ) eventDivider[i].push( separator ) nextX = 0 drawTitle = (isVisible, i, j) -> #secondLineOpacity title = new TextLayer parent: rowEvents[i][j] fontFamily: "GillSans", fontSize: 20, color: '#ebebeb' text: data.programmeData.channels[i][j].title opacity: isVisible truncate: true x: cellLeftPadding, y: 20 #20 index: 2 height: 26, width: rowEvents[i][j].width-14 status = new Layer parent: rowEvents[i][j] image: 'images/icon/episode-pending.png' height: 20, width: 20 x: 10, y: 22 opacity: 0 if rowEvents[i][j].x < serviceList.maxX and rowEvents[i][j].maxX > serviceList.maxX title.x = -( rowEvents[i][j].x - serviceList.maxX ) + cellLeftPadding title.width = rowEvents[i][j].maxX - serviceList.maxX - 14 status.x = title.x # secondLineText = new TextLayer # parent:rowEvents[i][j] # fontFamily:'GillSans-Light, GillSans-Light', fontSize:18, color:'#ebebeb' # text:secondLine[i][j] # x:title.x, index:2, y:42 # height:24, width:title.width - 10 # opacity: if i == 0 then secondLineOpacity else 0 # style: # 'display':'block' # 'display':'-webkit-box' # 'white-space':'nowrap' # 'word-break':'break-all' # 'overflow':'hidden' # '-webkit-line-clamp':'1' # '-webkit-box-orient':'vertical' # secondLineText.visible = false if isVisible == 0 return title drawSeparator = ( isVisible, i, j ) -> separator = new Layer parent:rowEvents[i][j] width:2 backgroundColor:youviewGrey2 opacity:separatorOpacity height:cellHeight - 23 x:-2 y:12 index:0 return separator filters = new Layer parent: header width:1280 height:64 y:162, index:6 borderColor: 'transparent' backgroundColor: '' filterContainer = new Layer parent: filters width:1280 height:64 backgroundColor: 'rgba(7, 15, 27, 0.88)' for i in [0...filter.length] filterText = new TextLayer parent: filterContainer, name: filter[i], text: filter[i] autoSize:true x:138, y:24 textTransform:"uppercase",fontFamily:"GillSans-Bold",fontSize:16, color: '#505359' if i == 0 filterText.color = '#ebebeb' filterLayer.push(filterText) filterLayer[i].x = (filterLayer[i-1].maxX + 40) if filterLayer[i-1]? nowline = new Layer image:'images/nowline.png' x:460 y:253 width:99 height:467 index:6 filterDividerTop = new Layer parent:background image:'images/filter-divider.png' y:162, index:10 height:2, width:1280 filterDividerBottom = new Layer parent:background y:226, index:10 image:'images/filter-divider.png' height:2, width:1280 filterDividerBottom.states = show: opacity:1 hide: opacity:0 extension = new Layer opacity:0, index:1 blackOverlay = new Layer width: 1280, height: 720 backgroundColor: 'rgba(0,0,0,0.9)' index: 0 blueOverlay = new Layer parent:eventParent height:720, width:1280 opacity:0.8 index:1 style: 'background' : 'linear-gradient(to bottom, rgba(0, 166, 255, 0.4) 0%, rgba(0, 166, 255, 0.1) 100%)' # style: # 'background' : '-webkit-linear-gradient( 270deg, rgba(255, 0, 0, 1) 0%, rgba(255, 255, 0, 1) 15%, rgba(0, 255, 0, 1) 30%, rgba(0, 255, 255, 1) 50%, rgba(0, 0, 255, 1) 65%, rgba(255, 0, 255, 1) 80%, rgba(255, 0, 0, 1) 100% )' #( 270deg, rgba( 0, 166, 255, 255 ) 0%, rgba( 0, 166, 255, 0 ) 100% ) menuHighlight = new Layer parent:filters x:0 width: 0 height:2 backgroundColor: youviewBlue #10px wider menuHighlightGlow = new Layer parent:menuHighlight width:0 height:4 blur:7 backgroundColor: youviewBlue menuHighlightGlow.bringToFront() legend = new Layer image:'images/legend.png' maxY:Screen.height+20 width:1280 height:114 opacity:0 showLegend = new Animation legend, opacity:1 duration:0.5 maxY:Screen.height hideLegend = showLegend.reverse() dumbVariable = 0 init = () -> fillRows() styleHighlight(1,0) fillDateTrack() captureKeys() blackOverlay.sendToBack() tvShow.sendToBack() nowline.bringToFront() init() Utils.interval 0.5, -> thisY = hY thisX = hX nowLineTimeout++ if nowLineTimeout == 6 nowline.x += 1 nowLineTimeout = 0 expansionTimeout = expansionTimeout + 1 if expansionTimeout == 2 and thisY >= 0 expansionCleverness(thisX,thisY) legendTimeout++ if legendTimeout == 4 showLegend.start() Canvas.image = 'https://struanfraser.co.uk/images/youview-back.jpg'
752
#Utils & Config data = JSON.parse Utils.domLoadDataSync 'data/programmeData.json' hyperSpeed = false youviewBlue = '#00a6ff' youviewBlue2 = '#0F5391' youviewBlue3 = 'rgba(0, 51, 102, 0.8);' youviewGrey1 = '#b6b9bf' youviewGrey2 = '#83858a' darkGrey3 = '#505359' black = '#000' white = '#ebebeb' veryDarkGrey4 = '#171717' veryDarkGrey5 = '#0D0D0D' minute = 9.6 document.body.style.cursor = "auto" #Struan Utils convertToPixel = (time) -> return time*minute getDate = (modifier) -> date = new Date() dateInt = date.getUTCDate() if (dateInt + modifier) > 31 or (dateInt + modifier) <= 0 dateInt = (dateInt + modifier)%31 else dateInt+=modifier return dateInt getTime = (modifier) -> date = new Date() time = date.getHours() modifier = modifier + 48*100 if modifier%2#Odd time += ((modifier-1)/2) time = time%24 newTime = String(time) + ":00" else#Even time += (modifier/2 - 1) time = time%24 newTime = String(time) + ":30" return newTime getDay = (modifier) -> if modifier == 0 day = "Today" fontColor = white fontOpacity = 1 fontOpacityDate = 1 return day else dayString = "" today = new Date() dayInt = today.getUTCDay() dayInt += modifier if dayInt < 0 dayInt = (dayInt+7)%7 if dayInt > 6 dayInt%=7 switch dayInt when 0 then dayString = "Sunday" when 1 then dayString = "Monday" when 2 then dayString = "Tuesday" when 3 then dayString = "Wednesday" when 4 then dayString = "Thursday" when 5 then dayString = "Friday" when 6 then dayString = "Saturday" return dayString.substring(0,3) rowEvents = [] eventDivider = [] # eventTextObject = [] for i in [0..data.programmeData.channels.length] rowEvents.push( i ) eventDivider.push( i ) for i in [0..rowEvents.length] rowEvents[i] = [] eventDivider[i] = [] eventTitle = [0,1,2,3,4,5,6] channelIdent = [] dateTrack = [] rowDivider = [] filterSelection = 0 filterSelected = 0 Framer.Defaults.Animation = time: 0.3 channels = [] filterLayer = [] hX = 1 hY = 0 virtualCursor = 300 maxExpansion = 45 tunedChannel = 0 filter = ['All Channels','HD','Entertainment',"Children's",'News','Films','Factual & Lifestyle','Radio','Shopping & Travel','Adult & Dating'] tuned = ['http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4'] Utils.interval 1, -> Framer.Device.setDeviceScale( (Canvas.width/Screen.width) * 1, false ) cellHeight = 60 cellLeftPadding = 8 #Static Layers tvShow = new VideoLayer x:0 width:1280 height:720 backgroundColor: black video:tuned[tunedChannel] index:-1 tvShow.center() tvShow.player.autoplay = true tvShow.player.loop = true tvShow.player.muted = true background = new Layer width:1280 height:720 x:0 backgroundColor:null clip:true background.center() eventParent = new Layer parent:background y:260 width:1280 height:460 index:1 backgroundColor: null clip:true serviceList = new Layer parent:eventParent x:64 y:2 width:224 height:460 index:4 backgroundColor:'rgba(0, 0, 0, 0.5)' divider = new Layer parent:eventParent width:1280 height:2 y:0 index:-1 backgroundColor:veryDarkGrey4 header = new Layer parent:background x:0 width:1280 height:226 dateTrackHeader = new Layer parent:header width:1280 height:162 backgroundColor: 'rgba(0, 48, 109, 0.50)' opacity: 0.85 dateTrackContainer = new Layer parent:background x:40, y:96, index:10 height:32 opacity:1 backgroundColor: "transparent" dayTrack = [] fillDateTrack = () -> dayModifier = -7 for i in [0...15] fontColor = youviewGrey1 fontOpacity = 0.7 fontOpacityDate = 0.4 day = getDay(dayModifier) dateContainer = new Layer parent:dateTrackContainer width:80, height:48 x:i*80 backgroundColor: 'transparent' newDay = new TextLayer name:day+dayModifier parent:dateContainer width:80, height:32 text:day, textAlign: "center", textTransform: "uppercase", fontFamily: "GillSans-Bold", fontSize:16, letterSpacing: 1.92, color:fontColor opacity: fontOpacity dayTrack.push(newDay) date = getDate(dayModifier) newDate = new TextLayer parent:dateContainer y:24, width:80, height:16 text:date, textAlign: "center", textTransform: "uppercase", fontFamily: "GillSans-Bold, GillSans-Bold", fontSize:16, letterSpacing: 1.92, color:white opacity:fontOpacityDate dayModifier++ dateTrack.push(dateContainer) expansionTimeout = 0 nowLineTimeout = 0 legendTimeout = 0 unselectedSecondLineOpacity = 0.3 separatorOpacity = 0.2 #Event Handling fastScroll = 0 captureKeys = () -> document.addEventListener 'keydown', (event) -> keyCode = event.which eventHandler(keyCode) expansionTimeout = 0 dumbVariable = 0 eventHandler = Utils.throttle 0.2, (keyCode) -> thisY = hY thisX = hX if fastScroll == 4 and thisY > 0 engageHyperSpeed(keyCode) else if hyperSpeed == false switch keyCode when 13 if thisY >= 0 tune() else if thisY == -1 selectFilter() when 39 #Right legendTimeout = 0 hideLegend.start() goRight(thisX, thisY) fastScroll++ when 37 #Left legendTimeout = 0 hideLegend.start() goLeft(thisX, thisY) fastScroll++ when 40 #Down legendTimeout = 0 hideLegend.start() goDown(thisX, thisY) when 38 #Up legendTimeout = 0 hideLegend.start() goUp(thisX, thisY) when 71 if thisY >= 0 openGuide() when 82 #R record(thisX, thisY) document.addEventListener 'keyup', (event) -> keyCode = event.which closeHandler(keyCode) closeHandler = (keyCode) -> y = hY x = hX switch keyCode when 39, 37 fastScroll = 0 hyperSpeed = false disengageHyperSpeed(x,y) engageHyperSpeed = (keyCode) -> if trackChanged == true hideEverything() scroll(keyCode) timeElapsed = 1 #Scroll Stuff timeTrack = new Layer height:34, width:1280 y:225 index:6 opacity:0.95 borderColor: 'transparent' backgroundColor: 'rgba(4, 44, 94, 0.4)' timeContainer = new Layer parent:timeTrack backgroundColor: 'transparent' timeContainer.states = hide: opacity:0 show: opacity:0.95 for i in [1..4] times = new TextLayer name:'time' + i parent:timeContainer x:convertToPixel(30)*(i), y:8, index:4 height:18, width:55 text:getTime(i) textAlign:'center' fontSize:16, fontFamily:'GillSans-Bold, GillSans-Bold' color:white #Scrolling Time dateModifier = 0 dayModifier = 0 trackChanged = false selectedDate = 7 scrollingDay = new TextLayer midX:Screen.midX - 27, y:89 text:'Today', textTransform:'uppercase', fontFamily:"GillSans-Bold", color:white, fontSize:24, textAlign:'center' opacity:0 scrollingDate = new TextLayer y: 124, midX:Screen.midX - 27, opacity: 0 text:getDate(0), textTransform:'uppercase', fontFamily:'GillSans-Light', color:white, fontSize:20, textAlign:'center' changeDay = (change) -> if selectedDate <= 13 and selectedDate >= 0 dateTrack[selectedDate].children[1].opacity = 0.4 dateTrack[selectedDate].children[0].opacity = 0.7 selectedDate += change dateTrack[selectedDate].children[1].opacity = 1 dateTrack[selectedDate].children[0].opacity = 1 newDay = parseInt(scrollingDate.text) scrollingDate.text = newDay + change scrollingDay.text = getDay(selectedDate) scroll = (keyCode) -> hyperSpeed = true if trackChanged == false activeTimeTrack() #If right if keyCode == 39 if timeContainer.children[ 1 ].y == -31 timeElapsed+=1 if (getTime( timeElapsed+1 ) == '0:00') changeDay(1) #If left else if keyCode == 37 if timeContainer.children[ 1 ].y == -31 timeElapsed-- if(getTime( timeElapsed+1 ) == '0:00') dayModifier-- changeDay(-1) forEachTime = -1 if timeElapsed % 2 for k in [ 0...timeContainer.children.length ] timeContainer.children[ k ].text = getTime( forEachTime + timeElapsed ) forEachTime++ hideTime = new Animation layer:timeContainer properties: opacity:0 delay:0.1 showTime = hideTime.reverse() activeTimeTrack = () -> hideTime.start() trackChanged = true disengageHyperSpeed = Utils.throttle 1, (x,y) -> hyperSpeed = false scrollingDay.animate opacity:0 options: time:0.5 scrollingDate.animate opacity:0 # scrollingDate.onAnimationStop -> # timeContainer.stateSwitch('hide') # timeTrackDefaults() # showEverything(x,y) # scrollingDate.removeAllListeners trackChanged = false timeTrackDefaults = () -> for i in [ 0..3 ] timeContainer.children[ i ].y = 8 timeContainer.children[ i ].fontSize = 16 timeContainer.children[ i ].color = youviewGrey2 timeContainer.children[ 1 ].opacity = 0.5 timeTrack.opacity = 0.95 timeContainer.stateSwitch('show') hideEverything = Utils.throttle 1, () -> nowline.opacity = 0 for i in [0...channels.length] for j in [0...channels[i].children.length] channels[i].children[j].animate opacity:0 options: time:0.1*i dateTrackContainer.animate opacity: 0 filterContainer.animate opacity: 0 showEverything = Utils.throttle 1, (x,y) -> nowline.opacity = 1 for i in [channels.length-1..0] for j in [channels[i].children.length-1..0] channels[i].children[j].animate opacity:1 options: time:0.1*j styleHighlight(x,y) filterDividerBottom.stateSwitch('show') dateTrackContainer.animate opacity: 1 filterContainer.animate opacity:1 #Fluff openGuide = () -> if background.opacity == 0 background.opacity = 1 else background.opacity = 1 tune = () -> if background.opacity == 1 tunedChannel++ if tunedChannel == tuned.length tunedChannel = 0 tvShow.video = tuned[tunedChannel] background.opacity = 0 #Styling & Expansion styleHighlight = (x,y,xMod,yMod) -> if yMod == NaN then yMod = 0 if xMod == NaN then xMod = 0 popOutHighlight.shadow2.color = 'rgba(0,0,0,0)' channels[selectedRow].backgroundColor = youviewBlue3 channels[selectedRow].opacity = 1 channelIdent[y].opacity = 1 rowEvents[y][x].turnOn() rowEvents[y][x].showOn() eventDivider[y][x].opacity = 0 eventDivider[y][x+1].opacity = 0 if eventDivider[y]?[x+1]? if xMod == 1 or xMod == -1 changeVirtualCursor(x,y) for i in [0...channelIdent.length] for j in [0...channels[i].children.length] channels[i].children[j].turnOff() if rowEvents[y][x].x > serviceList.maxX popOutHighlight.x = rowEvents[y][x].x else popOutHighlight.x = serviceList.maxX popOutHighlight.y = rowEvents[y][x].screenFrame.y popOutHighlight.width = rowEvents[y][x].width popOutHighlight.height = 60 popOutHighlight.borderRadius = 0 highlightTitle.x = 8 highlightTitle.y = 20 synopsis.visible = false highlightStartEnd.visible = false highlightTitle.text = rowEvents[y][x].children[0].text highlightTitle.width = rowEvents[y][x].width - popOutPadding synopsis.width = rowEvents[y][x].width - popOutPadding highlightStartEnd.width = rowEvents[y][x].width - popOutPadding hY = y hX = x popOutPadding = 16 popOutHighlight = new Layer backgroundColor: '#0F5391' height: 60 #94 shadow2: y: 5 blur: 20 color: 'rgba(0,0,0,0)' highlightTitle = new TextLayer parent: popOutHighlight fontFamily: "GillSans" fontSize: 20 truncate: true color: '#ebebeb' x: 8, y: 20 # 34 height: 26 highlightStartEnd = new TextLayer parent: popOutHighlight fontFamily: "GillSans-Bold" fontSize: 16 truncate: true color: youviewGrey1 x: popOutPadding, y: 10 textTransform: 'uppercase' height: 26 text: '6:00 – 9:00PM' visible: false synopsis = new TextLayer parent: popOutHighlight fontFamily: "GillSans" color: youviewGrey1 truncate: true fontSize: 18 visible: false y: 62, x: popOutPadding height: 26 text: '5/8. Drama about midwives in 1960s London. <NAME> must win the trust of a mother who is terrified of giving birth. <NAME> and <NAME> encounter a suspected smallpox case. Also in HD.' # Expansion Rules expansionCleverness = (x,y) -> popOutHighlight.borderRadius = 1 popOutHighlight.y -= 14 popOutHighlight.x -= 8 popOutHighlight.height = 94 popOutHighlight.shadow2.y = 5 popOutHighlight.shadow2.blur = 20 popOutHighlight.shadow2.color = 'rgba(0,0,0,0.4)' highlightTitle.x = popOutPadding highlightTitle.y = 34 highlightStartEnd.x = popOutPadding synopsis.x = popOutPadding synopsis.visible = true highlightStartEnd.visible = true if popOutHighlight.width < convertToPixel(maxExpansion) + popOutPadding popOutHighlight.width = convertToPixel(maxExpansion) + popOutPadding highlightTitle.width = convertToPixel(maxExpansion) - popOutPadding synopsis.width = convertToPixel(maxExpansion) - popOutPadding highlightStartEnd.width = convertToPixel(maxExpansion) - popOutPadding # if rowEvents[y][x].x < serviceList.maxX # #This works perfect # popOutHighlight.width = textWidthComparator.width - (rowEvents[y][x].maxX - serviceList.maxX) + popOutPadding # else # #If event is after service list # if ( (popOutHighlight.width + rowEvents[y][x].width) > convertToPixel(maxExpansion) ) # #Full cell width > maxExpansion # popOutHighlight.width = convertToPixel(maxExpansion) - rowEvents[y][x].width # rowEvents[y][x].children[0].width = convertToPixel(maxExpansion) - 10 # else # popOutHighlight.width = textWidthComparator.width - rowEvents[y][x].width + 34 # extension.height = cellHeight # rowEvents[y][x].children[1].width = rowEvents[y][x].children[0].width + 10 #HERE BE EXPANSION COLOUR # extension.backgroundColor = youviewBlue2 # #093459 # extension.shadowColor = 'rgba(0,0,0,0.5)' # extension.shadowBlur = 8 # extension.shadowX = 8 # extension.shadowY = 0 # extension.opacity = 1 # textWidthComparator.destroy() # Navigation & Fixes goRight = (x,y) -> if rowEvents[y]?[x+1]? and y >= 0 if rowEvents[y][x+1].x < 1280 deselectCell(x,y) fixDividers(x,y) x++ styleHighlight(x,y,1) else if y == -1 and filterSelection < filterLayer.length - 1 filterSelection++ highlightFilter(-1) selectedRow = 0 goLeft = (x,y) -> if rowEvents[y]?[x-1]?.maxX > 298 and y >=0 deselectCell(x,y) fixDividers(x,y) x-- styleHighlight(x,y,-1) else if y == -1 and filterSelection > 0 filterSelection-- highlightFilter(1) goDown = (x,y) -> if rowEvents[y+1]?[x]? and y != -1 deselectCell(x,y) channelIdent[y].opacity = 0.5 y++ if selectedRow == 5 and y+3 < rowEvents.length deselectRow(x,y,selectedRow, -1) showNextRow(x,y) else deselectRow(x,y,selectedRow, -1) selectedRow++ x = checkHighlightPos(x,y) styleHighlight(x,y) else if y == -1 y++ menuHighlight.animateStop() menuHighlight.width = 0 filterLayer[filterSelection].color = youviewGrey1 filterLayer[filterSelected].color = youviewBlue2 x = checkHighlightPos(x,y) styleHighlight(x,y) goUp = (x,y) -> if rowEvents[y-1]?[x]? deselectCell(x,y) channelIdent[y].opacity = 0.5 y-- if selectedRow == 1 and y != 0 deselectRow(x,y,selectedRow, 1) showPreviousRow(x,y) else deselectRow(x,y,selectedRow, 1) selectedRow-- x = checkHighlightPos(x,y) styleHighlight(x,y) # else if y == 0 # deselectCell(x,y) # filterSelection = filterSelected # highlightFilter(0) # y-- highlightFilter = (oldFilterMod) -> if filterLayer[filterSelection]? if filterSelection+oldFilterMod != filterSelected filterLayer[filterSelection+oldFilterMod].color = '#505359' else filterLayer[filterSelection+oldFilterMod].color = youviewBlue2 filterLayer[filterSelection].color = youviewBlue menuHighlight.y = 64 menuHighlight.x = filterLayer[filterSelection].midX menuHighlight.width = 0 menuHighlightGlow.width = 0 menuHighlight.opacity = 1 menuHighlight.animationStop menuHighlight.animate properties: width:filterLayer[filterSelection].width x:filterLayer[filterSelection].x time:0.4 selectFilter = () -> y = 0 filterLayer[filterSelected].color = youviewGrey1 filterLayer[filterSelection].color = youviewBlue2 filterSelected = filterSelection styleHighlight(x,y) menuHighlight.animateStop() menuHighlight.width = 0 showNextRow = (x,y) -> for i in [0...channelIdent.length] channelIdent[i].y = channelIdent[i].y - (cellHeight+2) # channelIdent[i].animate # y: channelIdent[i].y - (cellHeight+2) # options: # time:0.3 # curve:'ease-in-out' for j in [0...channels[i].children.length] channels[i].children[j].y -= (cellHeight+2) # channels[i].children[j].animate # y: channels[i].children[j].y - (cellHeight+2) # options: # time:0.3 # curve:'ease-in-out' x = checkHighlightPos(x,y) document.removeAllListeners lastChannel = channelIdent.length - 1 lastEvent = channels[lastChannel].children.length - 1 # channels[lastChannel].children[lastEvent].onAnimationEnd -> styleHighlight(x,y,0,-1) captureKeys() showPreviousRow = (x,y) -> for i in [0...channels.length] channelIdent[i].y += cellHeight+2 # channelIdent[i].animate # y: channelIdent[i].y + (cellHeight+2) # options: # time:0.3 # curve:'ease-in-out' for j in [0...channels[i].children.length] channels[i].children[j].y += cellHeight+2 # channels[i].children[j].animate # y: channels[i].children[j].y + (cellHeight+2) # options: # time:0.3 # curve:'ease-in-out' document.removeAllListeners # Utils.delay 0.4, -> x = checkHighlightPos(x,y) styleHighlight(x,y) captureKeys() # Actions record = (x,y) -> if hY >= 0 rowEvents[y][x].children[0].width -= 42 rowEvents[y][x].children[0].x = 42 deselectCell = (x, y) -> for i in [x+1...rowEvents[y].length] if rowEvents[y]?[i]? rowEvents[y][i].index = 3 if rowEvents[y]?[x]?.x <= serviceList.maxX rowEvents[y][x].children[0].width = rowEvents[y][x].maxX - serviceList.maxX - 14 else rowEvents[y][x].children[0].width = convertToPixel(data.programmeData.channels[y][x].duration) - 14 extension.opacity = 0 for i in [0...rowEvents.length] for j in [0...rowEvents[i].length] # rowEvents[y]?[x]?.stateSwitch('noHighlight') rowEvents[y]?[x]?.turnOff() rowEvents[y]?[x]?.showOff() deselectRow = (x, y, rowIndex, change) -> channels[rowIndex].backgroundColor = '' for i in [0...eventDivider[ y+change ].length] if(rowEvents[ y+change ][ i ].screenFrame.x >= serviceList.maxX + 2) rowEvents[ y+change ][ i ].children[ 2 ].opacity = separatorOpacity else rowEvents[ y+change ][ i ].children[ 2 ].opacity = 0 changeVirtualCursor = (x,y) -> if rowEvents[y][x].x <= (serviceList.screenFrame.x + serviceList.width) virtualCursor = serviceList.screenFrame.x + serviceList.width + convertToPixel(15) else virtualCursor = Utils.round(rowEvents[y][x].x, 0) + 2 checkHighlightPos = (x,y) -> for i in [0...rowEvents[y].length] if( (virtualCursor >= rowEvents[y][i].x) and (virtualCursor <= rowEvents[y][i].maxX) ) break return i fixDividers = (x,y) -> if(rowEvents[y][x].x > serviceList.maxX+2) eventDivider[y][x].opacity = 0.1 eventDivider[y][x+1].opacity = 0.1 if eventDivider[y]?[x+1]? #Initial Draw #Fill rows nextX = 0 fillRows = () -> for i in [0...data.programmeData.channels.length] rowContainer = new Layer parent:eventParent width:1280 height:cellHeight y:i * (cellHeight+2) + 2 backgroundColor:'' index:3 divider = new Layer parent:eventParent width:1280 height:2 index:0 y:rowContainer.y+cellHeight backgroundColor:'rgba(18, 44, 54, 1)' service = new Layer parent:serviceList x:96, midY:rowContainer.midY + 80 opacity:0.5 backgroundColor:'' html: "<div style='display:flex;justify-content:center;align-items:center;width:90px;height:38px;'><img src = 'images/channel_" + (i) + ".png'></div>" serviceNumber = new TextLayer parent:service x:-70, y:8 text:'00' + (i + 1) textAlign:'center' fontSize:20 letterSpacing:0.42 fontFamily:"GillSans" index:4 color:white opacity:0.5 channelIdent.push( service ) channels.push( rowContainer ) rowDivider.push( divider ) for j in [0...data.programmeData.channels[i].length] event = new Layer parent:channels[i] x:nextX width:convertToPixel(data.programmeData.channels[i][j].duration) height:cellHeight backgroundColor: '' event.turnOn = -> @.isOn = true event.turnOff = -> @.isOn = false event.showOn = -> @backgroundColor = youviewBlue2 event.showOff = -> @backgroundColor = "" event.toggleHighlight = -> if @isOn == true then @isOn = false else if @isOn == false then @isOn = true # event.states = # highlight: # backgroundColor: youviewBlue2 # options: # time:0.2 # noHighlight: # backgroundColor: "" # options: # time:0.3 rowEvents[i].push( event ) nextX = event.maxX if( event.maxX > serviceList.maxX ) # This is problem causer title = drawTitle( 1, i, j ) else title = drawTitle( 0, i, j ) if( event.x > serviceList.maxX + 64 ) separator = drawSeparator( 0.1, i, j ) else separator = drawSeparator( 0, i, j ) eventDivider[i].push( separator ) nextX = 0 drawTitle = (isVisible, i, j) -> #secondLineOpacity title = new TextLayer parent: rowEvents[i][j] fontFamily: "GillSans", fontSize: 20, color: '#ebebeb' text: data.programmeData.channels[i][j].title opacity: isVisible truncate: true x: cellLeftPadding, y: 20 #20 index: 2 height: 26, width: rowEvents[i][j].width-14 status = new Layer parent: rowEvents[i][j] image: 'images/icon/episode-pending.png' height: 20, width: 20 x: 10, y: 22 opacity: 0 if rowEvents[i][j].x < serviceList.maxX and rowEvents[i][j].maxX > serviceList.maxX title.x = -( rowEvents[i][j].x - serviceList.maxX ) + cellLeftPadding title.width = rowEvents[i][j].maxX - serviceList.maxX - 14 status.x = title.x # secondLineText = new TextLayer # parent:rowEvents[i][j] # fontFamily:'GillSans-Light, GillSans-Light', fontSize:18, color:'#ebebeb' # text:secondLine[i][j] # x:title.x, index:2, y:42 # height:24, width:title.width - 10 # opacity: if i == 0 then secondLineOpacity else 0 # style: # 'display':'block' # 'display':'-webkit-box' # 'white-space':'nowrap' # 'word-break':'break-all' # 'overflow':'hidden' # '-webkit-line-clamp':'1' # '-webkit-box-orient':'vertical' # secondLineText.visible = false if isVisible == 0 return title drawSeparator = ( isVisible, i, j ) -> separator = new Layer parent:rowEvents[i][j] width:2 backgroundColor:youviewGrey2 opacity:separatorOpacity height:cellHeight - 23 x:-2 y:12 index:0 return separator filters = new Layer parent: header width:1280 height:64 y:162, index:6 borderColor: 'transparent' backgroundColor: '' filterContainer = new Layer parent: filters width:1280 height:64 backgroundColor: 'rgba(7, 15, 27, 0.88)' for i in [0...filter.length] filterText = new TextLayer parent: filterContainer, name: filter[i], text: filter[i] autoSize:true x:138, y:24 textTransform:"uppercase",fontFamily:"GillSans-Bold",fontSize:16, color: '#505359' if i == 0 filterText.color = '#ebebeb' filterLayer.push(filterText) filterLayer[i].x = (filterLayer[i-1].maxX + 40) if filterLayer[i-1]? nowline = new Layer image:'images/nowline.png' x:460 y:253 width:99 height:467 index:6 filterDividerTop = new Layer parent:background image:'images/filter-divider.png' y:162, index:10 height:2, width:1280 filterDividerBottom = new Layer parent:background y:226, index:10 image:'images/filter-divider.png' height:2, width:1280 filterDividerBottom.states = show: opacity:1 hide: opacity:0 extension = new Layer opacity:0, index:1 blackOverlay = new Layer width: 1280, height: 720 backgroundColor: 'rgba(0,0,0,0.9)' index: 0 blueOverlay = new Layer parent:eventParent height:720, width:1280 opacity:0.8 index:1 style: 'background' : 'linear-gradient(to bottom, rgba(0, 166, 255, 0.4) 0%, rgba(0, 166, 255, 0.1) 100%)' # style: # 'background' : '-webkit-linear-gradient( 270deg, rgba(255, 0, 0, 1) 0%, rgba(255, 255, 0, 1) 15%, rgba(0, 255, 0, 1) 30%, rgba(0, 255, 255, 1) 50%, rgba(0, 0, 255, 1) 65%, rgba(255, 0, 255, 1) 80%, rgba(255, 0, 0, 1) 100% )' #( 270deg, rgba( 0, 166, 255, 255 ) 0%, rgba( 0, 166, 255, 0 ) 100% ) menuHighlight = new Layer parent:filters x:0 width: 0 height:2 backgroundColor: youviewBlue #10px wider menuHighlightGlow = new Layer parent:menuHighlight width:0 height:4 blur:7 backgroundColor: youviewBlue menuHighlightGlow.bringToFront() legend = new Layer image:'images/legend.png' maxY:Screen.height+20 width:1280 height:114 opacity:0 showLegend = new Animation legend, opacity:1 duration:0.5 maxY:Screen.height hideLegend = showLegend.reverse() dumbVariable = 0 init = () -> fillRows() styleHighlight(1,0) fillDateTrack() captureKeys() blackOverlay.sendToBack() tvShow.sendToBack() nowline.bringToFront() init() Utils.interval 0.5, -> thisY = hY thisX = hX nowLineTimeout++ if nowLineTimeout == 6 nowline.x += 1 nowLineTimeout = 0 expansionTimeout = expansionTimeout + 1 if expansionTimeout == 2 and thisY >= 0 expansionCleverness(thisX,thisY) legendTimeout++ if legendTimeout == 4 showLegend.start() Canvas.image = 'https://struanfraser.co.uk/images/youview-back.jpg'
true
#Utils & Config data = JSON.parse Utils.domLoadDataSync 'data/programmeData.json' hyperSpeed = false youviewBlue = '#00a6ff' youviewBlue2 = '#0F5391' youviewBlue3 = 'rgba(0, 51, 102, 0.8);' youviewGrey1 = '#b6b9bf' youviewGrey2 = '#83858a' darkGrey3 = '#505359' black = '#000' white = '#ebebeb' veryDarkGrey4 = '#171717' veryDarkGrey5 = '#0D0D0D' minute = 9.6 document.body.style.cursor = "auto" #Struan Utils convertToPixel = (time) -> return time*minute getDate = (modifier) -> date = new Date() dateInt = date.getUTCDate() if (dateInt + modifier) > 31 or (dateInt + modifier) <= 0 dateInt = (dateInt + modifier)%31 else dateInt+=modifier return dateInt getTime = (modifier) -> date = new Date() time = date.getHours() modifier = modifier + 48*100 if modifier%2#Odd time += ((modifier-1)/2) time = time%24 newTime = String(time) + ":00" else#Even time += (modifier/2 - 1) time = time%24 newTime = String(time) + ":30" return newTime getDay = (modifier) -> if modifier == 0 day = "Today" fontColor = white fontOpacity = 1 fontOpacityDate = 1 return day else dayString = "" today = new Date() dayInt = today.getUTCDay() dayInt += modifier if dayInt < 0 dayInt = (dayInt+7)%7 if dayInt > 6 dayInt%=7 switch dayInt when 0 then dayString = "Sunday" when 1 then dayString = "Monday" when 2 then dayString = "Tuesday" when 3 then dayString = "Wednesday" when 4 then dayString = "Thursday" when 5 then dayString = "Friday" when 6 then dayString = "Saturday" return dayString.substring(0,3) rowEvents = [] eventDivider = [] # eventTextObject = [] for i in [0..data.programmeData.channels.length] rowEvents.push( i ) eventDivider.push( i ) for i in [0..rowEvents.length] rowEvents[i] = [] eventDivider[i] = [] eventTitle = [0,1,2,3,4,5,6] channelIdent = [] dateTrack = [] rowDivider = [] filterSelection = 0 filterSelected = 0 Framer.Defaults.Animation = time: 0.3 channels = [] filterLayer = [] hX = 1 hY = 0 virtualCursor = 300 maxExpansion = 45 tunedChannel = 0 filter = ['All Channels','HD','Entertainment',"Children's",'News','Films','Factual & Lifestyle','Radio','Shopping & Travel','Adult & Dating'] tuned = ['http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4'] Utils.interval 1, -> Framer.Device.setDeviceScale( (Canvas.width/Screen.width) * 1, false ) cellHeight = 60 cellLeftPadding = 8 #Static Layers tvShow = new VideoLayer x:0 width:1280 height:720 backgroundColor: black video:tuned[tunedChannel] index:-1 tvShow.center() tvShow.player.autoplay = true tvShow.player.loop = true tvShow.player.muted = true background = new Layer width:1280 height:720 x:0 backgroundColor:null clip:true background.center() eventParent = new Layer parent:background y:260 width:1280 height:460 index:1 backgroundColor: null clip:true serviceList = new Layer parent:eventParent x:64 y:2 width:224 height:460 index:4 backgroundColor:'rgba(0, 0, 0, 0.5)' divider = new Layer parent:eventParent width:1280 height:2 y:0 index:-1 backgroundColor:veryDarkGrey4 header = new Layer parent:background x:0 width:1280 height:226 dateTrackHeader = new Layer parent:header width:1280 height:162 backgroundColor: 'rgba(0, 48, 109, 0.50)' opacity: 0.85 dateTrackContainer = new Layer parent:background x:40, y:96, index:10 height:32 opacity:1 backgroundColor: "transparent" dayTrack = [] fillDateTrack = () -> dayModifier = -7 for i in [0...15] fontColor = youviewGrey1 fontOpacity = 0.7 fontOpacityDate = 0.4 day = getDay(dayModifier) dateContainer = new Layer parent:dateTrackContainer width:80, height:48 x:i*80 backgroundColor: 'transparent' newDay = new TextLayer name:day+dayModifier parent:dateContainer width:80, height:32 text:day, textAlign: "center", textTransform: "uppercase", fontFamily: "GillSans-Bold", fontSize:16, letterSpacing: 1.92, color:fontColor opacity: fontOpacity dayTrack.push(newDay) date = getDate(dayModifier) newDate = new TextLayer parent:dateContainer y:24, width:80, height:16 text:date, textAlign: "center", textTransform: "uppercase", fontFamily: "GillSans-Bold, GillSans-Bold", fontSize:16, letterSpacing: 1.92, color:white opacity:fontOpacityDate dayModifier++ dateTrack.push(dateContainer) expansionTimeout = 0 nowLineTimeout = 0 legendTimeout = 0 unselectedSecondLineOpacity = 0.3 separatorOpacity = 0.2 #Event Handling fastScroll = 0 captureKeys = () -> document.addEventListener 'keydown', (event) -> keyCode = event.which eventHandler(keyCode) expansionTimeout = 0 dumbVariable = 0 eventHandler = Utils.throttle 0.2, (keyCode) -> thisY = hY thisX = hX if fastScroll == 4 and thisY > 0 engageHyperSpeed(keyCode) else if hyperSpeed == false switch keyCode when 13 if thisY >= 0 tune() else if thisY == -1 selectFilter() when 39 #Right legendTimeout = 0 hideLegend.start() goRight(thisX, thisY) fastScroll++ when 37 #Left legendTimeout = 0 hideLegend.start() goLeft(thisX, thisY) fastScroll++ when 40 #Down legendTimeout = 0 hideLegend.start() goDown(thisX, thisY) when 38 #Up legendTimeout = 0 hideLegend.start() goUp(thisX, thisY) when 71 if thisY >= 0 openGuide() when 82 #R record(thisX, thisY) document.addEventListener 'keyup', (event) -> keyCode = event.which closeHandler(keyCode) closeHandler = (keyCode) -> y = hY x = hX switch keyCode when 39, 37 fastScroll = 0 hyperSpeed = false disengageHyperSpeed(x,y) engageHyperSpeed = (keyCode) -> if trackChanged == true hideEverything() scroll(keyCode) timeElapsed = 1 #Scroll Stuff timeTrack = new Layer height:34, width:1280 y:225 index:6 opacity:0.95 borderColor: 'transparent' backgroundColor: 'rgba(4, 44, 94, 0.4)' timeContainer = new Layer parent:timeTrack backgroundColor: 'transparent' timeContainer.states = hide: opacity:0 show: opacity:0.95 for i in [1..4] times = new TextLayer name:'time' + i parent:timeContainer x:convertToPixel(30)*(i), y:8, index:4 height:18, width:55 text:getTime(i) textAlign:'center' fontSize:16, fontFamily:'GillSans-Bold, GillSans-Bold' color:white #Scrolling Time dateModifier = 0 dayModifier = 0 trackChanged = false selectedDate = 7 scrollingDay = new TextLayer midX:Screen.midX - 27, y:89 text:'Today', textTransform:'uppercase', fontFamily:"GillSans-Bold", color:white, fontSize:24, textAlign:'center' opacity:0 scrollingDate = new TextLayer y: 124, midX:Screen.midX - 27, opacity: 0 text:getDate(0), textTransform:'uppercase', fontFamily:'GillSans-Light', color:white, fontSize:20, textAlign:'center' changeDay = (change) -> if selectedDate <= 13 and selectedDate >= 0 dateTrack[selectedDate].children[1].opacity = 0.4 dateTrack[selectedDate].children[0].opacity = 0.7 selectedDate += change dateTrack[selectedDate].children[1].opacity = 1 dateTrack[selectedDate].children[0].opacity = 1 newDay = parseInt(scrollingDate.text) scrollingDate.text = newDay + change scrollingDay.text = getDay(selectedDate) scroll = (keyCode) -> hyperSpeed = true if trackChanged == false activeTimeTrack() #If right if keyCode == 39 if timeContainer.children[ 1 ].y == -31 timeElapsed+=1 if (getTime( timeElapsed+1 ) == '0:00') changeDay(1) #If left else if keyCode == 37 if timeContainer.children[ 1 ].y == -31 timeElapsed-- if(getTime( timeElapsed+1 ) == '0:00') dayModifier-- changeDay(-1) forEachTime = -1 if timeElapsed % 2 for k in [ 0...timeContainer.children.length ] timeContainer.children[ k ].text = getTime( forEachTime + timeElapsed ) forEachTime++ hideTime = new Animation layer:timeContainer properties: opacity:0 delay:0.1 showTime = hideTime.reverse() activeTimeTrack = () -> hideTime.start() trackChanged = true disengageHyperSpeed = Utils.throttle 1, (x,y) -> hyperSpeed = false scrollingDay.animate opacity:0 options: time:0.5 scrollingDate.animate opacity:0 # scrollingDate.onAnimationStop -> # timeContainer.stateSwitch('hide') # timeTrackDefaults() # showEverything(x,y) # scrollingDate.removeAllListeners trackChanged = false timeTrackDefaults = () -> for i in [ 0..3 ] timeContainer.children[ i ].y = 8 timeContainer.children[ i ].fontSize = 16 timeContainer.children[ i ].color = youviewGrey2 timeContainer.children[ 1 ].opacity = 0.5 timeTrack.opacity = 0.95 timeContainer.stateSwitch('show') hideEverything = Utils.throttle 1, () -> nowline.opacity = 0 for i in [0...channels.length] for j in [0...channels[i].children.length] channels[i].children[j].animate opacity:0 options: time:0.1*i dateTrackContainer.animate opacity: 0 filterContainer.animate opacity: 0 showEverything = Utils.throttle 1, (x,y) -> nowline.opacity = 1 for i in [channels.length-1..0] for j in [channels[i].children.length-1..0] channels[i].children[j].animate opacity:1 options: time:0.1*j styleHighlight(x,y) filterDividerBottom.stateSwitch('show') dateTrackContainer.animate opacity: 1 filterContainer.animate opacity:1 #Fluff openGuide = () -> if background.opacity == 0 background.opacity = 1 else background.opacity = 1 tune = () -> if background.opacity == 1 tunedChannel++ if tunedChannel == tuned.length tunedChannel = 0 tvShow.video = tuned[tunedChannel] background.opacity = 0 #Styling & Expansion styleHighlight = (x,y,xMod,yMod) -> if yMod == NaN then yMod = 0 if xMod == NaN then xMod = 0 popOutHighlight.shadow2.color = 'rgba(0,0,0,0)' channels[selectedRow].backgroundColor = youviewBlue3 channels[selectedRow].opacity = 1 channelIdent[y].opacity = 1 rowEvents[y][x].turnOn() rowEvents[y][x].showOn() eventDivider[y][x].opacity = 0 eventDivider[y][x+1].opacity = 0 if eventDivider[y]?[x+1]? if xMod == 1 or xMod == -1 changeVirtualCursor(x,y) for i in [0...channelIdent.length] for j in [0...channels[i].children.length] channels[i].children[j].turnOff() if rowEvents[y][x].x > serviceList.maxX popOutHighlight.x = rowEvents[y][x].x else popOutHighlight.x = serviceList.maxX popOutHighlight.y = rowEvents[y][x].screenFrame.y popOutHighlight.width = rowEvents[y][x].width popOutHighlight.height = 60 popOutHighlight.borderRadius = 0 highlightTitle.x = 8 highlightTitle.y = 20 synopsis.visible = false highlightStartEnd.visible = false highlightTitle.text = rowEvents[y][x].children[0].text highlightTitle.width = rowEvents[y][x].width - popOutPadding synopsis.width = rowEvents[y][x].width - popOutPadding highlightStartEnd.width = rowEvents[y][x].width - popOutPadding hY = y hX = x popOutPadding = 16 popOutHighlight = new Layer backgroundColor: '#0F5391' height: 60 #94 shadow2: y: 5 blur: 20 color: 'rgba(0,0,0,0)' highlightTitle = new TextLayer parent: popOutHighlight fontFamily: "GillSans" fontSize: 20 truncate: true color: '#ebebeb' x: 8, y: 20 # 34 height: 26 highlightStartEnd = new TextLayer parent: popOutHighlight fontFamily: "GillSans-Bold" fontSize: 16 truncate: true color: youviewGrey1 x: popOutPadding, y: 10 textTransform: 'uppercase' height: 26 text: '6:00 – 9:00PM' visible: false synopsis = new TextLayer parent: popOutHighlight fontFamily: "GillSans" color: youviewGrey1 truncate: true fontSize: 18 visible: false y: 62, x: popOutPadding height: 26 text: '5/8. Drama about midwives in 1960s London. PI:NAME:<NAME>END_PI must win the trust of a mother who is terrified of giving birth. PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI encounter a suspected smallpox case. Also in HD.' # Expansion Rules expansionCleverness = (x,y) -> popOutHighlight.borderRadius = 1 popOutHighlight.y -= 14 popOutHighlight.x -= 8 popOutHighlight.height = 94 popOutHighlight.shadow2.y = 5 popOutHighlight.shadow2.blur = 20 popOutHighlight.shadow2.color = 'rgba(0,0,0,0.4)' highlightTitle.x = popOutPadding highlightTitle.y = 34 highlightStartEnd.x = popOutPadding synopsis.x = popOutPadding synopsis.visible = true highlightStartEnd.visible = true if popOutHighlight.width < convertToPixel(maxExpansion) + popOutPadding popOutHighlight.width = convertToPixel(maxExpansion) + popOutPadding highlightTitle.width = convertToPixel(maxExpansion) - popOutPadding synopsis.width = convertToPixel(maxExpansion) - popOutPadding highlightStartEnd.width = convertToPixel(maxExpansion) - popOutPadding # if rowEvents[y][x].x < serviceList.maxX # #This works perfect # popOutHighlight.width = textWidthComparator.width - (rowEvents[y][x].maxX - serviceList.maxX) + popOutPadding # else # #If event is after service list # if ( (popOutHighlight.width + rowEvents[y][x].width) > convertToPixel(maxExpansion) ) # #Full cell width > maxExpansion # popOutHighlight.width = convertToPixel(maxExpansion) - rowEvents[y][x].width # rowEvents[y][x].children[0].width = convertToPixel(maxExpansion) - 10 # else # popOutHighlight.width = textWidthComparator.width - rowEvents[y][x].width + 34 # extension.height = cellHeight # rowEvents[y][x].children[1].width = rowEvents[y][x].children[0].width + 10 #HERE BE EXPANSION COLOUR # extension.backgroundColor = youviewBlue2 # #093459 # extension.shadowColor = 'rgba(0,0,0,0.5)' # extension.shadowBlur = 8 # extension.shadowX = 8 # extension.shadowY = 0 # extension.opacity = 1 # textWidthComparator.destroy() # Navigation & Fixes goRight = (x,y) -> if rowEvents[y]?[x+1]? and y >= 0 if rowEvents[y][x+1].x < 1280 deselectCell(x,y) fixDividers(x,y) x++ styleHighlight(x,y,1) else if y == -1 and filterSelection < filterLayer.length - 1 filterSelection++ highlightFilter(-1) selectedRow = 0 goLeft = (x,y) -> if rowEvents[y]?[x-1]?.maxX > 298 and y >=0 deselectCell(x,y) fixDividers(x,y) x-- styleHighlight(x,y,-1) else if y == -1 and filterSelection > 0 filterSelection-- highlightFilter(1) goDown = (x,y) -> if rowEvents[y+1]?[x]? and y != -1 deselectCell(x,y) channelIdent[y].opacity = 0.5 y++ if selectedRow == 5 and y+3 < rowEvents.length deselectRow(x,y,selectedRow, -1) showNextRow(x,y) else deselectRow(x,y,selectedRow, -1) selectedRow++ x = checkHighlightPos(x,y) styleHighlight(x,y) else if y == -1 y++ menuHighlight.animateStop() menuHighlight.width = 0 filterLayer[filterSelection].color = youviewGrey1 filterLayer[filterSelected].color = youviewBlue2 x = checkHighlightPos(x,y) styleHighlight(x,y) goUp = (x,y) -> if rowEvents[y-1]?[x]? deselectCell(x,y) channelIdent[y].opacity = 0.5 y-- if selectedRow == 1 and y != 0 deselectRow(x,y,selectedRow, 1) showPreviousRow(x,y) else deselectRow(x,y,selectedRow, 1) selectedRow-- x = checkHighlightPos(x,y) styleHighlight(x,y) # else if y == 0 # deselectCell(x,y) # filterSelection = filterSelected # highlightFilter(0) # y-- highlightFilter = (oldFilterMod) -> if filterLayer[filterSelection]? if filterSelection+oldFilterMod != filterSelected filterLayer[filterSelection+oldFilterMod].color = '#505359' else filterLayer[filterSelection+oldFilterMod].color = youviewBlue2 filterLayer[filterSelection].color = youviewBlue menuHighlight.y = 64 menuHighlight.x = filterLayer[filterSelection].midX menuHighlight.width = 0 menuHighlightGlow.width = 0 menuHighlight.opacity = 1 menuHighlight.animationStop menuHighlight.animate properties: width:filterLayer[filterSelection].width x:filterLayer[filterSelection].x time:0.4 selectFilter = () -> y = 0 filterLayer[filterSelected].color = youviewGrey1 filterLayer[filterSelection].color = youviewBlue2 filterSelected = filterSelection styleHighlight(x,y) menuHighlight.animateStop() menuHighlight.width = 0 showNextRow = (x,y) -> for i in [0...channelIdent.length] channelIdent[i].y = channelIdent[i].y - (cellHeight+2) # channelIdent[i].animate # y: channelIdent[i].y - (cellHeight+2) # options: # time:0.3 # curve:'ease-in-out' for j in [0...channels[i].children.length] channels[i].children[j].y -= (cellHeight+2) # channels[i].children[j].animate # y: channels[i].children[j].y - (cellHeight+2) # options: # time:0.3 # curve:'ease-in-out' x = checkHighlightPos(x,y) document.removeAllListeners lastChannel = channelIdent.length - 1 lastEvent = channels[lastChannel].children.length - 1 # channels[lastChannel].children[lastEvent].onAnimationEnd -> styleHighlight(x,y,0,-1) captureKeys() showPreviousRow = (x,y) -> for i in [0...channels.length] channelIdent[i].y += cellHeight+2 # channelIdent[i].animate # y: channelIdent[i].y + (cellHeight+2) # options: # time:0.3 # curve:'ease-in-out' for j in [0...channels[i].children.length] channels[i].children[j].y += cellHeight+2 # channels[i].children[j].animate # y: channels[i].children[j].y + (cellHeight+2) # options: # time:0.3 # curve:'ease-in-out' document.removeAllListeners # Utils.delay 0.4, -> x = checkHighlightPos(x,y) styleHighlight(x,y) captureKeys() # Actions record = (x,y) -> if hY >= 0 rowEvents[y][x].children[0].width -= 42 rowEvents[y][x].children[0].x = 42 deselectCell = (x, y) -> for i in [x+1...rowEvents[y].length] if rowEvents[y]?[i]? rowEvents[y][i].index = 3 if rowEvents[y]?[x]?.x <= serviceList.maxX rowEvents[y][x].children[0].width = rowEvents[y][x].maxX - serviceList.maxX - 14 else rowEvents[y][x].children[0].width = convertToPixel(data.programmeData.channels[y][x].duration) - 14 extension.opacity = 0 for i in [0...rowEvents.length] for j in [0...rowEvents[i].length] # rowEvents[y]?[x]?.stateSwitch('noHighlight') rowEvents[y]?[x]?.turnOff() rowEvents[y]?[x]?.showOff() deselectRow = (x, y, rowIndex, change) -> channels[rowIndex].backgroundColor = '' for i in [0...eventDivider[ y+change ].length] if(rowEvents[ y+change ][ i ].screenFrame.x >= serviceList.maxX + 2) rowEvents[ y+change ][ i ].children[ 2 ].opacity = separatorOpacity else rowEvents[ y+change ][ i ].children[ 2 ].opacity = 0 changeVirtualCursor = (x,y) -> if rowEvents[y][x].x <= (serviceList.screenFrame.x + serviceList.width) virtualCursor = serviceList.screenFrame.x + serviceList.width + convertToPixel(15) else virtualCursor = Utils.round(rowEvents[y][x].x, 0) + 2 checkHighlightPos = (x,y) -> for i in [0...rowEvents[y].length] if( (virtualCursor >= rowEvents[y][i].x) and (virtualCursor <= rowEvents[y][i].maxX) ) break return i fixDividers = (x,y) -> if(rowEvents[y][x].x > serviceList.maxX+2) eventDivider[y][x].opacity = 0.1 eventDivider[y][x+1].opacity = 0.1 if eventDivider[y]?[x+1]? #Initial Draw #Fill rows nextX = 0 fillRows = () -> for i in [0...data.programmeData.channels.length] rowContainer = new Layer parent:eventParent width:1280 height:cellHeight y:i * (cellHeight+2) + 2 backgroundColor:'' index:3 divider = new Layer parent:eventParent width:1280 height:2 index:0 y:rowContainer.y+cellHeight backgroundColor:'rgba(18, 44, 54, 1)' service = new Layer parent:serviceList x:96, midY:rowContainer.midY + 80 opacity:0.5 backgroundColor:'' html: "<div style='display:flex;justify-content:center;align-items:center;width:90px;height:38px;'><img src = 'images/channel_" + (i) + ".png'></div>" serviceNumber = new TextLayer parent:service x:-70, y:8 text:'00' + (i + 1) textAlign:'center' fontSize:20 letterSpacing:0.42 fontFamily:"GillSans" index:4 color:white opacity:0.5 channelIdent.push( service ) channels.push( rowContainer ) rowDivider.push( divider ) for j in [0...data.programmeData.channels[i].length] event = new Layer parent:channels[i] x:nextX width:convertToPixel(data.programmeData.channels[i][j].duration) height:cellHeight backgroundColor: '' event.turnOn = -> @.isOn = true event.turnOff = -> @.isOn = false event.showOn = -> @backgroundColor = youviewBlue2 event.showOff = -> @backgroundColor = "" event.toggleHighlight = -> if @isOn == true then @isOn = false else if @isOn == false then @isOn = true # event.states = # highlight: # backgroundColor: youviewBlue2 # options: # time:0.2 # noHighlight: # backgroundColor: "" # options: # time:0.3 rowEvents[i].push( event ) nextX = event.maxX if( event.maxX > serviceList.maxX ) # This is problem causer title = drawTitle( 1, i, j ) else title = drawTitle( 0, i, j ) if( event.x > serviceList.maxX + 64 ) separator = drawSeparator( 0.1, i, j ) else separator = drawSeparator( 0, i, j ) eventDivider[i].push( separator ) nextX = 0 drawTitle = (isVisible, i, j) -> #secondLineOpacity title = new TextLayer parent: rowEvents[i][j] fontFamily: "GillSans", fontSize: 20, color: '#ebebeb' text: data.programmeData.channels[i][j].title opacity: isVisible truncate: true x: cellLeftPadding, y: 20 #20 index: 2 height: 26, width: rowEvents[i][j].width-14 status = new Layer parent: rowEvents[i][j] image: 'images/icon/episode-pending.png' height: 20, width: 20 x: 10, y: 22 opacity: 0 if rowEvents[i][j].x < serviceList.maxX and rowEvents[i][j].maxX > serviceList.maxX title.x = -( rowEvents[i][j].x - serviceList.maxX ) + cellLeftPadding title.width = rowEvents[i][j].maxX - serviceList.maxX - 14 status.x = title.x # secondLineText = new TextLayer # parent:rowEvents[i][j] # fontFamily:'GillSans-Light, GillSans-Light', fontSize:18, color:'#ebebeb' # text:secondLine[i][j] # x:title.x, index:2, y:42 # height:24, width:title.width - 10 # opacity: if i == 0 then secondLineOpacity else 0 # style: # 'display':'block' # 'display':'-webkit-box' # 'white-space':'nowrap' # 'word-break':'break-all' # 'overflow':'hidden' # '-webkit-line-clamp':'1' # '-webkit-box-orient':'vertical' # secondLineText.visible = false if isVisible == 0 return title drawSeparator = ( isVisible, i, j ) -> separator = new Layer parent:rowEvents[i][j] width:2 backgroundColor:youviewGrey2 opacity:separatorOpacity height:cellHeight - 23 x:-2 y:12 index:0 return separator filters = new Layer parent: header width:1280 height:64 y:162, index:6 borderColor: 'transparent' backgroundColor: '' filterContainer = new Layer parent: filters width:1280 height:64 backgroundColor: 'rgba(7, 15, 27, 0.88)' for i in [0...filter.length] filterText = new TextLayer parent: filterContainer, name: filter[i], text: filter[i] autoSize:true x:138, y:24 textTransform:"uppercase",fontFamily:"GillSans-Bold",fontSize:16, color: '#505359' if i == 0 filterText.color = '#ebebeb' filterLayer.push(filterText) filterLayer[i].x = (filterLayer[i-1].maxX + 40) if filterLayer[i-1]? nowline = new Layer image:'images/nowline.png' x:460 y:253 width:99 height:467 index:6 filterDividerTop = new Layer parent:background image:'images/filter-divider.png' y:162, index:10 height:2, width:1280 filterDividerBottom = new Layer parent:background y:226, index:10 image:'images/filter-divider.png' height:2, width:1280 filterDividerBottom.states = show: opacity:1 hide: opacity:0 extension = new Layer opacity:0, index:1 blackOverlay = new Layer width: 1280, height: 720 backgroundColor: 'rgba(0,0,0,0.9)' index: 0 blueOverlay = new Layer parent:eventParent height:720, width:1280 opacity:0.8 index:1 style: 'background' : 'linear-gradient(to bottom, rgba(0, 166, 255, 0.4) 0%, rgba(0, 166, 255, 0.1) 100%)' # style: # 'background' : '-webkit-linear-gradient( 270deg, rgba(255, 0, 0, 1) 0%, rgba(255, 255, 0, 1) 15%, rgba(0, 255, 0, 1) 30%, rgba(0, 255, 255, 1) 50%, rgba(0, 0, 255, 1) 65%, rgba(255, 0, 255, 1) 80%, rgba(255, 0, 0, 1) 100% )' #( 270deg, rgba( 0, 166, 255, 255 ) 0%, rgba( 0, 166, 255, 0 ) 100% ) menuHighlight = new Layer parent:filters x:0 width: 0 height:2 backgroundColor: youviewBlue #10px wider menuHighlightGlow = new Layer parent:menuHighlight width:0 height:4 blur:7 backgroundColor: youviewBlue menuHighlightGlow.bringToFront() legend = new Layer image:'images/legend.png' maxY:Screen.height+20 width:1280 height:114 opacity:0 showLegend = new Animation legend, opacity:1 duration:0.5 maxY:Screen.height hideLegend = showLegend.reverse() dumbVariable = 0 init = () -> fillRows() styleHighlight(1,0) fillDateTrack() captureKeys() blackOverlay.sendToBack() tvShow.sendToBack() nowline.bringToFront() init() Utils.interval 0.5, -> thisY = hY thisX = hX nowLineTimeout++ if nowLineTimeout == 6 nowline.x += 1 nowLineTimeout = 0 expansionTimeout = expansionTimeout + 1 if expansionTimeout == 2 and thisY >= 0 expansionCleverness(thisX,thisY) legendTimeout++ if legendTimeout == 4 showLegend.start() Canvas.image = 'https://struanfraser.co.uk/images/youview-back.jpg'
[ { "context": "il: {task}})->\n task.reset 'yes' if task.key is 'animalsPresent'\n task.reset 'incomplete' if task.key is 'allPen", "end": 310, "score": 0.9923002123832703, "start": 296, "tag": "KEY", "value": "animalsPresent" }, { "context": "resent'\n task.reset 'incomplete' if t...
task-defaults.coffee
zooniverse/penguinwatch
0
# Default the first question to 'yes' currentProject = require 'zooniverse-readymade/current-project' classifyPage = currentProject.classifyPages[0] {decisionTree} = classifyPage classifyPage.el.on decisionTree.LOAD_TASK, ({originalEvent: detail: {task}})-> task.reset 'yes' if task.key is 'animalsPresent' task.reset 'incomplete' if task.key is 'allPenguinsMarked'
118644
# Default the first question to 'yes' currentProject = require 'zooniverse-readymade/current-project' classifyPage = currentProject.classifyPages[0] {decisionTree} = classifyPage classifyPage.el.on decisionTree.LOAD_TASK, ({originalEvent: detail: {task}})-> task.reset 'yes' if task.key is '<KEY>' task.reset 'incomplete' if task.key is '<KEY>'
true
# Default the first question to 'yes' currentProject = require 'zooniverse-readymade/current-project' classifyPage = currentProject.classifyPages[0] {decisionTree} = classifyPage classifyPage.el.on decisionTree.LOAD_TASK, ({originalEvent: detail: {task}})-> task.reset 'yes' if task.key is 'PI:KEY:<KEY>END_PI' task.reset 'incomplete' if task.key is 'PI:KEY:<KEY>END_PI'
[ { "context": "VATE KEY BLOCK-----\n Version: GnuPG v1\n\n lQOYBFbgdCwBCADP7pEHzySjYHIlQK7T3XlqfFaot7VAgwmBUmXwFNRsYxGFj5sC\n qEvhcw3nGvhVOul9A5S3yDZCtEDMqZSFDXNNIptpbhJgEqae0stfmHzHNUJSz+3w\n ZE8Bvz1D5MU8YsMCUbt/wM/dBsp0EdbCS+zWIfM7Gzhb5vYOYx/wAeUxORCljQ6i\n E80iGKII7EYmpscIOjb6QgaM7wih...
packages/client-app/internal_packages/keybase/spec/pgp-key-store-spec.cjsx
cnheider/nylas-mail
24,369
{React, ReactTestUtils, DraftStore, Message} = require 'nylas-exports' pgp = require 'kbpgp' _ = require 'underscore' fs = require 'fs' Identity = require '../lib/identity' PGPKeyStore = require '../lib/pgp-key-store' describe "PGPKeyStore", -> beforeEach -> @TEST_KEY = """-----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v1 lQOYBFbgdCwBCADP7pEHzySjYHIlQK7T3XlqfFaot7VAgwmBUmXwFNRsYxGFj5sC qEvhcw3nGvhVOul9A5S3yDZCtEDMqZSFDXNNIptpbhJgEqae0stfmHzHNUJSz+3w ZE8Bvz1D5MU8YsMCUbt/wM/dBsp0EdbCS+zWIfM7Gzhb5vYOYx/wAeUxORCljQ6i E80iGKII7EYmpscIOjb6QgaM7wih6GT3GWFYOMRG0uKGDVGWgWQ3EJgdcJq6Dvmx GgrEQL7R8chtuLn9iyG3t5ZUfNvoH6PM7L7ei2ceMjxvLOfaHWNVKc+9YPeEOcvB uQi5NEqSEZOSqd1jPPaOiSTnIOCeVXXMyZVlABEBAAEAB/0Q2OWLWm8/hYr6FbmU lPdHd3eWB/x5k6Rrg/+aajWj6or65V3L41Lym13fAcJpNXLBnE6qbWBoGy685miQ NzzGXS12Z2K5wgkaCT5NKo/BnEEZcJt4xMfZ/mK6Y4jPkbj3MSQd/8NXxzsUGHXs HDa+StXoThZM6/O3yrRFwAGP8UhMVYOSwZB0u+DZ8EFaImqKJmznRvyNOaaGDrI5 cNdB4Xkk7L/tDxUxqc60WMQ49BEA9HW7miqymb3MEBA4Gd931pGYRM3hzQDhg+VI oGlw2Xl9YjUGWVHMyufKzxTYhWWHDSpfjSVikeKwqbJWVqZ0a9/4GghhQRMdo2ho AerpBADeXox+MRdbf2SgerxN4dPMBL5A5LD89Cu8AeY+6Ae1KlvGQFEOOQlW6Cwh R1Tqn1p8JFG8jr7zg/nbPcIvOH/F00Dozfe+BW4BPJ8uv1E0ON/p54Bnp/XaNlGM KyCDqRK+KDVpMXgP+rFK94+xLOuimMU3PhIDq623mezc8+u2CwQA72ELj49/OtqD 6VzEG6MKGfAOkW8l0xuxqo3SgLBU2E45zA9JYaocQ+z1fzFTUmMruFQaD1SxX7kr Ml1s0BBiiEh323Cf01y1DXWQhWtw0s5phSzfzgB5GFZV42xtyQ+qZqf20TihJ8/O b56J1tM7DsVXbVtcZdKRtUbRZ8vuOE8D/1oIuDT1a8Eqzl0KuS5VLOuVYvl8pbMc aRkPtSkG4+nRw3LTQb771M39HpjgEv2Jw9aACHsWZ8DnNtoc8DA7UUeAouCT+Ev4 u3o9LrQ/+A/NUSLwBibViflo/gsR5L8tYn51zhJ3573FucFJP9ej7JncSL9x615q Il2+Ry2pfUUZRj20OURha290YSBOZWxzb24gKFRlc3QgS2V5IEZvciBOMSBQbHVn aW4pIDxkYWtvdGFAbnlsYXMuY29tPokBOAQTAQIAIgUCVuB0LAIbAwYLCQgHAwIG FQgCCQoLBBYCAwECHgECF4AACgkQJgGhql9yqOCb5wgAqATlYC2ysjyUN66IfatW rZij5lbIcjZyq5an1fxW9J0ofxeOIQ2duqnwoLFoDS2lNz4/kFlOn8vyvApsSfzC +Gy1T46rc32CUBMjtD5Lh5fQ7fSNysii813MZAwfhdR0H6XO6kFj4RTJe4nzKnmM sSSBbS/kbl9ZWZ993gisun8/PyDO4/1Yon8BDHABaJRJD5rqd1ZwtMIZguSgipXu HqrdLpDxNUPr+YQ0C5r0kVJLFu0TVIz9grjV+MMCNVlDJvFla7vvRTdnym3HnbZo XBeq/8zEnFcDWQC9Gkl4TrcuIwUYvcaO9j5V/E2fN+3b7YQp/0iwjZCHe+BgK5Hd TJ0DmARW4HQsAQgAtSb1ove+EOJEspTwFP2gmnZ32SF6qGLcXkZkHJ7bYzudoKrQ rkYcs61foyyeH/UrvOdHWsEOFnekE44oA/y7dGZiHAUcuYrqxtEF7QhmbcK0aRKS JqmjO17rZ4Xz2MXsFxnGup5D94ZLxv2XktZX8EexMjdfU5Zdx1wu0GsMZX5Gj6AP lQb0E1KDDnFII2uRs32j6GuO5WZJk1hdvz0DSTaaJ2pY3/WtMiUEBap9qSRR8WIK kUO+TbzeogDXW10EiRyhIQadnfQTFjSVpGEos9b1k7zNNk/hb7yvlNL+pRY+8UcH zRRMjC9wv6V7xmVOF/GhdGLLwzs36lxCbeheWQARAQABAAf/Vua0qZQtUo4pJH48 WeV9uPuh7MCZxdN/IZ6lAfHXDtiXem7XIvMxa6R9H5sU1AHaFInieg/owTBtvo/Q dHE2P9WptQVizUNt8yhsrlP8RyVDRLCK+g8g5idXyFbDLrdr1X0hD39C3ahIC9K1 dtRqZTMPNybHDSMyI6P+NS9VSA4naigzzIzz4GLUgnzI/55M6QFcWxrnXc8B3XPQ QxerSL3UseuNNr6nRhYt5arPpD7YhgmRakib+guPnmD5ZIbHOVFqS6RCkNkQ91zJ nCo+o72gHbUDupEo8l/739k2SknWrNFt4S+mrvBM3c29cCnFaKQyRBNNGXtwmNnE Dwr8DQQAxvQ+6Ijh4so4mdlI4+UT0d50gYQcnjz6BLtcRfewpT/EadIb0OuVS1Eh MxM9QN5hXFKzT7GRS+nuk4NvrGr8aJ7mDPXzOHE/rnnAuikMuB1F13I8ELbya36B j5wTvOBBjtNkcA1e9wX+iN4PyBVpzRUZZY6y0Xcyp9DsQwVpMvcEAOkYAeg4UCfO PumYjdBRqcAuCKSQ8/UOrTOu5BDiIoyYBD3mrWSe61zZTuR7kb8/IkGHDTC7tLVZ vKzdkRinh+qISpjI5OHSsITBV1uh/iko+K2rKca8gonjQBsxeAPMZwvMfUROGKkS eXm/5sLUWlRtGkfVED1rYwUkE720tFUvBACGilgE7ezuoH7ZukyPPw9RziI7/CQp u0KhFTGzLMGJWfiGgMC7l1jnS0EJxvs3ZpBme//vsKCjPGVg3/OqOHqCY0p9Uqjt 7v8o7y62AMzHKEGuMubSzDZZalo0515HQilfwnOGTHN14693icg1W/daB8aGI+Uz cH3NziXnu23zc0VMiQEfBBgBAgAJBQJW4HQsAhsMAAoJECYBoapfcqjghFEH/ioJ c4jot40O3Xa0K9ZFXol2seUHIf5rLgvcnwAKEiibK81/cZzlL6uXpgxVA4GOgdw5 nfGVd7b9jB7S6aUKcVoLDmy47qmJkWvZ45cjgv+K+ZoV22IN0J9Hhhdnqe+QJd4A vIqb67gb9cw0xUDqcLdYywsXHoF9WkAYpIvBw4klHgd77XTzYz6xv4vVl469CPdk +1dlOKpCHTLh7t38StP/rSu4ZrAYGET0e2+Ayqj44VHS9VwEbR/D2xrbjo43URZB VsVlQKtXimFLpck1z0BPQ0NmRdEzRHQwP2WNYfxdNCeFAGDL4tpblBzw/vp/CFTO 217s2OKjpJqtpHPf2vY= =UY7Y -----END PGP PRIVATE KEY BLOCK-----""" # mock getKeyContents to get rid of all the fs.readFiles spyOn(PGPKeyStore, "getKeyContents").andCallFake( ({key, passphrase, callback}) => data = @TEST_KEY pgp.KeyManager.import_from_armored_pgp { armored: data }, (err, km) => expect(err).toEqual(null) if km.is_pgp_locked() expect(passphrase).toBeDefined() km.unlock_pgp { passphrase: passphrase }, (err) => expect(err).toEqual(null) key.key = km key.setTimeout() if callback? callback() ) # define an encrypted and an unencrypted message @unencryptedMsg = new Message({clientId: 'test', subject: 'Subject', body: '<p>Body</p>'}) body = """-----BEGIN PGP MESSAGE----- Version: Keybase OpenPGP v2.0.52 Comment: keybase.io/crypto wcBMA5nwa6GWVDOUAQf+MjiVRIBWJyM6The6/h2MgSJTDyrN9teFFJTizOvgHNnD W4EpEmmhShNyERI67qXhC03lFczu2Zp2Qofgs8YePIEv7wwb27/cviODsE42YJvX 1zGir+jBp81s9ZiF4dex6Ir9XfiZJlypI2QV2dHjO+5pstW+XhKIc1R5vKvoFTGI 1XmZtL3EgtKfj/HkPUkq2N0G5kAoB2MTTQuurfXm+3TRkftqesyTKlek652sFjCv nSF+LQ1GYq5hI4YaUBiHnZd7wKUgDrIh2rzbuGq+AHjrHdVLMfRTbN0Xsy3OWRcC 9uWU8Nln00Ly6KbTqPXKcBDcMrOJuoxYcpmLlhRds9JoAY7MyIsj87M2mkTtAtMK hqK0PPvJKfepV+eljDhQ7y0TQ0IvNtO5/pcY2CozbFJncm/ToxxZPNJueKRcz+EH M9uBvrWNTwfHj26g405gpRDN1T8CsY5ZeiaDHduIKnBWd4za0ak0Xfw= =1aPN -----END PGP MESSAGE-----""" @encryptedMsg = new Message({clientId: 'test2', subject: 'Subject', body: body}) # blow away the saved identities and set up a test pub/priv keypair PGPKeyStore._identities = {} pubIdent = new Identity({ addresses: ["benbitdiddle@icloud.com"] isPriv: false }) PGPKeyStore._identities[pubIdent.clientId] = pubIdent privIdent = new Identity({ addresses: ["benbitdiddle@icloud.com"] isPriv: true }) PGPKeyStore._identities[privIdent.clientId] = privIdent describe "when handling private keys", -> it 'should be able to retrieve and unlock a private key', -> expect(PGPKeyStore.privKeys().some((cv, index, array) => cv.hasOwnProperty("key"))).toBeFalsey key = PGPKeyStore.privKeys(address: "benbitdiddle@icloud.com", timed: false)[0] PGPKeyStore.getKeyContents(key: key, passphrase: "", callback: => expect(PGPKeyStore.privKeys({timed: false}).some((cv, index, array) => cv.hasOwnProperty("key"))).toBeTruthy ) it 'should not return a private key after its timeout has passed', -> expect(PGPKeyStore.privKeys({address: "benbitdiddle@icloud.com", timed: false}).length).toEqual(1) PGPKeyStore.privKeys({address: "benbitdiddle@icloud.com", timed: false})[0].timeout = Date.now() - 5 expect(PGPKeyStore.privKeys(address: "benbitdiddle@icloud.com", timed: true).length).toEqual(0) PGPKeyStore.privKeys({address: "benbitdiddle@icloud.com", timed: false})[0].setTimeout() it 'should only return the key(s) corresponding to a supplied email address', -> expect(PGPKeyStore.privKeys(address: "wrong@example.com", timed: true).length).toEqual(0) it 'should return all private keys when an address is not supplied', -> expect(PGPKeyStore.privKeys({timed: false}).length).toEqual(1) it 'should update an existing key when it is unlocked, not add a new one', -> timeout = PGPKeyStore.privKeys({address: "benbitdiddle@icloud.com", timed: false})[0].timeout PGPKeyStore.getKeyContents(key: PGPKeyStore.privKeys({timed: false})[0], passphrase: "", callback: => # expect no new keys to have been added expect(PGPKeyStore.privKeys({timed: false}).length).toEqual(1) # make sure the timeout is updated expect(timeout < PGPKeyStore.privKeys({address: "benbitdiddle@icloud.com", timed: false}).timeout) ) describe "when decrypting messages", -> xit 'should be able to decrypt a message', -> # TODO for some reason, the pgp.unbox has a problem with the message body runs( => spyOn(PGPKeyStore, 'trigger') PGPKeyStore.getKeyContents(key: PGPKeyStore.privKeys({timed: false})[0], passphrase: "", callback: => PGPKeyStore.decrypt(@encryptedMsg) ) ) waitsFor((=> PGPKeyStore.trigger.callCount > 0), 'message to decrypt') runs( => expect(_.findWhere(PGPKeyStore._msgCache, {clientId: @encryptedMsg.clientId})).toExist() ) it 'should be able to handle an unencrypted message', -> PGPKeyStore.decrypt(@unencryptedMsg) expect(_.findWhere(PGPKeyStore._msgCache, {clientId: @unencryptedMsg.clientId})).not.toBeDefined() it 'should be able to tell when a message has no encrypted component', -> expect(PGPKeyStore.hasEncryptedComponent(@unencryptedMsg)).not expect(PGPKeyStore.hasEncryptedComponent(@encryptedMsg)) it 'should be able to handle a message with no BEGIN PGP MESSAGE block', -> body = """Version: Keybase OpenPGP v2.0.52 Comment: keybase.io/crypto wcBMA5nwa6GWVDOUAQf+MjiVRIBWJyM6The6/h2MgSJTDyrN9teFFJTizOvgHNnD W4EpEmmhShNyERI67qXhC03lFczu2Zp2Qofgs8YePIEv7wwb27/cviODsE42YJvX 1zGir+jBp81s9ZiF4dex6Ir9XfiZJlypI2QV2dHjO+5pstW+XhKIc1R5vKvoFTGI 1XmZtL3EgtKfj/HkPUkq2N0G5kAoB2MTTQuurfXm+3TRkftqesyTKlek652sFjCv nSF+LQ1GYq5hI4YaUBiHnZd7wKUgDrIh2rzbuGq+AHjrHdVLMfRTbN0Xsy3OWRcC 9uWU8Nln00Ly6KbTqPXKcBDcMrOJuoxYcpmLlhRds9JoAY7MyIsj87M2mkTtAtMK hqK0PPvJKfepV+eljDhQ7y0TQ0IvNtO5/pcY2CozbFJncm/ToxxZPNJueKRcz+EH M9uBvrWNTwfHj26g405gpRDN1T8CsY5ZeiaDHduIKnBWd4za0ak0Xfw= =1aPN -----END PGP MESSAGE-----""" badMsg = new Message({clientId: 'test2', subject: 'Subject', body: body}) PGPKeyStore.getKeyContents(key: PGPKeyStore.privKeys({timed: false})[0], passphrase: "", callback: => PGPKeyStore.decrypt(badMsg) expect(_.findWhere(PGPKeyStore._msgCache, {clientId: badMsg.clientId})).not.toBeDefined() ) it 'should be able to handle a message with no END PGP MESSAGE block', -> body = """-----BEGIN PGP MESSAGE----- Version: Keybase OpenPGP v2.0.52 Comment: keybase.io/crypto wcBMA5nwa6GWVDOUAQf+MjiVRIBWJyM6The6/h2MgSJTDyrN9teFFJTizOvgHNnD W4EpEmmhShNyERI67qXhC03lFczu2Zp2Qofgs8YePIEv7wwb27/cviODsE42YJvX 1zGir+jBp81s9ZiF4dex6Ir9XfiZJlypI2QV2dHjO+5pstW+XhKIc1R5vKvoFTGI 1XmZtL3EgtKfj/HkPUkq2N0G5kAoB2MTTQuurfXm+3TRkftqesyTKlek652sFjCv nSF+LQ1GYq5hI4YaUBiHnZd7wKUgDrIh2rzbuGq+AHjrHdVLMfRTbN0Xsy3OWRcC 9uWU8Nln00Ly6KbTqPXKcBDcMrOJuoxYcpmLlhRds9JoAY7MyIsj87M2mkTtAtMK hqK0PPvJKfepV+eljDhQ7y0TQ0IvNtO5/pcY2CozbFJncm/ToxxZPNJueKRcz+EH M9uBvrWNTwfHj26g405gpRDN1T8CsY5ZeiaDHduIKnBWd4za0ak0Xfw= =1aPN""" badMsg = new Message({clientId: 'test2', subject: 'Subject', body: body}) PGPKeyStore.getKeyContents(key: PGPKeyStore.privKeys({timed: false})[0], passphrase: "", callback: => PGPKeyStore.decrypt(badMsg) expect(_.findWhere(PGPKeyStore._msgCache, {clientId: badMsg.clientId})).not.toBeDefined() ) it 'should not return a decrypted message which has timed out', -> PGPKeyStore._msgCache.push({clientId: "testID", body: "example body", timeout: Date.now()}) msg = new Message({clientId: "testID"}) expect(PGPKeyStore.getDecrypted(msg)).toEqual(null) it 'should return a decrypted message', -> timeout = Date.now() + (1000*60*60) PGPKeyStore._msgCache.push({clientId: "testID2", body: "example body", timeout: timeout}) msg = new Message({clientId: "testID2", body: "example body"}) expect(PGPKeyStore.getDecrypted(msg)).toEqual(msg.body) describe "when handling public keys", -> it "should immediately return a pre-cached key", -> expect(PGPKeyStore.pubKeys('benbitdiddle@icloud.com').length).toEqual(1)
191331
{React, ReactTestUtils, DraftStore, Message} = require 'nylas-exports' pgp = require 'kbpgp' _ = require 'underscore' fs = require 'fs' Identity = require '../lib/identity' PGPKeyStore = require '../lib/pgp-key-store' describe "PGPKeyStore", -> beforeEach -> @TEST_KEY = """-----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v1 <KEY> cNd<KEY>4<KEY> a<KEY>xk<KEY> =UY7Y -----END PGP PRIVATE KEY BLOCK-----""" # mock getKeyContents to get rid of all the fs.readFiles spyOn(PGPKeyStore, "getKeyContents").andCallFake( ({key, passphrase, callback}) => data = @TEST_KEY pgp.KeyManager.import_from_armored_pgp { armored: data }, (err, km) => expect(err).toEqual(null) if km.is_pgp_locked() expect(passphrase).toBeDefined() km.unlock_pgp { passphrase: <PASSWORD> }, (err) => expect(err).toEqual(null) key.key = km key.setTimeout() if callback? callback() ) # define an encrypted and an unencrypted message @unencryptedMsg = new Message({clientId: 'test', subject: 'Subject', body: '<p>Body</p>'}) body = """-----BEGIN PGP MESSAGE----- Version: Keybase OpenPGP v2.0.52 Comment: keybase.io/crypto <KEY> =1aPN -----END PGP MESSAGE-----""" @encryptedMsg = new Message({clientId: 'test2', subject: 'Subject', body: body}) # blow away the saved identities and set up a test pub/priv keypair PGPKeyStore._identities = {} pubIdent = new Identity({ addresses: ["<EMAIL>"] isPriv: false }) PGPKeyStore._identities[pubIdent.clientId] = pubIdent privIdent = new Identity({ addresses: ["<EMAIL>"] isPriv: true }) PGPKeyStore._identities[privIdent.clientId] = privIdent describe "when handling private keys", -> it 'should be able to retrieve and unlock a private key', -> expect(PGPKeyStore.privKeys().some((cv, index, array) => cv.hasOwnProperty("key"))).toBeFalsey key = PGPKeyStore.privKeys(address: "<EMAIL>", timed: false)[0] PGPKeyStore.getKeyContents(key: key, passphrase: "", callback: => expect(PGPKeyStore.privKeys({timed: false}).some((cv, index, array) => cv.hasOwnProperty("key"))).toBeTruthy ) it 'should not return a private key after its timeout has passed', -> expect(PGPKeyStore.privKeys({address: "<EMAIL>", timed: false}).length).toEqual(1) PGPKeyStore.privKeys({address: "<EMAIL>", timed: false})[0].timeout = Date.now() - 5 expect(PGPKeyStore.privKeys(address: "<EMAIL>", timed: true).length).toEqual(0) PGPKeyStore.privKeys({address: "<EMAIL>", timed: false})[0].setTimeout() it 'should only return the key(s) corresponding to a supplied email address', -> expect(PGPKeyStore.privKeys(address: "<EMAIL>", timed: true).length).toEqual(0) it 'should return all private keys when an address is not supplied', -> expect(PGPKeyStore.privKeys({timed: false}).length).toEqual(1) it 'should update an existing key when it is unlocked, not add a new one', -> timeout = PGPKeyStore.privKeys({address: "<EMAIL>", timed: false})[0].timeout PGPKeyStore.getKeyContents(key: PGPKeyStore.privKeys({timed: false})[0], passphrase: "", callback: => # expect no new keys to have been added expect(PGPKeyStore.privKeys({timed: false}).length).toEqual(1) # make sure the timeout is updated expect(timeout < PGPKeyStore.privKeys({address: "<EMAIL>", timed: false}).timeout) ) describe "when decrypting messages", -> xit 'should be able to decrypt a message', -> # TODO for some reason, the pgp.unbox has a problem with the message body runs( => spyOn(PGPKeyStore, 'trigger') PGPKeyStore.getKeyContents(key: PGPKeyStore.privKeys({timed: false})[0], passphrase: "", callback: => PGPKeyStore.decrypt(@encryptedMsg) ) ) waitsFor((=> PGPKeyStore.trigger.callCount > 0), 'message to decrypt') runs( => expect(_.findWhere(PGPKeyStore._msgCache, {clientId: @encryptedMsg.clientId})).toExist() ) it 'should be able to handle an unencrypted message', -> PGPKeyStore.decrypt(@unencryptedMsg) expect(_.findWhere(PGPKeyStore._msgCache, {clientId: @unencryptedMsg.clientId})).not.toBeDefined() it 'should be able to tell when a message has no encrypted component', -> expect(PGPKeyStore.hasEncryptedComponent(@unencryptedMsg)).not expect(PGPKeyStore.hasEncryptedComponent(@encryptedMsg)) it 'should be able to handle a message with no BEGIN PGP MESSAGE block', -> body = """Version: Keybase OpenPGP v2.0.52 Comment: keybase.io/crypto wcBMA5nwa6GWVDOUAQf+MjiVRIBWJyM6The6/h2MgSJTDyrN9teFFJTizOvgHNnD W4EpEmmhShNyERI67qXh<KEY> =1aPN -----END PGP MESSAGE-----""" badMsg = new Message({clientId: 'test2', subject: 'Subject', body: body}) PGPKeyStore.getKeyContents(key: PGPKeyStore.privKeys({timed: false})[0], passphrase: "", callback: => PGPKeyStore.decrypt(badMsg) expect(_.findWhere(PGPKeyStore._msgCache, {clientId: badMsg.clientId})).not.toBeDefined() ) it 'should be able to handle a message with no END PGP MESSAGE block', -> body = """-----BEGIN PGP MESSAGE----- Version: Keybase OpenPGP v2.0.52 Comment: keybase.io/crypto wcBMA5nwa6GWVDOUAQf+MjiVRIBWJyM6The6/h2MgSJTDyrN9teFFJTizOvgHNnD W4EpEmmhShNyERI67qXhC03l<KEY> =1aPN""" badMsg = new Message({clientId: 'test2', subject: 'Subject', body: body}) PGPKeyStore.getKeyContents(key: PGPKeyStore.privKeys({timed: false})[0], passphrase: "", callback: => PGPKeyStore.decrypt(badMsg) expect(_.findWhere(PGPKeyStore._msgCache, {clientId: badMsg.clientId})).not.toBeDefined() ) it 'should not return a decrypted message which has timed out', -> PGPKeyStore._msgCache.push({clientId: "testID", body: "example body", timeout: Date.now()}) msg = new Message({clientId: "testID"}) expect(PGPKeyStore.getDecrypted(msg)).toEqual(null) it 'should return a decrypted message', -> timeout = Date.now() + (1000*60*60) PGPKeyStore._msgCache.push({clientId: "testID2", body: "example body", timeout: timeout}) msg = new Message({clientId: "testID2", body: "example body"}) expect(PGPKeyStore.getDecrypted(msg)).toEqual(msg.body) describe "when handling public keys", -> it "should immediately return a pre-cached key", -> expect(PGPKeyStore.pubKeys('<EMAIL>').length).toEqual(1)
true
{React, ReactTestUtils, DraftStore, Message} = require 'nylas-exports' pgp = require 'kbpgp' _ = require 'underscore' fs = require 'fs' Identity = require '../lib/identity' PGPKeyStore = require '../lib/pgp-key-store' describe "PGPKeyStore", -> beforeEach -> @TEST_KEY = """-----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v1 PI:KEY:<KEY>END_PI cNdPI:KEY:<KEY>END_PI4PI:KEY:<KEY>END_PI aPI:KEY:<KEY>END_PIxkPI:KEY:<KEY>END_PI =UY7Y -----END PGP PRIVATE KEY BLOCK-----""" # mock getKeyContents to get rid of all the fs.readFiles spyOn(PGPKeyStore, "getKeyContents").andCallFake( ({key, passphrase, callback}) => data = @TEST_KEY pgp.KeyManager.import_from_armored_pgp { armored: data }, (err, km) => expect(err).toEqual(null) if km.is_pgp_locked() expect(passphrase).toBeDefined() km.unlock_pgp { passphrase: PI:PASSWORD:<PASSWORD>END_PI }, (err) => expect(err).toEqual(null) key.key = km key.setTimeout() if callback? callback() ) # define an encrypted and an unencrypted message @unencryptedMsg = new Message({clientId: 'test', subject: 'Subject', body: '<p>Body</p>'}) body = """-----BEGIN PGP MESSAGE----- Version: Keybase OpenPGP v2.0.52 Comment: keybase.io/crypto PI:KEY:<KEY>END_PI =1aPN -----END PGP MESSAGE-----""" @encryptedMsg = new Message({clientId: 'test2', subject: 'Subject', body: body}) # blow away the saved identities and set up a test pub/priv keypair PGPKeyStore._identities = {} pubIdent = new Identity({ addresses: ["PI:EMAIL:<EMAIL>END_PI"] isPriv: false }) PGPKeyStore._identities[pubIdent.clientId] = pubIdent privIdent = new Identity({ addresses: ["PI:EMAIL:<EMAIL>END_PI"] isPriv: true }) PGPKeyStore._identities[privIdent.clientId] = privIdent describe "when handling private keys", -> it 'should be able to retrieve and unlock a private key', -> expect(PGPKeyStore.privKeys().some((cv, index, array) => cv.hasOwnProperty("key"))).toBeFalsey key = PGPKeyStore.privKeys(address: "PI:EMAIL:<EMAIL>END_PI", timed: false)[0] PGPKeyStore.getKeyContents(key: key, passphrase: "", callback: => expect(PGPKeyStore.privKeys({timed: false}).some((cv, index, array) => cv.hasOwnProperty("key"))).toBeTruthy ) it 'should not return a private key after its timeout has passed', -> expect(PGPKeyStore.privKeys({address: "PI:EMAIL:<EMAIL>END_PI", timed: false}).length).toEqual(1) PGPKeyStore.privKeys({address: "PI:EMAIL:<EMAIL>END_PI", timed: false})[0].timeout = Date.now() - 5 expect(PGPKeyStore.privKeys(address: "PI:EMAIL:<EMAIL>END_PI", timed: true).length).toEqual(0) PGPKeyStore.privKeys({address: "PI:EMAIL:<EMAIL>END_PI", timed: false})[0].setTimeout() it 'should only return the key(s) corresponding to a supplied email address', -> expect(PGPKeyStore.privKeys(address: "PI:EMAIL:<EMAIL>END_PI", timed: true).length).toEqual(0) it 'should return all private keys when an address is not supplied', -> expect(PGPKeyStore.privKeys({timed: false}).length).toEqual(1) it 'should update an existing key when it is unlocked, not add a new one', -> timeout = PGPKeyStore.privKeys({address: "PI:EMAIL:<EMAIL>END_PI", timed: false})[0].timeout PGPKeyStore.getKeyContents(key: PGPKeyStore.privKeys({timed: false})[0], passphrase: "", callback: => # expect no new keys to have been added expect(PGPKeyStore.privKeys({timed: false}).length).toEqual(1) # make sure the timeout is updated expect(timeout < PGPKeyStore.privKeys({address: "PI:EMAIL:<EMAIL>END_PI", timed: false}).timeout) ) describe "when decrypting messages", -> xit 'should be able to decrypt a message', -> # TODO for some reason, the pgp.unbox has a problem with the message body runs( => spyOn(PGPKeyStore, 'trigger') PGPKeyStore.getKeyContents(key: PGPKeyStore.privKeys({timed: false})[0], passphrase: "", callback: => PGPKeyStore.decrypt(@encryptedMsg) ) ) waitsFor((=> PGPKeyStore.trigger.callCount > 0), 'message to decrypt') runs( => expect(_.findWhere(PGPKeyStore._msgCache, {clientId: @encryptedMsg.clientId})).toExist() ) it 'should be able to handle an unencrypted message', -> PGPKeyStore.decrypt(@unencryptedMsg) expect(_.findWhere(PGPKeyStore._msgCache, {clientId: @unencryptedMsg.clientId})).not.toBeDefined() it 'should be able to tell when a message has no encrypted component', -> expect(PGPKeyStore.hasEncryptedComponent(@unencryptedMsg)).not expect(PGPKeyStore.hasEncryptedComponent(@encryptedMsg)) it 'should be able to handle a message with no BEGIN PGP MESSAGE block', -> body = """Version: Keybase OpenPGP v2.0.52 Comment: keybase.io/crypto wcBMA5nwa6GWVDOUAQf+MjiVRIBWJyM6The6/h2MgSJTDyrN9teFFJTizOvgHNnD W4EpEmmhShNyERI67qXhPI:KEY:<KEY>END_PI =1aPN -----END PGP MESSAGE-----""" badMsg = new Message({clientId: 'test2', subject: 'Subject', body: body}) PGPKeyStore.getKeyContents(key: PGPKeyStore.privKeys({timed: false})[0], passphrase: "", callback: => PGPKeyStore.decrypt(badMsg) expect(_.findWhere(PGPKeyStore._msgCache, {clientId: badMsg.clientId})).not.toBeDefined() ) it 'should be able to handle a message with no END PGP MESSAGE block', -> body = """-----BEGIN PGP MESSAGE----- Version: Keybase OpenPGP v2.0.52 Comment: keybase.io/crypto wcBMA5nwa6GWVDOUAQf+MjiVRIBWJyM6The6/h2MgSJTDyrN9teFFJTizOvgHNnD W4EpEmmhShNyERI67qXhC03lPI:KEY:<KEY>END_PI =1aPN""" badMsg = new Message({clientId: 'test2', subject: 'Subject', body: body}) PGPKeyStore.getKeyContents(key: PGPKeyStore.privKeys({timed: false})[0], passphrase: "", callback: => PGPKeyStore.decrypt(badMsg) expect(_.findWhere(PGPKeyStore._msgCache, {clientId: badMsg.clientId})).not.toBeDefined() ) it 'should not return a decrypted message which has timed out', -> PGPKeyStore._msgCache.push({clientId: "testID", body: "example body", timeout: Date.now()}) msg = new Message({clientId: "testID"}) expect(PGPKeyStore.getDecrypted(msg)).toEqual(null) it 'should return a decrypted message', -> timeout = Date.now() + (1000*60*60) PGPKeyStore._msgCache.push({clientId: "testID2", body: "example body", timeout: timeout}) msg = new Message({clientId: "testID2", body: "example body"}) expect(PGPKeyStore.getDecrypted(msg)).toEqual(msg.body) describe "when handling public keys", -> it "should immediately return a pre-cached key", -> expect(PGPKeyStore.pubKeys('PI:EMAIL:<EMAIL>END_PI').length).toEqual(1)
[ { "context": "\n \n var aLink = linkPool.pop();\n aLink.name = \"Hello\";\n \n // User clicks aLink, alert shows \"Clicked", "end": 474, "score": 0.9898093938827515, "start": 469, "tag": "NAME", "value": "Hello" } ]
dom-node-pool.coffee
tdreyno/dom-node-pool
1
### A simple pool for reusing DOM nodes (to avoid stuttering) Usage: var onClick = function() { alert("Clicked " + this.name); }; var linkPool = new DOMNodePool({ tagName: "a", initialSize: 10, autoInsert: document.getElementById("my_links"), onPop: function(a) { a.addEventListener("click", onClick); }, onPush: function(a) { a.removeEventListener("click", onClick); } }); var aLink = linkPool.pop(); aLink.name = "Hello"; // User clicks aLink, alert shows "Clicked Hello" linkPool.push(aLink); ### class DOMNodePool constructor: (options={})-> { tagName: @tagName autoInsert: @autoInsert onGenerate: @onGenerate onInsert: @onInsert onPush: @onPush onPull: @onPull initialSize: initialSize } = options @tagName ?= "div" @autoInsert ?= document.body initialSize ?= 5 @onGenerate ?= (e) -> @onInsert ?= (e) -> e.style.visibility = "hidden" @onPush ?= (e) -> @onPull ?= (e) -> @_pool = [] @_generateNode() for i in [0...initialSize] _generateNode: -> elem = document.createElement(@tagName) @onGenerate(elem) @push(elem) if @autoInsert @onInsert(elem) @autoInsert.appendChild(elem) undefined pop: -> @_generateNode() if !@_pool.length @onPop(@_pool[@_pool.length-1]) @_pool.pop() push: (n) -> @onPush(n) @_pool.push(n) undefined
96541
### A simple pool for reusing DOM nodes (to avoid stuttering) Usage: var onClick = function() { alert("Clicked " + this.name); }; var linkPool = new DOMNodePool({ tagName: "a", initialSize: 10, autoInsert: document.getElementById("my_links"), onPop: function(a) { a.addEventListener("click", onClick); }, onPush: function(a) { a.removeEventListener("click", onClick); } }); var aLink = linkPool.pop(); aLink.name = "<NAME>"; // User clicks aLink, alert shows "Clicked Hello" linkPool.push(aLink); ### class DOMNodePool constructor: (options={})-> { tagName: @tagName autoInsert: @autoInsert onGenerate: @onGenerate onInsert: @onInsert onPush: @onPush onPull: @onPull initialSize: initialSize } = options @tagName ?= "div" @autoInsert ?= document.body initialSize ?= 5 @onGenerate ?= (e) -> @onInsert ?= (e) -> e.style.visibility = "hidden" @onPush ?= (e) -> @onPull ?= (e) -> @_pool = [] @_generateNode() for i in [0...initialSize] _generateNode: -> elem = document.createElement(@tagName) @onGenerate(elem) @push(elem) if @autoInsert @onInsert(elem) @autoInsert.appendChild(elem) undefined pop: -> @_generateNode() if !@_pool.length @onPop(@_pool[@_pool.length-1]) @_pool.pop() push: (n) -> @onPush(n) @_pool.push(n) undefined
true
### A simple pool for reusing DOM nodes (to avoid stuttering) Usage: var onClick = function() { alert("Clicked " + this.name); }; var linkPool = new DOMNodePool({ tagName: "a", initialSize: 10, autoInsert: document.getElementById("my_links"), onPop: function(a) { a.addEventListener("click", onClick); }, onPush: function(a) { a.removeEventListener("click", onClick); } }); var aLink = linkPool.pop(); aLink.name = "PI:NAME:<NAME>END_PI"; // User clicks aLink, alert shows "Clicked Hello" linkPool.push(aLink); ### class DOMNodePool constructor: (options={})-> { tagName: @tagName autoInsert: @autoInsert onGenerate: @onGenerate onInsert: @onInsert onPush: @onPush onPull: @onPull initialSize: initialSize } = options @tagName ?= "div" @autoInsert ?= document.body initialSize ?= 5 @onGenerate ?= (e) -> @onInsert ?= (e) -> e.style.visibility = "hidden" @onPush ?= (e) -> @onPull ?= (e) -> @_pool = [] @_generateNode() for i in [0...initialSize] _generateNode: -> elem = document.createElement(@tagName) @onGenerate(elem) @push(elem) if @autoInsert @onInsert(elem) @autoInsert.appendChild(elem) undefined pop: -> @_generateNode() if !@_pool.length @onPop(@_pool[@_pool.length-1]) @_pool.pop() push: (n) -> @onPush(n) @_pool.push(n) undefined
[ { "context": "per\n \n @class bkcore.threejs.Particles\n @author Thibaut 'BKcore' Despoulain <http://bkcore.com>\n###\nclass", "end": 91, "score": 0.9998752474784851, "start": 84, "tag": "NAME", "value": "Thibaut" }, { "context": "class bkcore.threejs.Particles\n @author Thibaut ...
webInterface/game/bkcore.coffee/threejs/Particles.coffee
ploh007/design-project
1,017
### Particle system wrapper/helper @class bkcore.threejs.Particles @author Thibaut 'BKcore' Despoulain <http://bkcore.com> ### class Particles ### Creates a new particle system using given parameters @param {Object{max, spawnRate, spawn, velocity, randomness, force, spawnRadius, life, friction, color, color2, tint, texture, size, blending, depthTest, transparent, opacity}} opts ### constructor: (opts)-> @black = new THREE.Color(0x000000) @white = new THREE.Color(0xffffff) @material = new THREE.ParticleBasicMaterial( color: opts.tint ? 0xffffff map: opts.texture ? null size: opts.size ? 4 blending: opts.blending ? THREE.AdditiveBlending depthTest: opts.depthTest ? false transparent: opts.transparent ? true vertexColors: true opacity: opts.opacity ? 1.0 sizeAttenuation: true ) @max = opts.max ? 1000 @spawnRate = opts.spawnRate ? 0 @spawn = opts.spawn ? new THREE.Vector3() @velocity = opts.velocity ? new THREE.Vector3() @randomness = opts.randomness ? new THREE.Vector3() @force = opts.force ? new THREE.Vector3() @spawnRadius = opts.spawnRadius ? new THREE.Vector3() @life = opts.life ? 60 @ageing = 1 / @life @friction = opts.friction ? 1.0 @color = new THREE.Color(opts.color ? 0xffffff) @color2 = if opts.color2? then new THREE.Color(opts.color2) else null @position = opts.position ? new THREE.Vector3() @rotation = opts.rotation ? new THREE.Vector3() @sort = opts.sort ? false @pool = [] @buffer = [] @geometry = null @system = null @build() ### Emits given number of particles @param int count ### emit: (count)-> emitable = Math.min(count, @pool.length) for i in [0..emitable] p = @pool.pop() p.available = false p.position.copy(@spawn).addSelf( @randomVector().multiplySelf(@spawnRadius) ) p.velocity.copy(@velocity).addSelf( @randomVector().multiplySelf(@randomness) ) p.force.copy(@force) p.basecolor.copy(@color) if @color2? p.basecolor.lerpSelf(@color2, Math.random()) p.life = 1.0 ### @private ### build: ()-> @geometry = new THREE.Geometry() @geometry.dynamic = true @pool = [] @buffer = [] for i in [0..@max] p = new bkcore.threejs.Particle() @pool.push(p) @buffer.push(p) @geometry.vertices.push(p.position) @geometry.colors.push(p.color) @system = new THREE.ParticleSystem(@geometry, @material) @system.position = @position @system.rotation = @rotation @system.sort = @sort ### @private ### randomVector: ()-> return new THREE.Vector3( Math.random()*2-1, Math.random()*2-1, Math.random()*2-1 ) ### Updates particles (should be call in a RAF loop) @param float dt time delta ~1.0 ### update: (dt)-> df = new THREE.Vector3() dv = new THREE.Vector3() for i in [0..@buffer.length] p = @buffer[i] continue if p.available p.life -= @ageing if p.life <= 0 p.reset() @pool.push(p) continue l = if p.life > 0.5 then 1.0 else p.life + 0.5 p.color.setRGB( l * p.basecolor.r, l * p.basecolor.g, l * p.basecolor.b ) if @friction != 1.0 p.velocity.multiplyScalar(@friction) df.copy(p.force).multiplyScalar(dt) p.velocity.addSelf(df) dv.copy(p.velocity).multiplyScalar(dt) p.position.addSelf(dv) if @spawnRate > 0 @emit(@spawnRate) @geometry.verticesNeedUpdate = true @geometry.colorsNeedUpdate = true ### Particle sub class @class bkcore.threejs.Particle @author Thibaut 'BKcore' Despoulain <http://bkcore.com> ### class Particle constructor: ()-> @position = new THREE.Vector3(-10000,-10000,-10000) @velocity = new THREE.Vector3() @force = new THREE.Vector3() @color = new THREE.Color(0x000000) @basecolor = new THREE.Color(0x000000) @life = 0.0 @available = true reset: ()-> @position.set(0,-100000,0) @velocity.set(0,0,0) @force.set(0,0,0) @color.setRGB(0,0,0) @basecolor.setRGB(0,0,0) @life = 0.0 @available = true ### Exports @package bkcore.threejs ### exports = exports ? @ exports.bkcore ||= {} exports.bkcore.threejs ||= {} exports.bkcore.threejs.Particle = Particle exports.bkcore.threejs.Particles = Particles
28009
### Particle system wrapper/helper @class bkcore.threejs.Particles @author <NAME> 'BKcore' <NAME> <http://bkcore.com> ### class Particles ### Creates a new particle system using given parameters @param {Object{max, spawnRate, spawn, velocity, randomness, force, spawnRadius, life, friction, color, color2, tint, texture, size, blending, depthTest, transparent, opacity}} opts ### constructor: (opts)-> @black = new THREE.Color(0x000000) @white = new THREE.Color(0xffffff) @material = new THREE.ParticleBasicMaterial( color: opts.tint ? 0xffffff map: opts.texture ? null size: opts.size ? 4 blending: opts.blending ? THREE.AdditiveBlending depthTest: opts.depthTest ? false transparent: opts.transparent ? true vertexColors: true opacity: opts.opacity ? 1.0 sizeAttenuation: true ) @max = opts.max ? 1000 @spawnRate = opts.spawnRate ? 0 @spawn = opts.spawn ? new THREE.Vector3() @velocity = opts.velocity ? new THREE.Vector3() @randomness = opts.randomness ? new THREE.Vector3() @force = opts.force ? new THREE.Vector3() @spawnRadius = opts.spawnRadius ? new THREE.Vector3() @life = opts.life ? 60 @ageing = 1 / @life @friction = opts.friction ? 1.0 @color = new THREE.Color(opts.color ? 0xffffff) @color2 = if opts.color2? then new THREE.Color(opts.color2) else null @position = opts.position ? new THREE.Vector3() @rotation = opts.rotation ? new THREE.Vector3() @sort = opts.sort ? false @pool = [] @buffer = [] @geometry = null @system = null @build() ### Emits given number of particles @param int count ### emit: (count)-> emitable = Math.min(count, @pool.length) for i in [0..emitable] p = @pool.pop() p.available = false p.position.copy(@spawn).addSelf( @randomVector().multiplySelf(@spawnRadius) ) p.velocity.copy(@velocity).addSelf( @randomVector().multiplySelf(@randomness) ) p.force.copy(@force) p.basecolor.copy(@color) if @color2? p.basecolor.lerpSelf(@color2, Math.random()) p.life = 1.0 ### @private ### build: ()-> @geometry = new THREE.Geometry() @geometry.dynamic = true @pool = [] @buffer = [] for i in [0..@max] p = new bkcore.threejs.Particle() @pool.push(p) @buffer.push(p) @geometry.vertices.push(p.position) @geometry.colors.push(p.color) @system = new THREE.ParticleSystem(@geometry, @material) @system.position = @position @system.rotation = @rotation @system.sort = @sort ### @private ### randomVector: ()-> return new THREE.Vector3( Math.random()*2-1, Math.random()*2-1, Math.random()*2-1 ) ### Updates particles (should be call in a RAF loop) @param float dt time delta ~1.0 ### update: (dt)-> df = new THREE.Vector3() dv = new THREE.Vector3() for i in [0..@buffer.length] p = @buffer[i] continue if p.available p.life -= @ageing if p.life <= 0 p.reset() @pool.push(p) continue l = if p.life > 0.5 then 1.0 else p.life + 0.5 p.color.setRGB( l * p.basecolor.r, l * p.basecolor.g, l * p.basecolor.b ) if @friction != 1.0 p.velocity.multiplyScalar(@friction) df.copy(p.force).multiplyScalar(dt) p.velocity.addSelf(df) dv.copy(p.velocity).multiplyScalar(dt) p.position.addSelf(dv) if @spawnRate > 0 @emit(@spawnRate) @geometry.verticesNeedUpdate = true @geometry.colorsNeedUpdate = true ### Particle sub class @class bkcore.threejs.Particle @author <NAME> 'BKcore' <NAME> <http://bkcore.com> ### class Particle constructor: ()-> @position = new THREE.Vector3(-10000,-10000,-10000) @velocity = new THREE.Vector3() @force = new THREE.Vector3() @color = new THREE.Color(0x000000) @basecolor = new THREE.Color(0x000000) @life = 0.0 @available = true reset: ()-> @position.set(0,-100000,0) @velocity.set(0,0,0) @force.set(0,0,0) @color.setRGB(0,0,0) @basecolor.setRGB(0,0,0) @life = 0.0 @available = true ### Exports @package bkcore.threejs ### exports = exports ? @ exports.bkcore ||= {} exports.bkcore.threejs ||= {} exports.bkcore.threejs.Particle = Particle exports.bkcore.threejs.Particles = Particles
true
### Particle system wrapper/helper @class bkcore.threejs.Particles @author PI:NAME:<NAME>END_PI 'BKcore' PI:NAME:<NAME>END_PI <http://bkcore.com> ### class Particles ### Creates a new particle system using given parameters @param {Object{max, spawnRate, spawn, velocity, randomness, force, spawnRadius, life, friction, color, color2, tint, texture, size, blending, depthTest, transparent, opacity}} opts ### constructor: (opts)-> @black = new THREE.Color(0x000000) @white = new THREE.Color(0xffffff) @material = new THREE.ParticleBasicMaterial( color: opts.tint ? 0xffffff map: opts.texture ? null size: opts.size ? 4 blending: opts.blending ? THREE.AdditiveBlending depthTest: opts.depthTest ? false transparent: opts.transparent ? true vertexColors: true opacity: opts.opacity ? 1.0 sizeAttenuation: true ) @max = opts.max ? 1000 @spawnRate = opts.spawnRate ? 0 @spawn = opts.spawn ? new THREE.Vector3() @velocity = opts.velocity ? new THREE.Vector3() @randomness = opts.randomness ? new THREE.Vector3() @force = opts.force ? new THREE.Vector3() @spawnRadius = opts.spawnRadius ? new THREE.Vector3() @life = opts.life ? 60 @ageing = 1 / @life @friction = opts.friction ? 1.0 @color = new THREE.Color(opts.color ? 0xffffff) @color2 = if opts.color2? then new THREE.Color(opts.color2) else null @position = opts.position ? new THREE.Vector3() @rotation = opts.rotation ? new THREE.Vector3() @sort = opts.sort ? false @pool = [] @buffer = [] @geometry = null @system = null @build() ### Emits given number of particles @param int count ### emit: (count)-> emitable = Math.min(count, @pool.length) for i in [0..emitable] p = @pool.pop() p.available = false p.position.copy(@spawn).addSelf( @randomVector().multiplySelf(@spawnRadius) ) p.velocity.copy(@velocity).addSelf( @randomVector().multiplySelf(@randomness) ) p.force.copy(@force) p.basecolor.copy(@color) if @color2? p.basecolor.lerpSelf(@color2, Math.random()) p.life = 1.0 ### @private ### build: ()-> @geometry = new THREE.Geometry() @geometry.dynamic = true @pool = [] @buffer = [] for i in [0..@max] p = new bkcore.threejs.Particle() @pool.push(p) @buffer.push(p) @geometry.vertices.push(p.position) @geometry.colors.push(p.color) @system = new THREE.ParticleSystem(@geometry, @material) @system.position = @position @system.rotation = @rotation @system.sort = @sort ### @private ### randomVector: ()-> return new THREE.Vector3( Math.random()*2-1, Math.random()*2-1, Math.random()*2-1 ) ### Updates particles (should be call in a RAF loop) @param float dt time delta ~1.0 ### update: (dt)-> df = new THREE.Vector3() dv = new THREE.Vector3() for i in [0..@buffer.length] p = @buffer[i] continue if p.available p.life -= @ageing if p.life <= 0 p.reset() @pool.push(p) continue l = if p.life > 0.5 then 1.0 else p.life + 0.5 p.color.setRGB( l * p.basecolor.r, l * p.basecolor.g, l * p.basecolor.b ) if @friction != 1.0 p.velocity.multiplyScalar(@friction) df.copy(p.force).multiplyScalar(dt) p.velocity.addSelf(df) dv.copy(p.velocity).multiplyScalar(dt) p.position.addSelf(dv) if @spawnRate > 0 @emit(@spawnRate) @geometry.verticesNeedUpdate = true @geometry.colorsNeedUpdate = true ### Particle sub class @class bkcore.threejs.Particle @author PI:NAME:<NAME>END_PI 'BKcore' PI:NAME:<NAME>END_PI <http://bkcore.com> ### class Particle constructor: ()-> @position = new THREE.Vector3(-10000,-10000,-10000) @velocity = new THREE.Vector3() @force = new THREE.Vector3() @color = new THREE.Color(0x000000) @basecolor = new THREE.Color(0x000000) @life = 0.0 @available = true reset: ()-> @position.set(0,-100000,0) @velocity.set(0,0,0) @force.set(0,0,0) @color.setRGB(0,0,0) @basecolor.setRGB(0,0,0) @life = 0.0 @available = true ### Exports @package bkcore.threejs ### exports = exports ? @ exports.bkcore ||= {} exports.bkcore.threejs ||= {} exports.bkcore.threejs.Particle = Particle exports.bkcore.threejs.Particles = Particles
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999114274978638, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" }, { "context": "comments.get(@props.comment.parentId)\n user = @userFor(@...
resources/assets/coffee/react/_components/comment.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import ClickToCopy from 'click-to-copy' import { CommentEditor } from 'comment-editor' import { CommentShowMore } from 'comment-show-more' import DeletedCommentsCount from 'deleted-comments-count' import { Observer } from 'mobx-react' import core from 'osu-core-singleton' import * as React from 'react' import { a, button, div, span, textarea } from 'react-dom-factories' import { ReportReportable } from 'report-reportable' import { ShowMoreLink } from 'show-more-link' import { Spinner } from 'spinner' import { UserAvatar } from 'user-avatar' el = React.createElement deletedUser = username: osu.trans('users.deleted') commentableMetaStore = core.dataStore.commentableMetaStore store = core.dataStore.commentStore userStore = core.dataStore.userStore uiState = core.dataStore.uiState export class Comment extends React.PureComponent MAX_DEPTH = 6 makePreviewElement = document.createElement('div') makePreview = (comment) -> if comment.isDeleted osu.trans('comments.deleted') else makePreviewElement.innerHTML = comment.messageHtml _.truncate makePreviewElement.textContent, length: 100 constructor: (props) -> super props @xhr = {} @loadMoreRef = React.createRef() if osu.isMobile() # There's no indentation on mobile so don't expand by default otherwise it will be confusing. expandReplies = false else if @props.comment.isDeleted expandReplies = false else if @props.expandReplies? expandReplies = @props.expandReplies else children = uiState.getOrderedCommentsByParentId(@props.comment.id) # Collapse if either no children is loaded or current level doesn't add indentation. expandReplies = children?.length > 0 && @props.depth < MAX_DEPTH @state = postingVote: false editing: false showNewReply: false expandReplies: expandReplies componentWillUnmount: => xhr?.abort() for own _name, xhr of @xhr render: => el Observer, null, () => @children = uiState.getOrderedCommentsByParentId(@props.comment.id) ? [] parent = store.comments.get(@props.comment.parentId) user = @userFor(@props.comment) meta = commentableMetaStore.get(@props.comment.commentableType, @props.comment.commentableId) modifiers = @props.modifiers?[..] ? [] modifiers.push 'top' if @props.depth == 0 repliesClass = 'comment__replies' repliesClass += ' comment__replies--indented' if @props.depth < MAX_DEPTH repliesClass += ' comment__replies--hidden' if !@state.expandReplies div className: osu.classWithModifiers 'comment', modifiers @renderRepliesToggle() @renderCommentableMeta(meta) div className: "comment__main #{if @props.comment.isDeleted then 'comment__main--deleted' else ''}", if @props.comment.canHaveVote div className: 'comment__float-container comment__float-container--left hidden-xs', @renderVoteButton() @renderUserAvatar user div className: 'comment__container', div className: 'comment__row comment__row--header', @renderUsername user @renderOwnerBadge(meta) if @props.comment.pinned span className: 'comment__row-item comment__row-item--pinned' span className: 'fa fa-thumbtack' ' ' osu.trans 'comments.pinned' if parent? span className: 'comment__row-item comment__row-item--parent' @parentLink(parent) if @props.comment.isDeleted span className: 'comment__row-item comment__row-item--deleted' osu.trans('comments.deleted') if @state.editing div className: 'comment__editor', el CommentEditor, id: @props.comment.id message: @props.comment.message modifiers: @props.modifiers close: @closeEdit else if @props.comment.messageHtml? div className: 'comment__message', dangerouslySetInnerHTML: __html: @props.comment.messageHtml div className: 'comment__row comment__row--footer', if @props.comment.canHaveVote div className: 'comment__row-item visible-xs' @renderVoteText() div className: 'comment__row-item comment__row-item--info' dangerouslySetInnerHTML: __html: osu.timeago(@props.comment.createdAt) @renderPermalink() @renderReplyButton() @renderEdit() @renderRestore() @renderDelete() @renderPin() @renderReport() @renderEditedBy() @renderRepliesText() @renderReplyBox() if @props.comment.repliesCount > 0 div className: repliesClass @children.map @renderComment el DeletedCommentsCount, { comments: @children, showDeleted: uiState.comments.isShowDeleted } el CommentShowMore, parent: @props.comment comments: @children total: @props.comment.repliesCount modifiers: @props.modifiers label: osu.trans('comments.load_replies') if @children.length == 0 ref: @loadMoreRef renderComment: (comment) => comment = store.comments.get(comment.id) return null if comment.isDeleted && !uiState.comments.isShowDeleted el Comment, key: comment.id comment: comment depth: @props.depth + 1 parent: @props.comment modifiers: @props.modifiers expandReplies: @props.expandReplies renderDelete: => if !@props.comment.isDeleted && @props.comment.canDelete div className: 'comment__row-item', button type: 'button' className: 'comment__action' onClick: @delete osu.trans('common.buttons.delete') renderPin: => if @props.comment.canPin div className: 'comment__row-item', button type: 'button' className: 'comment__action' onClick: @togglePinned osu.trans 'common.buttons.' + if @props.comment.pinned then 'unpin' else 'pin' renderEdit: => if @props.comment.canEdit div className: 'comment__row-item', button type: 'button' className: "comment__action #{if @state.editing then 'comment__action--active' else ''}" onClick: @toggleEdit osu.trans('common.buttons.edit') renderEditedBy: => if !@props.comment.isDeleted && @props.comment.isEdited editor = userStore.get(@props.comment.editedById) div className: 'comment__row-item comment__row-item--info' dangerouslySetInnerHTML: __html: osu.trans 'comments.edited', timeago: osu.timeago(@props.comment.editedAt) user: if editor.id? osu.link(laroute.route('users.show', user: editor.id), editor.username, classNames: ['comment__link']) else _.escape editor.username renderOwnerBadge: (meta) => return null unless @props.comment.userId == meta.owner_id div className: 'comment__row-item', div className: 'comment__owner-badge', meta.owner_title renderPermalink: => div className: 'comment__row-item', span className: 'comment__action comment__action--permalink' el ClickToCopy, value: laroute.route('comments.show', comment: @props.comment.id) label: osu.trans 'common.buttons.permalink' valueAsUrl: true renderRepliesText: => return if @props.comment.repliesCount == 0 if !@state.expandReplies && @children.length == 0 callback = @loadReplies label = osu.trans('comments.load_replies') else callback = @toggleReplies label = osu.transChoice('comments.replies_count', @props.comment.repliesCount) div className: 'comment__row-item comment__row-item--replies', el ShowMoreLink, direction: if @state.expandReplies then 'up' else 'down' hasMore: true label: label callback: callback modifiers: ['comment-replies'] renderRepliesToggle: => if @props.depth == 0 && @children.length > 0 div className: 'comment__float-container comment__float-container--right', button className: 'comment__top-show-replies' type: 'button' onClick: @toggleReplies span className: "fas #{if @state.expandReplies then 'fa-angle-up' else 'fa-angle-down'}" renderReplyBox: => if @state.showNewReply div className: 'comment__reply-box', el CommentEditor, close: @closeNewReply modifiers: @props.modifiers onPosted: @handleReplyPosted parent: @props.comment renderReplyButton: => if !@props.comment.isDeleted div className: 'comment__row-item', button type: 'button' className: "comment__action #{if @state.showNewReply then 'comment__action--active' else ''}" onClick: @toggleNewReply osu.trans('common.buttons.reply') renderReport: => if @props.comment.canReport div className: 'comment__row-item', el ReportReportable, className: 'comment__action' reportableId: @props.comment.id reportableType: 'comment' user: @userFor(@props.comment) renderRestore: => if @props.comment.isDeleted && @props.comment.canRestore div className: 'comment__row-item', button type: 'button' className: 'comment__action' onClick: @restore osu.trans('common.buttons.restore') renderUserAvatar: (user) => if user.id? a className: 'comment__avatar js-usercard' 'data-user-id': user.id href: laroute.route('users.show', user: user.id) el UserAvatar, user: user, modifiers: ['full-circle'] else span className: 'comment__avatar' el UserAvatar, user: user, modifiers: ['full-circle'] renderUsername: (user) => if user.id? a 'data-user-id': user.id href: laroute.route('users.show', user: user.id) className: 'js-usercard comment__row-item comment__row-item--username comment__row-item--username-link' user.username else span className: 'comment__row-item comment__row-item--username' user.username # mobile vote button renderVoteButton: => className = osu.classWithModifiers('comment-vote', @props.modifiers) className += ' comment-vote--posting' if @state.postingVote if @hasVoted() className += ' comment-vote--on' hover = null else className += ' comment-vote--off' hover = div className: 'comment-vote__hover', '+1' button className: className type: 'button' onClick: @voteToggle disabled: @state.postingVote || !@props.comment.canVote span className: 'comment-vote__text', "+#{osu.formatNumberSuffixed(@props.comment.votesCount, null, maximumFractionDigits: 1)}" if @state.postingVote span className: 'comment-vote__spinner', el Spinner hover renderVoteText: => className = 'comment__action' className += ' comment__action--active' if @hasVoted() button className: className type: 'button' onClick: @voteToggle disabled: @state.postingVote "+#{osu.formatNumberSuffixed(@props.comment.votesCount, null, maximumFractionDigits: 1)}" renderCommentableMeta: (meta) => return unless @props.showCommentableMeta if meta.url component = a params = href: meta.url className: 'comment__link' else component = span params = null div className: 'comment__commentable-meta', if @props.comment.commentableType? span className: 'comment__commentable-meta-type', span className: 'comment__commentable-meta-icon fas fa-comment' ' ' osu.trans("comments.commentable_name.#{@props.comment.commentableType}") component params, meta.title hasVoted: => store.userVotes.has(@props.comment.id) delete: => return unless confirm(osu.trans('common.confirmation')) @xhr.delete?.abort() @xhr.delete = $.ajax laroute.route('comments.destroy', comment: @props.comment.id), method: 'DELETE' .done (data) => $.publish 'comment:updated', data .fail (xhr, status) => return if status == 'abort' osu.ajaxError xhr togglePinned: => return unless @props.comment.canPin @xhr.pin?.abort() @xhr.pin = $.ajax laroute.route('comments.pin', comment: @props.comment.id), method: if @props.comment.pinned then 'DELETE' else 'POST' .done (data) => $.publish 'comment:updated', data .fail (xhr, status) => return if status == 'abort' osu.ajaxError xhr handleReplyPosted: (type) => @setState expandReplies: true if type == 'reply' toggleEdit: => @setState editing: !@state.editing closeEdit: => @setState editing: false loadReplies: => @loadMoreRef.current?.load() @toggleReplies() parentLink: (parent) => props = title: makePreview(parent) if @props.linkParent component = a props.href = laroute.route('comments.show', comment: parent.id) props.className = 'comment__link' else component = span component props, span className: 'fas fa-reply' ' ' @userFor(parent).username userFor: (comment) => user = userStore.get(comment.userId)?.toJSON() if user? user else if comment.legacyName? username: comment.legacyName else deletedUser restore: => @xhr.restore?.abort() @xhr.restore = $.ajax laroute.route('comments.restore', comment: @props.comment.id), method: 'POST' .done (data) => $.publish 'comment:updated', data .fail (xhr, status) => return if status == 'abort' osu.ajaxError xhr toggleNewReply: => @setState showNewReply: !@state.showNewReply voteToggle: (e) => target = e.target if !currentUser.id? userLogin.show target return @setState postingVote: true if @hasVoted() method = 'DELETE' storeMethod = 'removeUserVote' else method = 'POST' storeMethod = 'addUserVote' @xhr.vote?.abort() @xhr.vote = $.ajax laroute.route('comments.vote', comment: @props.comment.id), method: method .always => @setState postingVote: false .done (data) => $.publish 'comment:updated', data store[storeMethod](@props.comment) .fail (xhr, status) => return if status == 'abort' return $(target).trigger('ajax:error', [xhr, status]) if xhr.status == 401 osu.ajaxError xhr closeNewReply: => @setState showNewReply: false toggleReplies: => @setState expandReplies: !@state.expandReplies
216958
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import ClickToCopy from 'click-to-copy' import { CommentEditor } from 'comment-editor' import { CommentShowMore } from 'comment-show-more' import DeletedCommentsCount from 'deleted-comments-count' import { Observer } from 'mobx-react' import core from 'osu-core-singleton' import * as React from 'react' import { a, button, div, span, textarea } from 'react-dom-factories' import { ReportReportable } from 'report-reportable' import { ShowMoreLink } from 'show-more-link' import { Spinner } from 'spinner' import { UserAvatar } from 'user-avatar' el = React.createElement deletedUser = username: osu.trans('users.deleted') commentableMetaStore = core.dataStore.commentableMetaStore store = core.dataStore.commentStore userStore = core.dataStore.userStore uiState = core.dataStore.uiState export class Comment extends React.PureComponent MAX_DEPTH = 6 makePreviewElement = document.createElement('div') makePreview = (comment) -> if comment.isDeleted osu.trans('comments.deleted') else makePreviewElement.innerHTML = comment.messageHtml _.truncate makePreviewElement.textContent, length: 100 constructor: (props) -> super props @xhr = {} @loadMoreRef = React.createRef() if osu.isMobile() # There's no indentation on mobile so don't expand by default otherwise it will be confusing. expandReplies = false else if @props.comment.isDeleted expandReplies = false else if @props.expandReplies? expandReplies = @props.expandReplies else children = uiState.getOrderedCommentsByParentId(@props.comment.id) # Collapse if either no children is loaded or current level doesn't add indentation. expandReplies = children?.length > 0 && @props.depth < MAX_DEPTH @state = postingVote: false editing: false showNewReply: false expandReplies: expandReplies componentWillUnmount: => xhr?.abort() for own _name, xhr of @xhr render: => el Observer, null, () => @children = uiState.getOrderedCommentsByParentId(@props.comment.id) ? [] parent = store.comments.get(@props.comment.parentId) user = @userFor(@props.comment) meta = commentableMetaStore.get(@props.comment.commentableType, @props.comment.commentableId) modifiers = @props.modifiers?[..] ? [] modifiers.push 'top' if @props.depth == 0 repliesClass = 'comment__replies' repliesClass += ' comment__replies--indented' if @props.depth < MAX_DEPTH repliesClass += ' comment__replies--hidden' if !@state.expandReplies div className: osu.classWithModifiers 'comment', modifiers @renderRepliesToggle() @renderCommentableMeta(meta) div className: "comment__main #{if @props.comment.isDeleted then 'comment__main--deleted' else ''}", if @props.comment.canHaveVote div className: 'comment__float-container comment__float-container--left hidden-xs', @renderVoteButton() @renderUserAvatar user div className: 'comment__container', div className: 'comment__row comment__row--header', @renderUsername user @renderOwnerBadge(meta) if @props.comment.pinned span className: 'comment__row-item comment__row-item--pinned' span className: 'fa fa-thumbtack' ' ' osu.trans 'comments.pinned' if parent? span className: 'comment__row-item comment__row-item--parent' @parentLink(parent) if @props.comment.isDeleted span className: 'comment__row-item comment__row-item--deleted' osu.trans('comments.deleted') if @state.editing div className: 'comment__editor', el CommentEditor, id: @props.comment.id message: @props.comment.message modifiers: @props.modifiers close: @closeEdit else if @props.comment.messageHtml? div className: 'comment__message', dangerouslySetInnerHTML: __html: @props.comment.messageHtml div className: 'comment__row comment__row--footer', if @props.comment.canHaveVote div className: 'comment__row-item visible-xs' @renderVoteText() div className: 'comment__row-item comment__row-item--info' dangerouslySetInnerHTML: __html: osu.timeago(@props.comment.createdAt) @renderPermalink() @renderReplyButton() @renderEdit() @renderRestore() @renderDelete() @renderPin() @renderReport() @renderEditedBy() @renderRepliesText() @renderReplyBox() if @props.comment.repliesCount > 0 div className: repliesClass @children.map @renderComment el DeletedCommentsCount, { comments: @children, showDeleted: uiState.comments.isShowDeleted } el CommentShowMore, parent: @props.comment comments: @children total: @props.comment.repliesCount modifiers: @props.modifiers label: osu.trans('comments.load_replies') if @children.length == 0 ref: @loadMoreRef renderComment: (comment) => comment = store.comments.get(comment.id) return null if comment.isDeleted && !uiState.comments.isShowDeleted el Comment, key: comment.id comment: comment depth: @props.depth + 1 parent: @props.comment modifiers: @props.modifiers expandReplies: @props.expandReplies renderDelete: => if !@props.comment.isDeleted && @props.comment.canDelete div className: 'comment__row-item', button type: 'button' className: 'comment__action' onClick: @delete osu.trans('common.buttons.delete') renderPin: => if @props.comment.canPin div className: 'comment__row-item', button type: 'button' className: 'comment__action' onClick: @togglePinned osu.trans 'common.buttons.' + if @props.comment.pinned then 'unpin' else 'pin' renderEdit: => if @props.comment.canEdit div className: 'comment__row-item', button type: 'button' className: "comment__action #{if @state.editing then 'comment__action--active' else ''}" onClick: @toggleEdit osu.trans('common.buttons.edit') renderEditedBy: => if !@props.comment.isDeleted && @props.comment.isEdited editor = userStore.get(@props.comment.editedById) div className: 'comment__row-item comment__row-item--info' dangerouslySetInnerHTML: __html: osu.trans 'comments.edited', timeago: osu.timeago(@props.comment.editedAt) user: if editor.id? osu.link(laroute.route('users.show', user: editor.id), editor.username, classNames: ['comment__link']) else _.escape editor.username renderOwnerBadge: (meta) => return null unless @props.comment.userId == meta.owner_id div className: 'comment__row-item', div className: 'comment__owner-badge', meta.owner_title renderPermalink: => div className: 'comment__row-item', span className: 'comment__action comment__action--permalink' el ClickToCopy, value: laroute.route('comments.show', comment: @props.comment.id) label: osu.trans 'common.buttons.permalink' valueAsUrl: true renderRepliesText: => return if @props.comment.repliesCount == 0 if !@state.expandReplies && @children.length == 0 callback = @loadReplies label = osu.trans('comments.load_replies') else callback = @toggleReplies label = osu.transChoice('comments.replies_count', @props.comment.repliesCount) div className: 'comment__row-item comment__row-item--replies', el ShowMoreLink, direction: if @state.expandReplies then 'up' else 'down' hasMore: true label: label callback: callback modifiers: ['comment-replies'] renderRepliesToggle: => if @props.depth == 0 && @children.length > 0 div className: 'comment__float-container comment__float-container--right', button className: 'comment__top-show-replies' type: 'button' onClick: @toggleReplies span className: "fas #{if @state.expandReplies then 'fa-angle-up' else 'fa-angle-down'}" renderReplyBox: => if @state.showNewReply div className: 'comment__reply-box', el CommentEditor, close: @closeNewReply modifiers: @props.modifiers onPosted: @handleReplyPosted parent: @props.comment renderReplyButton: => if !@props.comment.isDeleted div className: 'comment__row-item', button type: 'button' className: "comment__action #{if @state.showNewReply then 'comment__action--active' else ''}" onClick: @toggleNewReply osu.trans('common.buttons.reply') renderReport: => if @props.comment.canReport div className: 'comment__row-item', el ReportReportable, className: 'comment__action' reportableId: @props.comment.id reportableType: 'comment' user: @userFor(@props.comment) renderRestore: => if @props.comment.isDeleted && @props.comment.canRestore div className: 'comment__row-item', button type: 'button' className: 'comment__action' onClick: @restore osu.trans('common.buttons.restore') renderUserAvatar: (user) => if user.id? a className: 'comment__avatar js-usercard' 'data-user-id': user.id href: laroute.route('users.show', user: user.id) el UserAvatar, user: user, modifiers: ['full-circle'] else span className: 'comment__avatar' el UserAvatar, user: user, modifiers: ['full-circle'] renderUsername: (user) => if user.id? a 'data-user-id': user.id href: laroute.route('users.show', user: user.id) className: 'js-usercard comment__row-item comment__row-item--username comment__row-item--username-link' user.username else span className: 'comment__row-item comment__row-item--username' user.username # mobile vote button renderVoteButton: => className = osu.classWithModifiers('comment-vote', @props.modifiers) className += ' comment-vote--posting' if @state.postingVote if @hasVoted() className += ' comment-vote--on' hover = null else className += ' comment-vote--off' hover = div className: 'comment-vote__hover', '+1' button className: className type: 'button' onClick: @voteToggle disabled: @state.postingVote || !@props.comment.canVote span className: 'comment-vote__text', "+#{osu.formatNumberSuffixed(@props.comment.votesCount, null, maximumFractionDigits: 1)}" if @state.postingVote span className: 'comment-vote__spinner', el Spinner hover renderVoteText: => className = 'comment__action' className += ' comment__action--active' if @hasVoted() button className: className type: 'button' onClick: @voteToggle disabled: @state.postingVote "+#{osu.formatNumberSuffixed(@props.comment.votesCount, null, maximumFractionDigits: 1)}" renderCommentableMeta: (meta) => return unless @props.showCommentableMeta if meta.url component = a params = href: meta.url className: 'comment__link' else component = span params = null div className: 'comment__commentable-meta', if @props.comment.commentableType? span className: 'comment__commentable-meta-type', span className: 'comment__commentable-meta-icon fas fa-comment' ' ' osu.trans("comments.commentable_name.#{@props.comment.commentableType}") component params, meta.title hasVoted: => store.userVotes.has(@props.comment.id) delete: => return unless confirm(osu.trans('common.confirmation')) @xhr.delete?.abort() @xhr.delete = $.ajax laroute.route('comments.destroy', comment: @props.comment.id), method: 'DELETE' .done (data) => $.publish 'comment:updated', data .fail (xhr, status) => return if status == 'abort' osu.ajaxError xhr togglePinned: => return unless @props.comment.canPin @xhr.pin?.abort() @xhr.pin = $.ajax laroute.route('comments.pin', comment: @props.comment.id), method: if @props.comment.pinned then 'DELETE' else 'POST' .done (data) => $.publish 'comment:updated', data .fail (xhr, status) => return if status == 'abort' osu.ajaxError xhr handleReplyPosted: (type) => @setState expandReplies: true if type == 'reply' toggleEdit: => @setState editing: !@state.editing closeEdit: => @setState editing: false loadReplies: => @loadMoreRef.current?.load() @toggleReplies() parentLink: (parent) => props = title: makePreview(parent) if @props.linkParent component = a props.href = laroute.route('comments.show', comment: parent.id) props.className = 'comment__link' else component = span component props, span className: 'fas fa-reply' ' ' @userFor(parent).username userFor: (comment) => user = userStore.get(comment.userId)?.toJSON() if user? user else if comment.legacyName? username: comment.legacyName else deletedUser restore: => @xhr.restore?.abort() @xhr.restore = $.ajax laroute.route('comments.restore', comment: @props.comment.id), method: 'POST' .done (data) => $.publish 'comment:updated', data .fail (xhr, status) => return if status == 'abort' osu.ajaxError xhr toggleNewReply: => @setState showNewReply: !@state.showNewReply voteToggle: (e) => target = e.target if !currentUser.id? userLogin.show target return @setState postingVote: true if @hasVoted() method = 'DELETE' storeMethod = 'removeUserVote' else method = 'POST' storeMethod = 'addUserVote' @xhr.vote?.abort() @xhr.vote = $.ajax laroute.route('comments.vote', comment: @props.comment.id), method: method .always => @setState postingVote: false .done (data) => $.publish 'comment:updated', data store[storeMethod](@props.comment) .fail (xhr, status) => return if status == 'abort' return $(target).trigger('ajax:error', [xhr, status]) if xhr.status == 401 osu.ajaxError xhr closeNewReply: => @setState showNewReply: false toggleReplies: => @setState expandReplies: !@state.expandReplies
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import ClickToCopy from 'click-to-copy' import { CommentEditor } from 'comment-editor' import { CommentShowMore } from 'comment-show-more' import DeletedCommentsCount from 'deleted-comments-count' import { Observer } from 'mobx-react' import core from 'osu-core-singleton' import * as React from 'react' import { a, button, div, span, textarea } from 'react-dom-factories' import { ReportReportable } from 'report-reportable' import { ShowMoreLink } from 'show-more-link' import { Spinner } from 'spinner' import { UserAvatar } from 'user-avatar' el = React.createElement deletedUser = username: osu.trans('users.deleted') commentableMetaStore = core.dataStore.commentableMetaStore store = core.dataStore.commentStore userStore = core.dataStore.userStore uiState = core.dataStore.uiState export class Comment extends React.PureComponent MAX_DEPTH = 6 makePreviewElement = document.createElement('div') makePreview = (comment) -> if comment.isDeleted osu.trans('comments.deleted') else makePreviewElement.innerHTML = comment.messageHtml _.truncate makePreviewElement.textContent, length: 100 constructor: (props) -> super props @xhr = {} @loadMoreRef = React.createRef() if osu.isMobile() # There's no indentation on mobile so don't expand by default otherwise it will be confusing. expandReplies = false else if @props.comment.isDeleted expandReplies = false else if @props.expandReplies? expandReplies = @props.expandReplies else children = uiState.getOrderedCommentsByParentId(@props.comment.id) # Collapse if either no children is loaded or current level doesn't add indentation. expandReplies = children?.length > 0 && @props.depth < MAX_DEPTH @state = postingVote: false editing: false showNewReply: false expandReplies: expandReplies componentWillUnmount: => xhr?.abort() for own _name, xhr of @xhr render: => el Observer, null, () => @children = uiState.getOrderedCommentsByParentId(@props.comment.id) ? [] parent = store.comments.get(@props.comment.parentId) user = @userFor(@props.comment) meta = commentableMetaStore.get(@props.comment.commentableType, @props.comment.commentableId) modifiers = @props.modifiers?[..] ? [] modifiers.push 'top' if @props.depth == 0 repliesClass = 'comment__replies' repliesClass += ' comment__replies--indented' if @props.depth < MAX_DEPTH repliesClass += ' comment__replies--hidden' if !@state.expandReplies div className: osu.classWithModifiers 'comment', modifiers @renderRepliesToggle() @renderCommentableMeta(meta) div className: "comment__main #{if @props.comment.isDeleted then 'comment__main--deleted' else ''}", if @props.comment.canHaveVote div className: 'comment__float-container comment__float-container--left hidden-xs', @renderVoteButton() @renderUserAvatar user div className: 'comment__container', div className: 'comment__row comment__row--header', @renderUsername user @renderOwnerBadge(meta) if @props.comment.pinned span className: 'comment__row-item comment__row-item--pinned' span className: 'fa fa-thumbtack' ' ' osu.trans 'comments.pinned' if parent? span className: 'comment__row-item comment__row-item--parent' @parentLink(parent) if @props.comment.isDeleted span className: 'comment__row-item comment__row-item--deleted' osu.trans('comments.deleted') if @state.editing div className: 'comment__editor', el CommentEditor, id: @props.comment.id message: @props.comment.message modifiers: @props.modifiers close: @closeEdit else if @props.comment.messageHtml? div className: 'comment__message', dangerouslySetInnerHTML: __html: @props.comment.messageHtml div className: 'comment__row comment__row--footer', if @props.comment.canHaveVote div className: 'comment__row-item visible-xs' @renderVoteText() div className: 'comment__row-item comment__row-item--info' dangerouslySetInnerHTML: __html: osu.timeago(@props.comment.createdAt) @renderPermalink() @renderReplyButton() @renderEdit() @renderRestore() @renderDelete() @renderPin() @renderReport() @renderEditedBy() @renderRepliesText() @renderReplyBox() if @props.comment.repliesCount > 0 div className: repliesClass @children.map @renderComment el DeletedCommentsCount, { comments: @children, showDeleted: uiState.comments.isShowDeleted } el CommentShowMore, parent: @props.comment comments: @children total: @props.comment.repliesCount modifiers: @props.modifiers label: osu.trans('comments.load_replies') if @children.length == 0 ref: @loadMoreRef renderComment: (comment) => comment = store.comments.get(comment.id) return null if comment.isDeleted && !uiState.comments.isShowDeleted el Comment, key: comment.id comment: comment depth: @props.depth + 1 parent: @props.comment modifiers: @props.modifiers expandReplies: @props.expandReplies renderDelete: => if !@props.comment.isDeleted && @props.comment.canDelete div className: 'comment__row-item', button type: 'button' className: 'comment__action' onClick: @delete osu.trans('common.buttons.delete') renderPin: => if @props.comment.canPin div className: 'comment__row-item', button type: 'button' className: 'comment__action' onClick: @togglePinned osu.trans 'common.buttons.' + if @props.comment.pinned then 'unpin' else 'pin' renderEdit: => if @props.comment.canEdit div className: 'comment__row-item', button type: 'button' className: "comment__action #{if @state.editing then 'comment__action--active' else ''}" onClick: @toggleEdit osu.trans('common.buttons.edit') renderEditedBy: => if !@props.comment.isDeleted && @props.comment.isEdited editor = userStore.get(@props.comment.editedById) div className: 'comment__row-item comment__row-item--info' dangerouslySetInnerHTML: __html: osu.trans 'comments.edited', timeago: osu.timeago(@props.comment.editedAt) user: if editor.id? osu.link(laroute.route('users.show', user: editor.id), editor.username, classNames: ['comment__link']) else _.escape editor.username renderOwnerBadge: (meta) => return null unless @props.comment.userId == meta.owner_id div className: 'comment__row-item', div className: 'comment__owner-badge', meta.owner_title renderPermalink: => div className: 'comment__row-item', span className: 'comment__action comment__action--permalink' el ClickToCopy, value: laroute.route('comments.show', comment: @props.comment.id) label: osu.trans 'common.buttons.permalink' valueAsUrl: true renderRepliesText: => return if @props.comment.repliesCount == 0 if !@state.expandReplies && @children.length == 0 callback = @loadReplies label = osu.trans('comments.load_replies') else callback = @toggleReplies label = osu.transChoice('comments.replies_count', @props.comment.repliesCount) div className: 'comment__row-item comment__row-item--replies', el ShowMoreLink, direction: if @state.expandReplies then 'up' else 'down' hasMore: true label: label callback: callback modifiers: ['comment-replies'] renderRepliesToggle: => if @props.depth == 0 && @children.length > 0 div className: 'comment__float-container comment__float-container--right', button className: 'comment__top-show-replies' type: 'button' onClick: @toggleReplies span className: "fas #{if @state.expandReplies then 'fa-angle-up' else 'fa-angle-down'}" renderReplyBox: => if @state.showNewReply div className: 'comment__reply-box', el CommentEditor, close: @closeNewReply modifiers: @props.modifiers onPosted: @handleReplyPosted parent: @props.comment renderReplyButton: => if !@props.comment.isDeleted div className: 'comment__row-item', button type: 'button' className: "comment__action #{if @state.showNewReply then 'comment__action--active' else ''}" onClick: @toggleNewReply osu.trans('common.buttons.reply') renderReport: => if @props.comment.canReport div className: 'comment__row-item', el ReportReportable, className: 'comment__action' reportableId: @props.comment.id reportableType: 'comment' user: @userFor(@props.comment) renderRestore: => if @props.comment.isDeleted && @props.comment.canRestore div className: 'comment__row-item', button type: 'button' className: 'comment__action' onClick: @restore osu.trans('common.buttons.restore') renderUserAvatar: (user) => if user.id? a className: 'comment__avatar js-usercard' 'data-user-id': user.id href: laroute.route('users.show', user: user.id) el UserAvatar, user: user, modifiers: ['full-circle'] else span className: 'comment__avatar' el UserAvatar, user: user, modifiers: ['full-circle'] renderUsername: (user) => if user.id? a 'data-user-id': user.id href: laroute.route('users.show', user: user.id) className: 'js-usercard comment__row-item comment__row-item--username comment__row-item--username-link' user.username else span className: 'comment__row-item comment__row-item--username' user.username # mobile vote button renderVoteButton: => className = osu.classWithModifiers('comment-vote', @props.modifiers) className += ' comment-vote--posting' if @state.postingVote if @hasVoted() className += ' comment-vote--on' hover = null else className += ' comment-vote--off' hover = div className: 'comment-vote__hover', '+1' button className: className type: 'button' onClick: @voteToggle disabled: @state.postingVote || !@props.comment.canVote span className: 'comment-vote__text', "+#{osu.formatNumberSuffixed(@props.comment.votesCount, null, maximumFractionDigits: 1)}" if @state.postingVote span className: 'comment-vote__spinner', el Spinner hover renderVoteText: => className = 'comment__action' className += ' comment__action--active' if @hasVoted() button className: className type: 'button' onClick: @voteToggle disabled: @state.postingVote "+#{osu.formatNumberSuffixed(@props.comment.votesCount, null, maximumFractionDigits: 1)}" renderCommentableMeta: (meta) => return unless @props.showCommentableMeta if meta.url component = a params = href: meta.url className: 'comment__link' else component = span params = null div className: 'comment__commentable-meta', if @props.comment.commentableType? span className: 'comment__commentable-meta-type', span className: 'comment__commentable-meta-icon fas fa-comment' ' ' osu.trans("comments.commentable_name.#{@props.comment.commentableType}") component params, meta.title hasVoted: => store.userVotes.has(@props.comment.id) delete: => return unless confirm(osu.trans('common.confirmation')) @xhr.delete?.abort() @xhr.delete = $.ajax laroute.route('comments.destroy', comment: @props.comment.id), method: 'DELETE' .done (data) => $.publish 'comment:updated', data .fail (xhr, status) => return if status == 'abort' osu.ajaxError xhr togglePinned: => return unless @props.comment.canPin @xhr.pin?.abort() @xhr.pin = $.ajax laroute.route('comments.pin', comment: @props.comment.id), method: if @props.comment.pinned then 'DELETE' else 'POST' .done (data) => $.publish 'comment:updated', data .fail (xhr, status) => return if status == 'abort' osu.ajaxError xhr handleReplyPosted: (type) => @setState expandReplies: true if type == 'reply' toggleEdit: => @setState editing: !@state.editing closeEdit: => @setState editing: false loadReplies: => @loadMoreRef.current?.load() @toggleReplies() parentLink: (parent) => props = title: makePreview(parent) if @props.linkParent component = a props.href = laroute.route('comments.show', comment: parent.id) props.className = 'comment__link' else component = span component props, span className: 'fas fa-reply' ' ' @userFor(parent).username userFor: (comment) => user = userStore.get(comment.userId)?.toJSON() if user? user else if comment.legacyName? username: comment.legacyName else deletedUser restore: => @xhr.restore?.abort() @xhr.restore = $.ajax laroute.route('comments.restore', comment: @props.comment.id), method: 'POST' .done (data) => $.publish 'comment:updated', data .fail (xhr, status) => return if status == 'abort' osu.ajaxError xhr toggleNewReply: => @setState showNewReply: !@state.showNewReply voteToggle: (e) => target = e.target if !currentUser.id? userLogin.show target return @setState postingVote: true if @hasVoted() method = 'DELETE' storeMethod = 'removeUserVote' else method = 'POST' storeMethod = 'addUserVote' @xhr.vote?.abort() @xhr.vote = $.ajax laroute.route('comments.vote', comment: @props.comment.id), method: method .always => @setState postingVote: false .done (data) => $.publish 'comment:updated', data store[storeMethod](@props.comment) .fail (xhr, status) => return if status == 'abort' return $(target).trigger('ajax:error', [xhr, status]) if xhr.status == 401 osu.ajaxError xhr closeNewReply: => @setState showNewReply: false toggleReplies: => @setState expandReplies: !@state.expandReplies
[ { "context": "images inside the editable for Hallo\n# (c) 2013 Christian Grobmeier, http://www.grobmeier.de\n# This plugin may be ", "end": 95, "score": 0.9998383522033691, "start": 76, "tag": "NAME", "value": "Christian Grobmeier" } ]
src/plugins/image_size.coffee
grobmeier/hallo
1
# Plugin to work with images inside the editable for Hallo # (c) 2013 Christian Grobmeier, http://www.grobmeier.de # This plugin may be freely distributed under the MIT license # # Depends on: hallo-image-select ((jQuery) -> jQuery.widget "IKS.hallo-image-size", options: editable: null toolbar: null uuid: '', resizeStep : 10 populateToolbar: (toolbar) -> widget = this buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" buttonize = (label, icon) => buttonElement = jQuery '<span></span>' buttonElement.hallobutton uuid: @options.uuid editable: @options.editable label: label command: null icon: icon cssClass: @options.buttonCssClass buttonset.append buttonElement buttonset.hide() return buttonElement resizeStep = @options.resizeStep sizeButton = (alignment, icon, resize) -> button = buttonize alignment, icon button.on "click", => image = widget.options.editable.selectedImage if resize is 100 image.css('width', 'auto') image.css('height', 'auto') else width = image.width() height = image.height() faktor = (resize / 100) image.width ( width * faktor ) image.height ( height * faktor ) sizeButton "Smaller", "icon-resize-small", (100 - resizeStep) sizeButton "Original", "icon-fullscreen", 100 sizeButton "Bigger", "icon-resize-full", (100 + resizeStep) buttonset.hallobuttonset() toolbar.append buttonset jQuery(document).on "halloselected", => element = @options.editable.selectedImage if element isnt null buttonset.show() else buttonset.hide() )(jQuery)
121324
# Plugin to work with images inside the editable for Hallo # (c) 2013 <NAME>, http://www.grobmeier.de # This plugin may be freely distributed under the MIT license # # Depends on: hallo-image-select ((jQuery) -> jQuery.widget "IKS.hallo-image-size", options: editable: null toolbar: null uuid: '', resizeStep : 10 populateToolbar: (toolbar) -> widget = this buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" buttonize = (label, icon) => buttonElement = jQuery '<span></span>' buttonElement.hallobutton uuid: @options.uuid editable: @options.editable label: label command: null icon: icon cssClass: @options.buttonCssClass buttonset.append buttonElement buttonset.hide() return buttonElement resizeStep = @options.resizeStep sizeButton = (alignment, icon, resize) -> button = buttonize alignment, icon button.on "click", => image = widget.options.editable.selectedImage if resize is 100 image.css('width', 'auto') image.css('height', 'auto') else width = image.width() height = image.height() faktor = (resize / 100) image.width ( width * faktor ) image.height ( height * faktor ) sizeButton "Smaller", "icon-resize-small", (100 - resizeStep) sizeButton "Original", "icon-fullscreen", 100 sizeButton "Bigger", "icon-resize-full", (100 + resizeStep) buttonset.hallobuttonset() toolbar.append buttonset jQuery(document).on "halloselected", => element = @options.editable.selectedImage if element isnt null buttonset.show() else buttonset.hide() )(jQuery)
true
# Plugin to work with images inside the editable for Hallo # (c) 2013 PI:NAME:<NAME>END_PI, http://www.grobmeier.de # This plugin may be freely distributed under the MIT license # # Depends on: hallo-image-select ((jQuery) -> jQuery.widget "IKS.hallo-image-size", options: editable: null toolbar: null uuid: '', resizeStep : 10 populateToolbar: (toolbar) -> widget = this buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" buttonize = (label, icon) => buttonElement = jQuery '<span></span>' buttonElement.hallobutton uuid: @options.uuid editable: @options.editable label: label command: null icon: icon cssClass: @options.buttonCssClass buttonset.append buttonElement buttonset.hide() return buttonElement resizeStep = @options.resizeStep sizeButton = (alignment, icon, resize) -> button = buttonize alignment, icon button.on "click", => image = widget.options.editable.selectedImage if resize is 100 image.css('width', 'auto') image.css('height', 'auto') else width = image.width() height = image.height() faktor = (resize / 100) image.width ( width * faktor ) image.height ( height * faktor ) sizeButton "Smaller", "icon-resize-small", (100 - resizeStep) sizeButton "Original", "icon-fullscreen", 100 sizeButton "Bigger", "icon-resize-full", (100 + resizeStep) buttonset.hallobuttonset() toolbar.append buttonset jQuery(document).on "halloselected", => element = @options.editable.selectedImage if element isnt null buttonset.show() else buttonset.hide() )(jQuery)
[ { "context": ".\r\n@todo Remove prior to product publish.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n###\r\nclass NodeStatsRoute ", "end": 497, "score": 0.9998327493667603, "start": 485, "tag": "NAME", "value": "Nathan Klick" } ]
Workspace/QRef/NodeServer/src/router/routes/restful/NodeStatsRoute.coffee
qrefdev/qref
0
Route = require('../../Route') mongoose = require('mongoose') UserSchema = require('../../../schema/UserSchema') os = require('os') ### **** DEVELOPER ONLY **** Route used to acquire detailed runtime info about the node server during development. @example Service Methods Request Format: application/json Response Format: application/json GET /services/restful/node/stats Retrieves node runtime statistics. @todo Remove prior to product publish. @author Nathan Klick @copyright QRef 2012 ### class NodeStatsRoute extends Route constructor: () -> super [{method: 'GET', path: '/node/stats'}] get: (req, res) -> console.log("Express server rendering runtime report."); response = tempDir: os.tmpDir(), hostName: os.hostname(), osType: os.type(), osArch: os.arch(), osRelease: os.release(), osUptime: os.uptime(), osLoadAvg: os.loadavg(), totalMem: os.totalmem(), freeMem: os.freemem(), cpus: os.cpus(), processMem: process.memoryUsage(), processUptime: process.uptime(), networkInterfaces: os.networkInterfaces() res.json(response, 200) module.exports = new NodeStatsRoute()
122302
Route = require('../../Route') mongoose = require('mongoose') UserSchema = require('../../../schema/UserSchema') os = require('os') ### **** DEVELOPER ONLY **** Route used to acquire detailed runtime info about the node server during development. @example Service Methods Request Format: application/json Response Format: application/json GET /services/restful/node/stats Retrieves node runtime statistics. @todo Remove prior to product publish. @author <NAME> @copyright QRef 2012 ### class NodeStatsRoute extends Route constructor: () -> super [{method: 'GET', path: '/node/stats'}] get: (req, res) -> console.log("Express server rendering runtime report."); response = tempDir: os.tmpDir(), hostName: os.hostname(), osType: os.type(), osArch: os.arch(), osRelease: os.release(), osUptime: os.uptime(), osLoadAvg: os.loadavg(), totalMem: os.totalmem(), freeMem: os.freemem(), cpus: os.cpus(), processMem: process.memoryUsage(), processUptime: process.uptime(), networkInterfaces: os.networkInterfaces() res.json(response, 200) module.exports = new NodeStatsRoute()
true
Route = require('../../Route') mongoose = require('mongoose') UserSchema = require('../../../schema/UserSchema') os = require('os') ### **** DEVELOPER ONLY **** Route used to acquire detailed runtime info about the node server during development. @example Service Methods Request Format: application/json Response Format: application/json GET /services/restful/node/stats Retrieves node runtime statistics. @todo Remove prior to product publish. @author PI:NAME:<NAME>END_PI @copyright QRef 2012 ### class NodeStatsRoute extends Route constructor: () -> super [{method: 'GET', path: '/node/stats'}] get: (req, res) -> console.log("Express server rendering runtime report."); response = tempDir: os.tmpDir(), hostName: os.hostname(), osType: os.type(), osArch: os.arch(), osRelease: os.release(), osUptime: os.uptime(), osLoadAvg: os.loadavg(), totalMem: os.totalmem(), freeMem: os.freemem(), cpus: os.cpus(), processMem: process.memoryUsage(), processUptime: process.uptime(), networkInterfaces: os.networkInterfaces() res.json(response, 200) module.exports = new NodeStatsRoute()
[ { "context": "# Plays Coppersmith on 5/2 starts; plays Big Money otherwise.", "end": 11, "score": 0.8110172152519226, "start": 8, "tag": "NAME", "value": "Cop" }, { "context": "5/2 starts; plays Big Money otherwise.\n{\n name: 'OBM Coppersmith'\n author: 'HiveMindEmulator'\n requi...
strategies/OBM_Coppersmith.coffee
rspeer/dominiate
65
# Plays Coppersmith on 5/2 starts; plays Big Money otherwise. { name: 'OBM Coppersmith' author: 'HiveMindEmulator' requires: ['Coppersmith'] gainPriority: (state, my) -> [ "Province" if my.getTotalMoney() > 18 "Duchy" if state.gainsToEndGame() <= 4 "Estate" if state.gainsToEndGame() <= 2 "Gold" "Duchy" if state.gainsToEndGame() <= 6 "Coppersmith" if my.numCardsInDeck() == 10 and my.getAvailableMoney() == 5 "Silver" ] }
7059
# Plays <NAME>persmith on 5/2 starts; plays Big Money otherwise. { name: '<NAME> <NAME>' author: 'HiveMindEmulator' requires: ['<NAME>'] gainPriority: (state, my) -> [ "Province" if my.getTotalMoney() > 18 "Duchy" if state.gainsToEndGame() <= 4 "Estate" if state.gainsToEndGame() <= 2 "Gold" "Duchy" if state.gainsToEndGame() <= 6 "<NAME>" if my.numCardsInDeck() == 10 and my.getAvailableMoney() == 5 "Silver" ] }
true
# Plays PI:NAME:<NAME>END_PIpersmith on 5/2 starts; plays Big Money otherwise. { name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' author: 'HiveMindEmulator' requires: ['PI:NAME:<NAME>END_PI'] gainPriority: (state, my) -> [ "Province" if my.getTotalMoney() > 18 "Duchy" if state.gainsToEndGame() <= 4 "Estate" if state.gainsToEndGame() <= 2 "Gold" "Duchy" if state.gainsToEndGame() <= 6 "PI:NAME:<NAME>END_PI" if my.numCardsInDeck() == 10 and my.getAvailableMoney() == 5 "Silver" ] }
[ { "context": "bow'\n delay = 1500\n if name == 'ganyu' then delay = 1800\n if name == 'tartagli", "end": 2115, "score": 0.6889230608940125, "start": 2110, "tag": "NAME", "value": "ganyu" }, { "context": "= 'ganyu' then delay = 1800\n if name == 'ta...
source/tactic.coffee
phonowell/genshin-impact-script
391
# !@e - not at e duration # !@e? - e is not ready # !@m - not at movement # @e - at e-duration # @e? - e is ready # @m - at movement # a - attack # a~ - charged attack # e - use e # ee - use e twice # e~ - holding e # j - jump # ja - jump & attack # q - use q # s - sprint # t - aim # tt - aim twice ### interface type Fn = () => unknown ### # function class TacticX intervalCheck: 50 intervalExecute: 100 isActive: false isPressed: {} # --- constructor: -> Player .on 'attack:start', @start .on 'attack:end', @stop Party .on 'change', @reset .on 'switch', => unless @isActive then return @stop() @start() # aim(callback: Fn): void aim: (callback) -> $.press 'r' @delay @intervalExecute, callback # aimTwice(callback: Fn): void aimTwice: (callback) -> $.press 'r' @delay @intervalExecute, => $.press 'r' @delay @intervalExecute, callback # atDuration(cbA: Fn, cbB: Fn, isNot: boolean = false): void atDuration: (cbA, cbB, isNot = false) -> cb = [cbA, cbB] if isNot then cb = [cbB, cbA] if SkillTimer.listDuration[Party.current] @delay @intervalCheck, cb[0] else @delay @intervalCheck, cb[1] # atMovement: (cbA: Fn, cbB: Fn, isNot: boolean = false): void atMovement: (cbA, cbB, isNot = false) -> cb = [cbA, cbB] if isNot then cb = [cbB, cbA] if Movement.isMoving @delay @intervalCheck, cb[0] else @delay @intervalCheck, cb[1] # atReady(cbA: Fn, cb: Fn, isNot: boolean = false): void atReady: (cbA, cbB, isNot = false) -> cb = [cbA, cbB] if isNot then cb = [cbB, cbA] unless SkillTimer.listCountDown[Party.current] @delay @intervalCheck, cb[0] else @delay @intervalCheck, cb[1] # attack(isCharged: boolean, callback: Fn): void attack: (isCharged, callback) -> if isCharged $.click 'left:down' @isPressed['l-button'] = true delay = 400 name = Party.name {weapon} = Character.data[name] switch weapon when 'bow' delay = 1500 if name == 'ganyu' then delay = 1800 if name == 'tartaglia' then delay = 400 if name == 'yoimiya' then delay = 2600 when 'sword' if name == 'xingqiu' then delay = 600 @delay delay, => $.click 'left:up' @isPressed['l-button'] = false if Movement.isMoving and Party.name == 'klee' @delay 200, => @jump callback return @delay @intervalExecute, callback return $.click 'left' @delay 200, callback # delay(time: number, callback: Fn): void delay: (time, callback) -> unless @isActive then return Client.delay '~tactic', time, callback # execute(listTactic: string[], g: number = 0, i: number = 0): void execute: (listTactic, g = 0, i = 0) -> item = @get listTactic, g, i unless item @execute listTactic return next = => @execute listTactic, g, i + 1 nextGroup = => @execute listTactic, g + 1, 0 map = '!@e': => @atDuration next, nextGroup, 'not' '!@e?': => @atReady next, nextGroup, 'not' '!@m': => @atMovement next, nextGroup, 'not' '@e': => @atDuration next, nextGroup, 0 '@e?': => @atReady next, nextGroup, 0 '@m': => @atMovement next, nextGroup, 0 'a': => @attack false, next 'a~': => @attack true, next 'e': => @useE false, next 'ee': => @useEE next 'e~': => @useE true, next 'j': => @jump next 'ja': => @jumpAttack next 'q': => @useQ next 's': => @sprint next 't': => @aim next 'tt': => @aimTwice next # console.log "tactic: #{item}" callback = map[item] if !callback and ($.type item) == 'number' callback = => @delay item, next if callback then callback() # get(list: string[], g: number = 0, i: number = 0): string get: (list, g = 0, i = 0) -> if g >= $.length list then return '' group = list[g] if i >= $.length group then return '' return group[i] # jump(callback: Fn): void jump: (callback) -> Movement.jump() unless Movement.isMoving @delay 450, callback else @delay 550, callback # jumpAttack(callback: Fn): void jumpAttack: (callback) -> Movement.jump() @delay 50, -> $.click 'left' @delay 50, callback # reset(): void reset: -> Client.delay '~tactic' if @isPressed['l-button'] $.click 'left:up' @isActive = false # sprint(callback: Fn): void sprint: (callback) -> Movement.sprint() @delay @intervalExecute, callback # start(): void start: -> if @isActive then return listTactic = @validate() unless listTactic $.click 'left:down' return @isActive = true wait = 1e3 - ($.now() - Party.tsSwitch) if wait < 200 wait = 200 @execute listTactic, 0, 0 # stop(): void stop: -> if @isActive @reset() return $.click 'left:up' # useE(isHolding: boolean, callback: Fn): void useE: (isHolding, callback) -> if SkillTimer.listCountDown[Party.current] @delay @intervalCheck, callback return Player.useE isHolding @delay @intervalExecute, callback # useEE(callback: Fn): void useEE: (callback) -> if SkillTimer.listCountDown[Party.current] @delay @intervalCheck, callback return Player.useE() @delay 600, => Player.useE() @delay @intervalExecute, callback # useQ(callback: Fn): void useQ: (callback) -> Player.useQ() @delay @intervalExecute, callback # validate(): boolean validate: -> unless Scene.name == 'normal' then return false {name} = Party unless name then return false listTactic = Character.data[name].onLongPress unless listTactic then return false return listTactic # execute Tactic = new TacticX()
169624
# !@e - not at e duration # !@e? - e is not ready # !@m - not at movement # @e - at e-duration # @e? - e is ready # @m - at movement # a - attack # a~ - charged attack # e - use e # ee - use e twice # e~ - holding e # j - jump # ja - jump & attack # q - use q # s - sprint # t - aim # tt - aim twice ### interface type Fn = () => unknown ### # function class TacticX intervalCheck: 50 intervalExecute: 100 isActive: false isPressed: {} # --- constructor: -> Player .on 'attack:start', @start .on 'attack:end', @stop Party .on 'change', @reset .on 'switch', => unless @isActive then return @stop() @start() # aim(callback: Fn): void aim: (callback) -> $.press 'r' @delay @intervalExecute, callback # aimTwice(callback: Fn): void aimTwice: (callback) -> $.press 'r' @delay @intervalExecute, => $.press 'r' @delay @intervalExecute, callback # atDuration(cbA: Fn, cbB: Fn, isNot: boolean = false): void atDuration: (cbA, cbB, isNot = false) -> cb = [cbA, cbB] if isNot then cb = [cbB, cbA] if SkillTimer.listDuration[Party.current] @delay @intervalCheck, cb[0] else @delay @intervalCheck, cb[1] # atMovement: (cbA: Fn, cbB: Fn, isNot: boolean = false): void atMovement: (cbA, cbB, isNot = false) -> cb = [cbA, cbB] if isNot then cb = [cbB, cbA] if Movement.isMoving @delay @intervalCheck, cb[0] else @delay @intervalCheck, cb[1] # atReady(cbA: Fn, cb: Fn, isNot: boolean = false): void atReady: (cbA, cbB, isNot = false) -> cb = [cbA, cbB] if isNot then cb = [cbB, cbA] unless SkillTimer.listCountDown[Party.current] @delay @intervalCheck, cb[0] else @delay @intervalCheck, cb[1] # attack(isCharged: boolean, callback: Fn): void attack: (isCharged, callback) -> if isCharged $.click 'left:down' @isPressed['l-button'] = true delay = 400 name = Party.name {weapon} = Character.data[name] switch weapon when 'bow' delay = 1500 if name == '<NAME>' then delay = 1800 if name == '<NAME>' then delay = 400 if name == '<NAME>imiya' then delay = 2600 when 'sword' if name == '<NAME>' then delay = 600 @delay delay, => $.click 'left:up' @isPressed['l-button'] = false if Movement.isMoving and Party.name == 'klee' @delay 200, => @jump callback return @delay @intervalExecute, callback return $.click 'left' @delay 200, callback # delay(time: number, callback: Fn): void delay: (time, callback) -> unless @isActive then return Client.delay '~tactic', time, callback # execute(listTactic: string[], g: number = 0, i: number = 0): void execute: (listTactic, g = 0, i = 0) -> item = @get listTactic, g, i unless item @execute listTactic return next = => @execute listTactic, g, i + 1 nextGroup = => @execute listTactic, g + 1, 0 map = '!@e': => @atDuration next, nextGroup, 'not' '!@e?': => @atReady next, nextGroup, 'not' '!@m': => @atMovement next, nextGroup, 'not' '@e': => @atDuration next, nextGroup, 0 '@e?': => @atReady next, nextGroup, 0 '@m': => @atMovement next, nextGroup, 0 'a': => @attack false, next 'a~': => @attack true, next 'e': => @useE false, next 'ee': => @useEE next 'e~': => @useE true, next 'j': => @jump next 'ja': => @jumpAttack next 'q': => @useQ next 's': => @sprint next 't': => @aim next 'tt': => @aimTwice next # console.log "tactic: #{item}" callback = map[item] if !callback and ($.type item) == 'number' callback = => @delay item, next if callback then callback() # get(list: string[], g: number = 0, i: number = 0): string get: (list, g = 0, i = 0) -> if g >= $.length list then return '' group = list[g] if i >= $.length group then return '' return group[i] # jump(callback: Fn): void jump: (callback) -> Movement.jump() unless Movement.isMoving @delay 450, callback else @delay 550, callback # jumpAttack(callback: Fn): void jumpAttack: (callback) -> Movement.jump() @delay 50, -> $.click 'left' @delay 50, callback # reset(): void reset: -> Client.delay '~tactic' if @isPressed['l-button'] $.click 'left:up' @isActive = false # sprint(callback: Fn): void sprint: (callback) -> Movement.sprint() @delay @intervalExecute, callback # start(): void start: -> if @isActive then return listTactic = @validate() unless listTactic $.click 'left:down' return @isActive = true wait = 1e3 - ($.now() - Party.tsSwitch) if wait < 200 wait = 200 @execute listTactic, 0, 0 # stop(): void stop: -> if @isActive @reset() return $.click 'left:up' # useE(isHolding: boolean, callback: Fn): void useE: (isHolding, callback) -> if SkillTimer.listCountDown[Party.current] @delay @intervalCheck, callback return Player.useE isHolding @delay @intervalExecute, callback # useEE(callback: Fn): void useEE: (callback) -> if SkillTimer.listCountDown[Party.current] @delay @intervalCheck, callback return Player.useE() @delay 600, => Player.useE() @delay @intervalExecute, callback # useQ(callback: Fn): void useQ: (callback) -> Player.useQ() @delay @intervalExecute, callback # validate(): boolean validate: -> unless Scene.name == 'normal' then return false {name} = Party unless name then return false listTactic = Character.data[name].onLongPress unless listTactic then return false return listTactic # execute Tactic = new TacticX()
true
# !@e - not at e duration # !@e? - e is not ready # !@m - not at movement # @e - at e-duration # @e? - e is ready # @m - at movement # a - attack # a~ - charged attack # e - use e # ee - use e twice # e~ - holding e # j - jump # ja - jump & attack # q - use q # s - sprint # t - aim # tt - aim twice ### interface type Fn = () => unknown ### # function class TacticX intervalCheck: 50 intervalExecute: 100 isActive: false isPressed: {} # --- constructor: -> Player .on 'attack:start', @start .on 'attack:end', @stop Party .on 'change', @reset .on 'switch', => unless @isActive then return @stop() @start() # aim(callback: Fn): void aim: (callback) -> $.press 'r' @delay @intervalExecute, callback # aimTwice(callback: Fn): void aimTwice: (callback) -> $.press 'r' @delay @intervalExecute, => $.press 'r' @delay @intervalExecute, callback # atDuration(cbA: Fn, cbB: Fn, isNot: boolean = false): void atDuration: (cbA, cbB, isNot = false) -> cb = [cbA, cbB] if isNot then cb = [cbB, cbA] if SkillTimer.listDuration[Party.current] @delay @intervalCheck, cb[0] else @delay @intervalCheck, cb[1] # atMovement: (cbA: Fn, cbB: Fn, isNot: boolean = false): void atMovement: (cbA, cbB, isNot = false) -> cb = [cbA, cbB] if isNot then cb = [cbB, cbA] if Movement.isMoving @delay @intervalCheck, cb[0] else @delay @intervalCheck, cb[1] # atReady(cbA: Fn, cb: Fn, isNot: boolean = false): void atReady: (cbA, cbB, isNot = false) -> cb = [cbA, cbB] if isNot then cb = [cbB, cbA] unless SkillTimer.listCountDown[Party.current] @delay @intervalCheck, cb[0] else @delay @intervalCheck, cb[1] # attack(isCharged: boolean, callback: Fn): void attack: (isCharged, callback) -> if isCharged $.click 'left:down' @isPressed['l-button'] = true delay = 400 name = Party.name {weapon} = Character.data[name] switch weapon when 'bow' delay = 1500 if name == 'PI:NAME:<NAME>END_PI' then delay = 1800 if name == 'PI:NAME:<NAME>END_PI' then delay = 400 if name == 'PI:NAME:<NAME>END_PIimiya' then delay = 2600 when 'sword' if name == 'PI:NAME:<NAME>END_PI' then delay = 600 @delay delay, => $.click 'left:up' @isPressed['l-button'] = false if Movement.isMoving and Party.name == 'klee' @delay 200, => @jump callback return @delay @intervalExecute, callback return $.click 'left' @delay 200, callback # delay(time: number, callback: Fn): void delay: (time, callback) -> unless @isActive then return Client.delay '~tactic', time, callback # execute(listTactic: string[], g: number = 0, i: number = 0): void execute: (listTactic, g = 0, i = 0) -> item = @get listTactic, g, i unless item @execute listTactic return next = => @execute listTactic, g, i + 1 nextGroup = => @execute listTactic, g + 1, 0 map = '!@e': => @atDuration next, nextGroup, 'not' '!@e?': => @atReady next, nextGroup, 'not' '!@m': => @atMovement next, nextGroup, 'not' '@e': => @atDuration next, nextGroup, 0 '@e?': => @atReady next, nextGroup, 0 '@m': => @atMovement next, nextGroup, 0 'a': => @attack false, next 'a~': => @attack true, next 'e': => @useE false, next 'ee': => @useEE next 'e~': => @useE true, next 'j': => @jump next 'ja': => @jumpAttack next 'q': => @useQ next 's': => @sprint next 't': => @aim next 'tt': => @aimTwice next # console.log "tactic: #{item}" callback = map[item] if !callback and ($.type item) == 'number' callback = => @delay item, next if callback then callback() # get(list: string[], g: number = 0, i: number = 0): string get: (list, g = 0, i = 0) -> if g >= $.length list then return '' group = list[g] if i >= $.length group then return '' return group[i] # jump(callback: Fn): void jump: (callback) -> Movement.jump() unless Movement.isMoving @delay 450, callback else @delay 550, callback # jumpAttack(callback: Fn): void jumpAttack: (callback) -> Movement.jump() @delay 50, -> $.click 'left' @delay 50, callback # reset(): void reset: -> Client.delay '~tactic' if @isPressed['l-button'] $.click 'left:up' @isActive = false # sprint(callback: Fn): void sprint: (callback) -> Movement.sprint() @delay @intervalExecute, callback # start(): void start: -> if @isActive then return listTactic = @validate() unless listTactic $.click 'left:down' return @isActive = true wait = 1e3 - ($.now() - Party.tsSwitch) if wait < 200 wait = 200 @execute listTactic, 0, 0 # stop(): void stop: -> if @isActive @reset() return $.click 'left:up' # useE(isHolding: boolean, callback: Fn): void useE: (isHolding, callback) -> if SkillTimer.listCountDown[Party.current] @delay @intervalCheck, callback return Player.useE isHolding @delay @intervalExecute, callback # useEE(callback: Fn): void useEE: (callback) -> if SkillTimer.listCountDown[Party.current] @delay @intervalCheck, callback return Player.useE() @delay 600, => Player.useE() @delay @intervalExecute, callback # useQ(callback: Fn): void useQ: (callback) -> Player.useQ() @delay @intervalExecute, callback # validate(): boolean validate: -> unless Scene.name == 'normal' then return false {name} = Party unless name then return false listTactic = Character.data[name].onLongPress unless listTactic then return false return listTactic # execute Tactic = new TacticX()
[ { "context": "er[email]': 'required'\n 'user[password]': 'required'\n 'user[password_confirmation]': 'required", "end": 193, "score": 0.9881249070167542, "start": 185, "tag": "PASSWORD", "value": "required" }, { "context": "required'\n 'user[password_confirmation...
public/assets/users.coffee
JironBach/eatlocaljapan
0
#users.coffee $ -> # users/sign_up if $('body').hasClass('registrations new') $('#new_user').validate rules: 'user[email]': 'required' 'user[password]': 'required' 'user[password_confirmation]': 'required' # users/sign_in if $('body').hasClass('sessions new') $('#new_user').validate rules: 'user[email]': 'required' 'user[password]': 'required' # users/password if $('body').hasClass('passwords') $('#new_user').validate rules: 'user[email]': 'required' 'user[password]': 'required' 'user[password_confirmation]': 'required' # users/confirmations if $('body').hasClass('confirmations') $('#new_user').validate rules: 'user[email]': 'required'
61598
#users.coffee $ -> # users/sign_up if $('body').hasClass('registrations new') $('#new_user').validate rules: 'user[email]': 'required' 'user[password]': '<PASSWORD>' 'user[password_confirmation]': '<PASSWORD>' # users/sign_in if $('body').hasClass('sessions new') $('#new_user').validate rules: 'user[email]': 'required' 'user[password]': '<PASSWORD>' # users/password if $('body').hasClass('passwords') $('#new_user').validate rules: 'user[email]': 'required' 'user[password]': '<PASSWORD>' 'user[password_confirmation]': '<PASSWORD>' # users/confirmations if $('body').hasClass('confirmations') $('#new_user').validate rules: 'user[email]': 'required'
true
#users.coffee $ -> # users/sign_up if $('body').hasClass('registrations new') $('#new_user').validate rules: 'user[email]': 'required' 'user[password]': 'PI:PASSWORD:<PASSWORD>END_PI' 'user[password_confirmation]': 'PI:PASSWORD:<PASSWORD>END_PI' # users/sign_in if $('body').hasClass('sessions new') $('#new_user').validate rules: 'user[email]': 'required' 'user[password]': 'PI:PASSWORD:<PASSWORD>END_PI' # users/password if $('body').hasClass('passwords') $('#new_user').validate rules: 'user[email]': 'required' 'user[password]': 'PI:PASSWORD:<PASSWORD>END_PI' 'user[password_confirmation]': 'PI:PASSWORD:<PASSWORD>END_PI' # users/confirmations if $('body').hasClass('confirmations') $('#new_user').validate rules: 'user[email]': 'required'
[ { "context": "(Darwin)\nComment: GPGTools - https://gpgtools.org\n\nmI0EUqDRSAEEAMMt5Y4DoTF8g+2ahwPRNy9XOXvdGd3lvNnx/qpmnrogmQnTGgs6\npEu7EJWa4FG/omKK6YMY9EYrHUWs2yDZyazSP311GMKDvYAqVPdlk2ki3X57cf8f\nhMuUuE9exj9rBP9XzIys8uj6+U/P/RrcdbZJ+XkggF54xwkwApShs93FABEBAAG0\nKlRlc3QgTWNUZXN0ZWUgKHB3IGlzICdhJykgPHRlc3RAZ2...
test/files/decoder.iced
samkenxstream/kbpgp
464
#----------------------------------------- {decode} = require "../../lib/openpgp/armor" #----------------------------------------- orig = """-----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org mI0EUqDRSAEEAMMt5Y4DoTF8g+2ahwPRNy9XOXvdGd3lvNnx/qpmnrogmQnTGgs6 pEu7EJWa4FG/omKK6YMY9EYrHUWs2yDZyazSP311GMKDvYAqVPdlk2ki3X57cf8f hMuUuE9exj9rBP9XzIys8uj6+U/P/RrcdbZJ+XkggF54xwkwApShs93FABEBAAG0 KlRlc3QgTWNUZXN0ZWUgKHB3IGlzICdhJykgPHRlc3RAZ21haWwuY29tPoi9BBMB CgAnBQJSoNFIAhsDBQkB4TOABQsJCAcDBRUKCQgLBRYCAwEAAh4BAheAAAoJEJAS rIm9T49IZvsEAI7jTFBn+VtJZklXJx5jUlbUN1CMDjs1QPI/NAeXZCgcsobplm9B PEnMyG8z9zTmzI/0ZicntHJqIuJWMv8tTfn3JUdbYs6ISiXD3CFIDCd50XsEDScY bZb9b9OLtEXrlPU9TL2m8y6B8aArfoFIjBLk3hDl1uTo3oasX10c8ZmzuI0EUqDR SAEEALO/3L8r+vTMh4tNVQ6EdyMAKvgoBKaztg7+hNN/OKGCDMLf9ijLjVFIGRxF iSGOXio2au6lHSPiwhSUEpvw73T2mJlJ4Phu01mqzvaffpFwbbd97zaJ+4cqyk3n IwJeQCw8XGLkn39eDUMyhPaJqgS1FgavHNe1XW2i6ZUqi/AbABEBAAGIpQQYAQoA DwUCUqDRSAIbDAUJAeEzgAAKCRCQEqyJvU+PSCdlA/9C5U+B3RI20m73qvMWd+mZ NbmYAfD5ynHqLdBvLnsCD6EHdMKlyY6XDmj1z8jfwcBjbTa40U8qP6dEQTWBhHml 0E3713KUQeR2aYmt3hHBtQFDcVt7FfQImj4BIqJ+V6pNRLQCNOFbAC3RaXnwFMnN RAA6k7dYVvv+36h0LfJGSQ== =YJ8I -----END PGP PUBLIC KEY BLOCK-----""" inside = """mI0EUqDRSAEEAMMt5Y4DoTF8g+2ahwPRNy9XOXvdGd3lvNnx/qpmnrogmQnTGgs6 pEu7EJWa4FG/omKK6YMY9EYrHUWs2yDZyazSP311GMKDvYAqVPdlk2ki3X57cf8f hMuUuE9exj9rBP9XzIys8uj6+U/P/RrcdbZJ+XkggF54xwkwApShs93FABEBAAG0 KlRlc3QgTWNUZXN0ZWUgKHB3IGlzICdhJykgPHRlc3RAZ21haWwuY29tPoi9BBMB CgAnBQJSoNFIAhsDBQkB4TOABQsJCAcDBRUKCQgLBRYCAwEAAh4BAheAAAoJEJAS rIm9T49IZvsEAI7jTFBn+VtJZklXJx5jUlbUN1CMDjs1QPI/NAeXZCgcsobplm9B PEnMyG8z9zTmzI/0ZicntHJqIuJWMv8tTfn3JUdbYs6ISiXD3CFIDCd50XsEDScY bZb9b9OLtEXrlPU9TL2m8y6B8aArfoFIjBLk3hDl1uTo3oasX10c8ZmzuI0EUqDR SAEEALO/3L8r+vTMh4tNVQ6EdyMAKvgoBKaztg7+hNN/OKGCDMLf9ijLjVFIGRxF iSGOXio2au6lHSPiwhSUEpvw73T2mJlJ4Phu01mqzvaffpFwbbd97zaJ+4cqyk3n IwJeQCw8XGLkn39eDUMyhPaJqgS1FgavHNe1XW2i6ZUqi/AbABEBAAGIpQQYAQoA DwUCUqDRSAIbDAUJAeEzgAAKCRCQEqyJvU+PSCdlA/9C5U+B3RI20m73qvMWd+mZ NbmYAfD5ynHqLdBvLnsCD6EHdMKlyY6XDmj1z8jfwcBjbTa40U8qP6dEQTWBhHml 0E3713KUQeR2aYmt3hHBtQFDcVt7FfQImj4BIqJ+V6pNRLQCNOFbAC3RaXnwFMnN RAA6k7dYVvv+36h0LfJGSQ==""" filler = """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum """ #------------------------------------- exports.test_freestanding = (T,cb) -> [err,msg] = decode orig T.no_error err T.assert msg, "got a message object back" T.equal msg.pre, "", "msg.pre is empty" T.equal msg.post, "", "msg.post is empty" T.equal msg.raw(), orig, "msg raw was right" T.equal msg.fields.type, "PUBLIC KEY BLOCK", "we expected a public key block" T.equal msg.fields.checksum, "YJ8I", "checksum was as expected" T.equal (inside.split('\n').join('')), msg.body.toString('base64'), 'base64 encode/decode worked' cb() #------------------------------------- exports.test_context_1 = (T,cb) -> text = [ filler, orig , filler ].join "\n" [err,msg] = decode text T.no_error err T.assert msg, "got a message object back" T.equal msg.pre, (filler + "\n"), "msg.pre = filler" T.equal msg.post, ("\n" + filler), "msg.post = filler" T.equal msg.fields.type, "PUBLIC KEY BLOCK", "we expected a public key block" T.equal msg.raw(), orig, "msg raw was right" cb() #------------------------------------- exports.test_context_2 = (T,cb) -> text = [ filler, orig ].join("\n") [err,msg] = decode text T.no_error err T.assert msg, "got a message object back" T.equal msg.pre, (filler + "\n"), "msg.pre = filler" T.equal msg.fields.type, "PUBLIC KEY BLOCK", "we expected a public key block" T.equal msg.raw(), orig, "msg raw was right" cb() #------------------------------------- exports.test_context_3 = (T,cb) -> text = orig + filler [err,msg] = decode text T.no_error err T.assert msg, "got a message object back" T.equal msg.post, filler, "msg.post = filler" T.equal msg.fields.type, "PUBLIC KEY BLOCK", "we expected a public key block" T.equal msg.raw(), orig, "msg raw was right" cb() #------------------------------------- bad1 = """-----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org mI0EUqDRSAEEAMMt5Y4DoTF8g+2ahwPRNy9XOXvdGd3lvNnx/qpmnrogmQnTGgs6 pEu7EJWa4FG/omKK6YMY9EYrHUWs2yDZyazSP311GMKDvYAqVPdlk2ki3X57cf8f hMuUuE9exj9rBP9XzIys8uj6+U/P/RrcdbZJ+XkggF54xwkwApShs93FABEBAAG0 KlRlc3QgTWNUZXN0ZWUgKHB3IGlzICdhJykgPHRlc3RAZ21haWwuY29tPoi9BBMB CgAnBQJSoNFIAhsDBQkB4TOABQsJCAcDBRUKCQgLBRYCAwEAAh4BAheAAAoJEJAS rIm9T49IZvsEAI7jTFBn+VtJZklXJx5jUlbUN1CMDjs1QPI/NAeXZCgcsobplm9B PEnMyG8z9zTmzI/0ZicntHJqIuJWMv8tTfn3JUdbYs6ISiXD3CFIDCd50XsEDScY bZb9b9OLtEXrlPU9TL2m8y6B8aArfoFIjBLk3hDl1uTo3oasX10c8ZmzuI0EUqDR SAEEALO/3L8r+vTMh4tNVQ6EdyMAKvgoBKaztg7+hNN/OKGCDMLf9ijLjVFIGRxF iSGOXio2au6lHSPiwhSUEpvw73T2mJlJ4Phu01mqzvaffpFwbbd97zaJ+4cqyk3n IwJeQCw8XGLkn39eDUMyhPaJqgS1FgavHNe1XW2i6ZUqi/AbABEBAAGIpQQYAQoA DwUCUqDRSAIbDAUJAeEzgAAKCRCQEqyJvU+PSCdlA/9C5U+B3RI20m73qvMWd+mZ NbmYAfD5ynHqLdBvLnsCD6EHdMKlyY6XDmj1z8jfwcBjbTa40U8qP6dEQTWBhHml 0E3713KUQeR2aYmt3hHBtQFDcVt7FfQImj4BIqJ+V6pNRLQCNOFbAC3RaXnwFMnN RAA6k7dYVvv+36h0LfJGSQ== =YJ8i -----END PGP PUBLIC KEY BLOCK-----""" exports.failed_checksum_1 = (T,cb) -> [err,msg] = decode bad1 T.assert err, "error happened" T.equal err.message, "checksum mismatch", "the right error message" cb() #------------------------------------- bad2 = """-----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org mI0EUqDRSAEEAMMt5Y4DoTF8g+2ahwPRNy9XOXvdGd3lvNnx/qpmnrogmQnTGgs6 pEu7EJWa4FG/omKK6YMY9EYrHUWs2yDZyazSP311GMKDvYAqVPdlk2ki3X57cf8f hMuUuE9exj9rBP9XzIys8uj6+U/P/RrcdbZJ+XkggF54xwkwApShs93FABEBAAG0 KlRlc3QgTWNUZXN0ZWUgKHB3IGlzICdhJykgPHRlc3RAZ21haWwuY29tPoi9BBMB CgAnBQJSoNFIAhsDBQkB4TOABQsJCAcDBRUKCQgLBRYCAwEAAh4BAheAAAoJEJAS rIm9T49IZvsEAI7jTFBn+VtJZklXJx5jUlbUN1CMDjs1QPI/NAeXZCgcsobplm9B PEnMyG8z9zTmzI/0ZicntHJqIuJWMv8tTfn3JUdbYs6ISiXD3CFIDCd50XsEDScY bZb9b9OLtEXrlPU9TL2m8y6B8aArfoFIjBLk3hDl1uTo3oasX10c8ZmzuI0EUqDR SAEEALO/3L8r+vTMh4tNVQ6EdyMAKvgoBKaztg7+hNN/OKGCDMLf9ijLjVFIGRxF iSGOXio2au6lHSPiwhSUEpvw73T2mJlJ4Phu01mqzvaffpFwbbd97zaJ+4cqyk3n IwJeQCw8XGLkn39eDUMyhPaJqgS1FgavHNe1XW2i6ZUqi/AbABEBAAGIpQQYAQoA DwUCUqDRSAIbDAUJAeEzgAAKCRCQEqyJvU+PSCdlA/9C5U+B3RI20m73qvMWd+mZ NbmYAfD5ynHqLdBvLnsCD6EHdMKlyY6XDmj1z8jfwcBjbTa40U8qP6dEQTWBhHml 0E3713KUQeR2aYmt3hHBtQFDcVt7FfQImj4BIqJ+V6pNRLQCNOFbAC3RaXnwFMnN RAA6k6dYVvv+36h0LfJGSQ== =YJ8I -----END PGP PUBLIC KEY BLOCK-----""" exports.failed_checksum_2 = (T,cb) -> [err,msg] = decode bad2 T.assert err, "error happened" T.equal err.message, "checksum mismatch", "the right error message" cb() #-------------------------------------
81350
#----------------------------------------- {decode} = require "../../lib/openpgp/armor" #----------------------------------------- orig = """-----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org <KEY> -----END PGP PUBLIC KEY BLOCK-----""" inside = """<KEY>"" filler = """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum """ #------------------------------------- exports.test_freestanding = (T,cb) -> [err,msg] = decode orig T.no_error err T.assert msg, "got a message object back" T.equal msg.pre, "", "msg.pre is empty" T.equal msg.post, "", "msg.post is empty" T.equal msg.raw(), orig, "msg raw was right" T.equal msg.fields.type, "PUBLIC KEY BLOCK", "we expected a public key block" T.equal msg.fields.checksum, "YJ8I", "checksum was as expected" T.equal (inside.split('\n').join('')), msg.body.toString('base64'), 'base64 encode/decode worked' cb() #------------------------------------- exports.test_context_1 = (T,cb) -> text = [ filler, orig , filler ].join "\n" [err,msg] = decode text T.no_error err T.assert msg, "got a message object back" T.equal msg.pre, (filler + "\n"), "msg.pre = filler" T.equal msg.post, ("\n" + filler), "msg.post = filler" T.equal msg.fields.type, "PUBLIC KEY BLOCK", "we expected a public key block" T.equal msg.raw(), orig, "msg raw was right" cb() #------------------------------------- exports.test_context_2 = (T,cb) -> text = [ filler, orig ].join("\n") [err,msg] = decode text T.no_error err T.assert msg, "got a message object back" T.equal msg.pre, (filler + "\n"), "msg.pre = filler" T.equal msg.fields.type, "PUBLIC KEY BLOCK", "we expected a public key block" T.equal msg.raw(), orig, "msg raw was right" cb() #------------------------------------- exports.test_context_3 = (T,cb) -> text = orig + filler [err,msg] = decode text T.no_error err T.assert msg, "got a message object back" T.equal msg.post, filler, "msg.post = filler" T.equal msg.fields.type, "PUBLIC KEY BLOCK", "we expected a public key block" T.equal msg.raw(), orig, "msg raw was right" cb() #------------------------------------- bad1 = """-----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org <KEY> -----END PGP PUBLIC KEY BLOCK-----""" exports.failed_checksum_1 = (T,cb) -> [err,msg] = decode bad1 T.assert err, "error happened" T.equal err.message, "checksum mismatch", "the right error message" cb() #------------------------------------- bad2 = """-----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org <KEY> -----END PGP PUBLIC KEY BLOCK-----""" exports.failed_checksum_2 = (T,cb) -> [err,msg] = decode bad2 T.assert err, "error happened" T.equal err.message, "checksum mismatch", "the right error message" cb() #-------------------------------------
true
#----------------------------------------- {decode} = require "../../lib/openpgp/armor" #----------------------------------------- orig = """-----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org PI:KEY:<KEY>END_PI -----END PGP PUBLIC KEY BLOCK-----""" inside = """PI:KEY:<KEY>END_PI"" filler = """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum """ #------------------------------------- exports.test_freestanding = (T,cb) -> [err,msg] = decode orig T.no_error err T.assert msg, "got a message object back" T.equal msg.pre, "", "msg.pre is empty" T.equal msg.post, "", "msg.post is empty" T.equal msg.raw(), orig, "msg raw was right" T.equal msg.fields.type, "PUBLIC KEY BLOCK", "we expected a public key block" T.equal msg.fields.checksum, "YJ8I", "checksum was as expected" T.equal (inside.split('\n').join('')), msg.body.toString('base64'), 'base64 encode/decode worked' cb() #------------------------------------- exports.test_context_1 = (T,cb) -> text = [ filler, orig , filler ].join "\n" [err,msg] = decode text T.no_error err T.assert msg, "got a message object back" T.equal msg.pre, (filler + "\n"), "msg.pre = filler" T.equal msg.post, ("\n" + filler), "msg.post = filler" T.equal msg.fields.type, "PUBLIC KEY BLOCK", "we expected a public key block" T.equal msg.raw(), orig, "msg raw was right" cb() #------------------------------------- exports.test_context_2 = (T,cb) -> text = [ filler, orig ].join("\n") [err,msg] = decode text T.no_error err T.assert msg, "got a message object back" T.equal msg.pre, (filler + "\n"), "msg.pre = filler" T.equal msg.fields.type, "PUBLIC KEY BLOCK", "we expected a public key block" T.equal msg.raw(), orig, "msg raw was right" cb() #------------------------------------- exports.test_context_3 = (T,cb) -> text = orig + filler [err,msg] = decode text T.no_error err T.assert msg, "got a message object back" T.equal msg.post, filler, "msg.post = filler" T.equal msg.fields.type, "PUBLIC KEY BLOCK", "we expected a public key block" T.equal msg.raw(), orig, "msg raw was right" cb() #------------------------------------- bad1 = """-----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org PI:KEY:<KEY>END_PI -----END PGP PUBLIC KEY BLOCK-----""" exports.failed_checksum_1 = (T,cb) -> [err,msg] = decode bad1 T.assert err, "error happened" T.equal err.message, "checksum mismatch", "the right error message" cb() #------------------------------------- bad2 = """-----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org PI:KEY:<KEY>END_PI -----END PGP PUBLIC KEY BLOCK-----""" exports.failed_checksum_2 = (T,cb) -> [err,msg] = decode bad2 T.assert err, "error happened" T.equal err.message, "checksum mismatch", "the right error message" cb() #-------------------------------------
[ { "context": "###\nSectionsCtrl.coffee\nCopyright (C) 2014 ender xu <xuender@gmail.com>\n\nDistributed under terms of t", "end": 51, "score": 0.9997004270553589, "start": 43, "tag": "NAME", "value": "ender xu" }, { "context": "\nSectionsCtrl.coffee\nCopyright (C) 2014 ender xu <xuend...
src/note/sectionsCtrl.coffee
xuender/mindfulness
0
### SectionsCtrl.coffee Copyright (C) 2014 ender xu <xuender@gmail.com> Distributed under terms of the MIT license. ### SectionsCtrl = ($scope, $http, $log, $modal, ngTableParams, $filter, $q)-> $scope.$parent.name = 'section' $scope.books = [] $scope.selectBooks= -> # 书籍列表 $log.debug 'selectBooks' def = $q.defer() $http.get('/note/books').success((msg)-> if msg.ok $scope.books = msg.data $log.debug $scope.books def.resolve($scope.books) ) def $scope.bookTitle = (books)-> angular.forEach(books, (book)-> angular.forEach($scope.books, (b)-> if b.id == book.book book.bookTitle = b.title ) ) $scope.new = -> $modal.open( templateUrl: 'partials/note/section.html?4.html' controller: SectionCtrl backdrop: 'static' size: 'lg' resolve: section: -> del: -> false books: -> $scope.books ).result.then((s)-> $http.post('/note/section', s).success((data)-> if data.ok $scope.tableParams.reload() else alert(data.err) ) ,-> $log.info '取消' ) $scope.update = (s)-> $modal.open( templateUrl: 'partials/note/section.html?4.html' controller: SectionCtrl backdrop: 'static' size: 'lg' resolve: section: -> s del: -> true books: -> $scope.books ).result.then((s)-> $log.debug s if angular.isString(s) $http.delete('/note/section/' + s).success((data)-> if data.ok $scope.tableParams.reload() else alert(data.err) ) else $http.put('/note/section', s).success((data)-> if data.ok $scope.tableParams.reload() else alert(data.err) ) ,-> $log.info '取消' ) $scope.tableParams = new ngTableParams( page: 1 count: 10 sorting: book: 'asc' order: 'asc' , getData: ($defer, params)-> # 过滤 $http.post('/note/sections', Page: params.page() Count: params.count() Sorting: params.orderBy() Filter: params.filter() ).success((data)-> $log.debug data params.total(data.count) $scope.bookTitle(data.data) $defer.resolve(data.data) ) ) SectionsCtrl.$inject = [ '$scope' '$http' '$log' '$modal' 'ngTableParams' '$filter' '$q' ]
139733
### SectionsCtrl.coffee Copyright (C) 2014 <NAME> <<EMAIL>> Distributed under terms of the MIT license. ### SectionsCtrl = ($scope, $http, $log, $modal, ngTableParams, $filter, $q)-> $scope.$parent.name = 'section' $scope.books = [] $scope.selectBooks= -> # 书籍列表 $log.debug 'selectBooks' def = $q.defer() $http.get('/note/books').success((msg)-> if msg.ok $scope.books = msg.data $log.debug $scope.books def.resolve($scope.books) ) def $scope.bookTitle = (books)-> angular.forEach(books, (book)-> angular.forEach($scope.books, (b)-> if b.id == book.book book.bookTitle = b.title ) ) $scope.new = -> $modal.open( templateUrl: 'partials/note/section.html?4.html' controller: SectionCtrl backdrop: 'static' size: 'lg' resolve: section: -> del: -> false books: -> $scope.books ).result.then((s)-> $http.post('/note/section', s).success((data)-> if data.ok $scope.tableParams.reload() else alert(data.err) ) ,-> $log.info '取消' ) $scope.update = (s)-> $modal.open( templateUrl: 'partials/note/section.html?4.html' controller: SectionCtrl backdrop: 'static' size: 'lg' resolve: section: -> s del: -> true books: -> $scope.books ).result.then((s)-> $log.debug s if angular.isString(s) $http.delete('/note/section/' + s).success((data)-> if data.ok $scope.tableParams.reload() else alert(data.err) ) else $http.put('/note/section', s).success((data)-> if data.ok $scope.tableParams.reload() else alert(data.err) ) ,-> $log.info '取消' ) $scope.tableParams = new ngTableParams( page: 1 count: 10 sorting: book: 'asc' order: 'asc' , getData: ($defer, params)-> # 过滤 $http.post('/note/sections', Page: params.page() Count: params.count() Sorting: params.orderBy() Filter: params.filter() ).success((data)-> $log.debug data params.total(data.count) $scope.bookTitle(data.data) $defer.resolve(data.data) ) ) SectionsCtrl.$inject = [ '$scope' '$http' '$log' '$modal' 'ngTableParams' '$filter' '$q' ]
true
### SectionsCtrl.coffee Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> Distributed under terms of the MIT license. ### SectionsCtrl = ($scope, $http, $log, $modal, ngTableParams, $filter, $q)-> $scope.$parent.name = 'section' $scope.books = [] $scope.selectBooks= -> # 书籍列表 $log.debug 'selectBooks' def = $q.defer() $http.get('/note/books').success((msg)-> if msg.ok $scope.books = msg.data $log.debug $scope.books def.resolve($scope.books) ) def $scope.bookTitle = (books)-> angular.forEach(books, (book)-> angular.forEach($scope.books, (b)-> if b.id == book.book book.bookTitle = b.title ) ) $scope.new = -> $modal.open( templateUrl: 'partials/note/section.html?4.html' controller: SectionCtrl backdrop: 'static' size: 'lg' resolve: section: -> del: -> false books: -> $scope.books ).result.then((s)-> $http.post('/note/section', s).success((data)-> if data.ok $scope.tableParams.reload() else alert(data.err) ) ,-> $log.info '取消' ) $scope.update = (s)-> $modal.open( templateUrl: 'partials/note/section.html?4.html' controller: SectionCtrl backdrop: 'static' size: 'lg' resolve: section: -> s del: -> true books: -> $scope.books ).result.then((s)-> $log.debug s if angular.isString(s) $http.delete('/note/section/' + s).success((data)-> if data.ok $scope.tableParams.reload() else alert(data.err) ) else $http.put('/note/section', s).success((data)-> if data.ok $scope.tableParams.reload() else alert(data.err) ) ,-> $log.info '取消' ) $scope.tableParams = new ngTableParams( page: 1 count: 10 sorting: book: 'asc' order: 'asc' , getData: ($defer, params)-> # 过滤 $http.post('/note/sections', Page: params.page() Count: params.count() Sorting: params.orderBy() Filter: params.filter() ).success((data)-> $log.debug data params.total(data.count) $scope.bookTitle(data.data) $defer.resolve(data.data) ) ) SectionsCtrl.$inject = [ '$scope' '$http' '$log' '$modal' 'ngTableParams' '$filter' '$q' ]
[ { "context": "class Person extends Object\n constructor: (@firstName, @lastName, gender) ->\n @_gender = gender\n ", "end": 54, "score": 0.7330367565155029, "start": 45, "tag": "USERNAME", "value": "firstName" }, { "context": ":\", ->\n\n beforeEach ->\n @person = new Pers...
test/support/accessor_test.js.coffee
zhangkaiyufromdongbei/CocoaBean
0
class Person extends Object constructor: (@firstName, @lastName, gender) -> @_gender = gender @_familyMembers = ['dad', 'mom', 'brother', 'sister'] @_handPhones = ['iPhone', 'Samsung'] @property "readwrite", "firstName" @property "lastName" @property "strong", "age" @property "readonly", "gender" @property "writeonly", "reputation" @property "name", set: (newName) -> [@firstName, @lastName] = newName.split ' ' get: -> "#{@firstName} #{@lastName}" @property "readwrite", "copy", "familyMembers" @property "readonly", "strong", "handPhones" describe "Property accessor:", -> beforeEach -> @person = new Person("James", "Last", "male") describe "accessibility:", -> describe "readwrite property", -> it "can set new value", -> @person.firstName = "First" @person.lastName = "Love" expect(@person.firstName).toEqual "First" expect(@person.lastName).toEqual "Love" it "can get current value", -> expect(@person.firstName).toEqual "James" expect(@person.lastName).toEqual "Last" describe "readonly property", -> it "can get current value", -> expect(@person.gender).toEqual "male" it "cannot set new value", -> expect( -> @person.gender = "female" ).toThrow() describe "writeonly property", -> it "cannot get current value", -> expect( -> @person.reputation ).toThrow() it "can set current value", -> @person.reputation = "nice" expect(@person._reputation).toEqual "nice" describe "referencing:", -> describe "strong", -> it "returns itself when gets", -> handPhones = @person.handPhones handPhones.push('China Xiaomi') expect(@person.handPhones.length).toBe 3 describe "copy", -> it "returns a copy of the object", -> familyMembers = @person.familyMembers familyMembers.push('monster') expect(@person.familyMembers.length).toBe 4 describe "accessor functions:", -> describe "setter", -> it "is used when specified", -> @person.name = "Equal Humanity" expect(@person.lastName).toBe "Humanity" expect(@person.firstName).toBe "Equal" it "has default setter when not specified", -> @person.age = 30 expect(@person.age).toBe 30 xit "is not used if property is readonly", -> describe "getter", -> it "is used when specified", -> @person.firstName = "Jasmine" expect(@person.name).toBe "Jasmine Last" it "has default getter when not specified", -> @person.age = 40 expect(@person.age).toBe 40 xit "is not used if property is writeonly", -> it "throw errors on defining if argument count is less than 1", -> expect( -> Person.property() ).toThrow()
129007
class Person extends Object constructor: (@firstName, @lastName, gender) -> @_gender = gender @_familyMembers = ['dad', 'mom', 'brother', 'sister'] @_handPhones = ['iPhone', 'Samsung'] @property "readwrite", "firstName" @property "lastName" @property "strong", "age" @property "readonly", "gender" @property "writeonly", "reputation" @property "name", set: (newName) -> [@firstName, @lastName] = newName.split ' ' get: -> "#{@firstName} #{@lastName}" @property "readwrite", "copy", "familyMembers" @property "readonly", "strong", "handPhones" describe "Property accessor:", -> beforeEach -> @person = new Person("<NAME>", "<NAME>", "male") describe "accessibility:", -> describe "readwrite property", -> it "can set new value", -> @person.firstName = "<NAME>" @person.lastName = "<NAME>" expect(@person.firstName).toEqual "<NAME>" expect(@person.lastName).toEqual "<NAME>" it "can get current value", -> expect(@person.firstName).toEqual "<NAME>" expect(@person.lastName).toEqual "<NAME>" describe "readonly property", -> it "can get current value", -> expect(@person.gender).toEqual "male" it "cannot set new value", -> expect( -> @person.gender = "female" ).toThrow() describe "writeonly property", -> it "cannot get current value", -> expect( -> @person.reputation ).toThrow() it "can set current value", -> @person.reputation = "nice" expect(@person._reputation).toEqual "nice" describe "referencing:", -> describe "strong", -> it "returns itself when gets", -> handPhones = @person.handPhones handPhones.push('China Xiaomi') expect(@person.handPhones.length).toBe 3 describe "copy", -> it "returns a copy of the object", -> familyMembers = @person.familyMembers familyMembers.push('monster') expect(@person.familyMembers.length).toBe 4 describe "accessor functions:", -> describe "setter", -> it "is used when specified", -> @person.name = "Equal Humanity" expect(@person.lastName).toBe "Humanity" expect(@person.firstName).toBe "Equal" it "has default setter when not specified", -> @person.age = 30 expect(@person.age).toBe 30 xit "is not used if property is readonly", -> describe "getter", -> it "is used when specified", -> @person.firstName = "<NAME>" expect(@person.name).toBe "<NAME>" it "has default getter when not specified", -> @person.age = 40 expect(@person.age).toBe 40 xit "is not used if property is writeonly", -> it "throw errors on defining if argument count is less than 1", -> expect( -> Person.property() ).toThrow()
true
class Person extends Object constructor: (@firstName, @lastName, gender) -> @_gender = gender @_familyMembers = ['dad', 'mom', 'brother', 'sister'] @_handPhones = ['iPhone', 'Samsung'] @property "readwrite", "firstName" @property "lastName" @property "strong", "age" @property "readonly", "gender" @property "writeonly", "reputation" @property "name", set: (newName) -> [@firstName, @lastName] = newName.split ' ' get: -> "#{@firstName} #{@lastName}" @property "readwrite", "copy", "familyMembers" @property "readonly", "strong", "handPhones" describe "Property accessor:", -> beforeEach -> @person = new Person("PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "male") describe "accessibility:", -> describe "readwrite property", -> it "can set new value", -> @person.firstName = "PI:NAME:<NAME>END_PI" @person.lastName = "PI:NAME:<NAME>END_PI" expect(@person.firstName).toEqual "PI:NAME:<NAME>END_PI" expect(@person.lastName).toEqual "PI:NAME:<NAME>END_PI" it "can get current value", -> expect(@person.firstName).toEqual "PI:NAME:<NAME>END_PI" expect(@person.lastName).toEqual "PI:NAME:<NAME>END_PI" describe "readonly property", -> it "can get current value", -> expect(@person.gender).toEqual "male" it "cannot set new value", -> expect( -> @person.gender = "female" ).toThrow() describe "writeonly property", -> it "cannot get current value", -> expect( -> @person.reputation ).toThrow() it "can set current value", -> @person.reputation = "nice" expect(@person._reputation).toEqual "nice" describe "referencing:", -> describe "strong", -> it "returns itself when gets", -> handPhones = @person.handPhones handPhones.push('China Xiaomi') expect(@person.handPhones.length).toBe 3 describe "copy", -> it "returns a copy of the object", -> familyMembers = @person.familyMembers familyMembers.push('monster') expect(@person.familyMembers.length).toBe 4 describe "accessor functions:", -> describe "setter", -> it "is used when specified", -> @person.name = "Equal Humanity" expect(@person.lastName).toBe "Humanity" expect(@person.firstName).toBe "Equal" it "has default setter when not specified", -> @person.age = 30 expect(@person.age).toBe 30 xit "is not used if property is readonly", -> describe "getter", -> it "is used when specified", -> @person.firstName = "PI:NAME:<NAME>END_PI" expect(@person.name).toBe "PI:NAME:<NAME>END_PI" it "has default getter when not specified", -> @person.age = 40 expect(@person.age).toBe 40 xit "is not used if property is writeonly", -> it "throw errors on defining if argument count is less than 1", -> expect( -> Person.property() ).toThrow()
[ { "context": "tFieldDBCorpusObject responseJSON\n # TODO @jrwdunham: should this `set` be a `save`?\n if fiel", "end": 1475, "score": 0.9840744733810425, "start": 1465, "tag": "USERNAME", "value": "@jrwdunham" }, { "context": " removeUser: true\n usern...
app/scripts/models/corpus.coffee
OpenSourceFieldlinguistics/dative
7
define [ 'underscore' 'backbone' './base' './../utils/utils' ], (_, Backbone, BaseModel, utils) -> # Corpus Model # ------------ # # A model for FieldDB corpora. A `CorpusModel` is instantiated with a pouchname # for the corpus. This is a unique, spaceless, lowercase name that begins with # its creator's username. # # A corpus model's data must be retrieved by two requests. (1) retrieves the # bulk of the corpus data while (2) returns the users with access to the # corpus: # # 1. @fetch # 2. @fetchUsers # # Three other server-request methods are defined here: # # 3. @removeUserFromCorpus # 4. @grantRoleToUser # 5. @updateCorpus class CorpusModel extends BaseModel initialize: (options) -> @applicationSettings = options.applicationSettings @pouchname = options.pouchname ############################################################################ # CORS methods ############################################################################ # Fetch the corpus data. # GET `<CorpusServiceURL>/<corpusname>/_design/deprecated/_view/private_corpuses` fetch: -> @trigger 'fetchStart' CorpusModel.cors.request( method: 'GET' timeout: 10000 url: "#{@getCorpusServerURL()}/_design/deprecated/_view/private_corpuses" onload: (responseJSON) => fieldDBCorpusObject = @getFieldDBCorpusObject responseJSON # TODO @jrwdunham: should this `set` be a `save`? if fieldDBCorpusObject then @set fieldDBCorpusObject @trigger 'fetchEnd' onerror: (responseJSON) => console.log "Failed to fetch a corpus at #{@url()}." @trigger 'fetchEnd' ontimeout: => console.log "Failed to fetch a corpus at #{@url()}. Request timed out." @trigger 'fetchEnd' ) # Fetch the users with access to a corpus. # POST `<AuthServiceURL>/corpusteam` fetchUsers: -> @trigger 'fetchUsersStart' payload = @getDefaultPayload() CorpusModel.cors.request( method: 'POST' timeout: 10000 url: "#{payload.authUrl}/corpusteam" payload: payload onload: (responseJSON) => if responseJSON.users @set 'users', responseJSON.users @trigger 'fetchUsersEnd' else @trigger 'fetchUsersEnd' console.log 'Failed request to /corpusteam: no users attribute.' onerror: (responseJSON) => @trigger 'fetchUsersEnd' console.log 'Failed request to /corpusteam: error.' ontimeout: => @trigger 'fetchUsersEnd' console.log 'Failed request to /corpusteam: timed out.' ) # Grant a role on a corpus to a user. # POST `<AuthServiceURL>/updateroles` grantRoleToUser: (role, username) -> @trigger 'grantRoleToUserStart' payload = @getDefaultPayload() payload.userRoleInfo = admin: if role is 'admin' then true else false writer: if role is 'reader' then false else true reader: true pouchname: payload.pouchname role: @getFieldDBRole role usernameToModify: username CorpusModel.cors.request( method: 'POST' timeout: 10000 url: "#{payload.authUrl}/updateroles" payload: payload onload: (responseJSON) => @trigger 'grantRoleToUserEnd' if responseJSON.corpusadded @trigger 'grantRoleToUserSuccess', role, username else console.log 'Failed request to /updateroles: no `corpusadded` attribute.' onerror: (responseJSON) => @trigger 'grantRoleToUserEnd' console.log 'Failed request to /updateroles: error.' ontimeout: => @trigger 'grantRoleToUserEnd' console.log 'Failed request to /updateroles: timed out.' ) # Remove a user from a corpus. # POST `<AuthServiceURL>/updateroles` removeUserFromCorpus: (username) -> @trigger 'removeUserFromCorpusStart' payload = @getDefaultPayload() payload.userRoleInfo = pouchname: payload.pouchname removeUser: true usernameToModify: username CorpusModel.cors.request( method: 'POST' timeout: 10000 url: "#{payload.authUrl}/updateroles" payload: payload onload: (responseJSON) => @trigger 'removeUserFromCorpusEnd' if responseJSON.corpusadded @trigger 'removeUserFromCorpusSuccess', username else console.log 'Failed request to /updateroles: no `corpusadded` attribute.' onerror: (responseJSON) => @trigger 'removeUserFromCorpusEnd' console.log 'Failed request to /updateroles: error.' ontimeout: => @trigger 'removeUserFromCorpusEnd' console.log 'Failed request to /updateroles: timed out.' ) # NOTE: @jrwdunham, @cesine: NOT IMPLEMENTED # See https://github.com/jrwdunham/dative/issues/78 # Update the details of a corpus # PUT `<CorpusServiceURL>/<pouchname>/<corpusUUID> # QUESTIONS: # 1. do I need to manually change `titleAsURL`? What about the other fields? # TODO: # set title to new title # set description to new description # update dateModified timestamp: (new Date().getTime() # allow user to modify gravatar # show gravatar in corpus list # updateCorpus: (title, description) -> console.log 'in updateCorpus of corpus model' console.log JSON.stringify(@, undefined, 2) # for attr in _.keys(@attributes).sort() # if attr not in ['applicationSettings', 'isActive'] # console.log '\n' # console.log attr # console.log JSON.stringify(@attributes[attr]) # console.log '\n' updateCorpus_: (title, description) -> @trigger 'updateCorpusStart' payload = @getDefaultPayload() payload.userRoleInfo = pouchname: payload.pouchname removeUser: true usernameToModify: username CorpusModel.cors.request( method: 'PUT' timeout: 10000 url: "#{payload.authUrl}/updateroles" payload: payload onload: (responseJSON) => @trigger 'updateCorpusEnd' if responseJSON.corpusadded @trigger 'updateCorpusSuccess', username else console.log 'Failed request to /updateroles: no `corpusadded` attribute.' onerror: (responseJSON) => @trigger 'updateCorpusEnd' console.log 'Failed request to /updateroles: error.' ontimeout: => @trigger 'updateCorpusEnd' console.log 'Failed request to /updateroles: timed out.' ) ### # This is the object that is sent to PUT `<CorpusServiceURL>/<pouchname>/<corpusUUID> # on an update request. It is _id: "63ff8fd7b5be6becbd9e5413b3060dd5" _rev: "12-d1e6a51f42377dc3803207bbf6a13baa" api: "private_corpuses" authUrl: FieldDB.Database.prototype.BASE_AUTH_URL collection: "private_corpuses" comments: [] confidential: {fieldDBtype: "Confidential", secretkey: "e14714cb-ddfb-5e4e-bad9-2a75d573dbe0",…} conversationFields: [,…] copyright: "Default: Add names of the copyright holders of the corpus." *** dateModified: 1421953770590 # timestamp of last modification (I think) datumFields: [{fieldDBtype: "DatumField", labelFieldLinguists: "Judgement", mask: "grammatical",…},…] datumStates: [{color: "success", showInSearchResults: "checked", selected: "selected", state: "Checked"},…] dbname: "jrwdunham-firstcorpus" description: "Best corpus ever" fieldDBtype: "Corpus" *** gravatar: "33b8cbbfd6c49148ad31ed95e67b4390" license: {title: "Default: Creative Commons Attribution-ShareAlike (CC BY-SA).",…} modifiedByUser: {value: "jrwdunham, jrwdunham, jrwdunham, jrwdunham, jrwdunham",…} participantFields: [,…] pouchname: "jrwdunham-firstcorpus" publicCorpus: "Private" searchKeywords: "Froggo" sessionFields: [{fieldDBtype: "DatumField", labelFieldLinguists: "Goal", value: "", mask: "", encryptedValue: "",…},…] termsOfUse: {,…} *** timestamp: 1399303339523 # timestamp of corpus creation (I think) title: "Big Bear Corpus" titleAsUrl: "big_bear_corpus" url: FieldDB.Database.prototype.BASE_DB_URL+"/jrwdunham-firstcorpus" version: "v2.38.16" ### ############################################################################ # utility methods ############################################################################ getCorpusServerURL: -> url = @applicationSettings.get 'baseDBURL' "#{url}/#{@pouchname}" getFieldDBCorpusObject: (responseJSON) -> result = {} if responseJSON.rows? [..., tmp] = responseJSON.rows # Last element in array, a la CoffeeScript result = tmp.value getDefaultPayload: -> authUrl: @applicationSettings.get?('activeServer')?.get?('url') username: @applicationSettings.get?('username') password: @applicationSettings.get?('password') # TODO trigger authenticate:mustconfirmidentity serverCode: @applicationSettings.get?('activeServer')?.get?('serverCode') pouchname: @get 'pouchname' getFieldDBRole: (role) -> switch role when 'admin' then 'admin' when 'writer' then 'read_write' when 'reader' then 'read_only'
73379
define [ 'underscore' 'backbone' './base' './../utils/utils' ], (_, Backbone, BaseModel, utils) -> # Corpus Model # ------------ # # A model for FieldDB corpora. A `CorpusModel` is instantiated with a pouchname # for the corpus. This is a unique, spaceless, lowercase name that begins with # its creator's username. # # A corpus model's data must be retrieved by two requests. (1) retrieves the # bulk of the corpus data while (2) returns the users with access to the # corpus: # # 1. @fetch # 2. @fetchUsers # # Three other server-request methods are defined here: # # 3. @removeUserFromCorpus # 4. @grantRoleToUser # 5. @updateCorpus class CorpusModel extends BaseModel initialize: (options) -> @applicationSettings = options.applicationSettings @pouchname = options.pouchname ############################################################################ # CORS methods ############################################################################ # Fetch the corpus data. # GET `<CorpusServiceURL>/<corpusname>/_design/deprecated/_view/private_corpuses` fetch: -> @trigger 'fetchStart' CorpusModel.cors.request( method: 'GET' timeout: 10000 url: "#{@getCorpusServerURL()}/_design/deprecated/_view/private_corpuses" onload: (responseJSON) => fieldDBCorpusObject = @getFieldDBCorpusObject responseJSON # TODO @jrwdunham: should this `set` be a `save`? if fieldDBCorpusObject then @set fieldDBCorpusObject @trigger 'fetchEnd' onerror: (responseJSON) => console.log "Failed to fetch a corpus at #{@url()}." @trigger 'fetchEnd' ontimeout: => console.log "Failed to fetch a corpus at #{@url()}. Request timed out." @trigger 'fetchEnd' ) # Fetch the users with access to a corpus. # POST `<AuthServiceURL>/corpusteam` fetchUsers: -> @trigger 'fetchUsersStart' payload = @getDefaultPayload() CorpusModel.cors.request( method: 'POST' timeout: 10000 url: "#{payload.authUrl}/corpusteam" payload: payload onload: (responseJSON) => if responseJSON.users @set 'users', responseJSON.users @trigger 'fetchUsersEnd' else @trigger 'fetchUsersEnd' console.log 'Failed request to /corpusteam: no users attribute.' onerror: (responseJSON) => @trigger 'fetchUsersEnd' console.log 'Failed request to /corpusteam: error.' ontimeout: => @trigger 'fetchUsersEnd' console.log 'Failed request to /corpusteam: timed out.' ) # Grant a role on a corpus to a user. # POST `<AuthServiceURL>/updateroles` grantRoleToUser: (role, username) -> @trigger 'grantRoleToUserStart' payload = @getDefaultPayload() payload.userRoleInfo = admin: if role is 'admin' then true else false writer: if role is 'reader' then false else true reader: true pouchname: payload.pouchname role: @getFieldDBRole role usernameToModify: username CorpusModel.cors.request( method: 'POST' timeout: 10000 url: "#{payload.authUrl}/updateroles" payload: payload onload: (responseJSON) => @trigger 'grantRoleToUserEnd' if responseJSON.corpusadded @trigger 'grantRoleToUserSuccess', role, username else console.log 'Failed request to /updateroles: no `corpusadded` attribute.' onerror: (responseJSON) => @trigger 'grantRoleToUserEnd' console.log 'Failed request to /updateroles: error.' ontimeout: => @trigger 'grantRoleToUserEnd' console.log 'Failed request to /updateroles: timed out.' ) # Remove a user from a corpus. # POST `<AuthServiceURL>/updateroles` removeUserFromCorpus: (username) -> @trigger 'removeUserFromCorpusStart' payload = @getDefaultPayload() payload.userRoleInfo = pouchname: payload.pouchname removeUser: true usernameToModify: username CorpusModel.cors.request( method: 'POST' timeout: 10000 url: "#{payload.authUrl}/updateroles" payload: payload onload: (responseJSON) => @trigger 'removeUserFromCorpusEnd' if responseJSON.corpusadded @trigger 'removeUserFromCorpusSuccess', username else console.log 'Failed request to /updateroles: no `corpusadded` attribute.' onerror: (responseJSON) => @trigger 'removeUserFromCorpusEnd' console.log 'Failed request to /updateroles: error.' ontimeout: => @trigger 'removeUserFromCorpusEnd' console.log 'Failed request to /updateroles: timed out.' ) # NOTE: @jrwdunham, @cesine: NOT IMPLEMENTED # See https://github.com/jrwdunham/dative/issues/78 # Update the details of a corpus # PUT `<CorpusServiceURL>/<pouchname>/<corpusUUID> # QUESTIONS: # 1. do I need to manually change `titleAsURL`? What about the other fields? # TODO: # set title to new title # set description to new description # update dateModified timestamp: (new Date().getTime() # allow user to modify gravatar # show gravatar in corpus list # updateCorpus: (title, description) -> console.log 'in updateCorpus of corpus model' console.log JSON.stringify(@, undefined, 2) # for attr in _.keys(@attributes).sort() # if attr not in ['applicationSettings', 'isActive'] # console.log '\n' # console.log attr # console.log JSON.stringify(@attributes[attr]) # console.log '\n' updateCorpus_: (title, description) -> @trigger 'updateCorpusStart' payload = @getDefaultPayload() payload.userRoleInfo = pouchname: payload.pouchname removeUser: true usernameToModify: username CorpusModel.cors.request( method: 'PUT' timeout: 10000 url: "#{payload.authUrl}/updateroles" payload: payload onload: (responseJSON) => @trigger 'updateCorpusEnd' if responseJSON.corpusadded @trigger 'updateCorpusSuccess', username else console.log 'Failed request to /updateroles: no `corpusadded` attribute.' onerror: (responseJSON) => @trigger 'updateCorpusEnd' console.log 'Failed request to /updateroles: error.' ontimeout: => @trigger 'updateCorpusEnd' console.log 'Failed request to /updateroles: timed out.' ) ### # This is the object that is sent to PUT `<CorpusServiceURL>/<pouchname>/<corpusUUID> # on an update request. It is _id: "63ff8fd7b5be6becbd9e5413b3060dd5" _rev: "12-d1e6a51f42377dc3803207bbf6a13baa" api: "private_corpuses" authUrl: FieldDB.Database.prototype.BASE_AUTH_URL collection: "private_corpuses" comments: [] confidential: {fieldDBtype: "Confidential", secretkey: "<KEY>",…} conversationFields: [,…] copyright: "Default: Add names of the copyright holders of the corpus." *** dateModified: 1421953770590 # timestamp of last modification (I think) datumFields: [{fieldDBtype: "DatumField", labelFieldLinguists: "Judgement", mask: "grammatical",…},…] datumStates: [{color: "success", showInSearchResults: "checked", selected: "selected", state: "Checked"},…] dbname: "jrwdunham-firstcorpus" description: "Best corpus ever" fieldDBtype: "Corpus" *** gravatar: "33b8cbbfd6c4<PASSWORD>8<PASSWORD>67b<PASSWORD>0" license: {title: "Default: Creative Commons Attribution-ShareAlike (CC BY-SA).",…} modifiedByUser: {value: "jrwdunham, jrwdunham, jrwdunham, jrwdunham, jrwdunham",…} participantFields: [,…] pouchname: "jrwdunham-firstcorpus" publicCorpus: "Private" searchKeywords: "Froggo" sessionFields: [{fieldDBtype: "DatumField", labelFieldLinguists: "Goal", value: "", mask: "", encryptedValue: "",…},…] termsOfUse: {,…} *** timestamp: 1399303339523 # timestamp of corpus creation (I think) title: "Big Bear Corpus" titleAsUrl: "big_bear_corpus" url: FieldDB.Database.prototype.BASE_DB_URL+"/jrwdunham-firstcorpus" version: "v2.38.16" ### ############################################################################ # utility methods ############################################################################ getCorpusServerURL: -> url = @applicationSettings.get 'baseDBURL' "#{url}/#{@pouchname}" getFieldDBCorpusObject: (responseJSON) -> result = {} if responseJSON.rows? [..., tmp] = responseJSON.rows # Last element in array, a la CoffeeScript result = tmp.value getDefaultPayload: -> authUrl: @applicationSettings.get?('activeServer')?.get?('url') username: @applicationSettings.get?('username') password: @applicationSettings.get?('password') # TODO trigger authenticate:mustconfirmidentity serverCode: @applicationSettings.get?('activeServer')?.get?('serverCode') pouchname: @get 'pouchname' getFieldDBRole: (role) -> switch role when 'admin' then 'admin' when 'writer' then 'read_write' when 'reader' then 'read_only'
true
define [ 'underscore' 'backbone' './base' './../utils/utils' ], (_, Backbone, BaseModel, utils) -> # Corpus Model # ------------ # # A model for FieldDB corpora. A `CorpusModel` is instantiated with a pouchname # for the corpus. This is a unique, spaceless, lowercase name that begins with # its creator's username. # # A corpus model's data must be retrieved by two requests. (1) retrieves the # bulk of the corpus data while (2) returns the users with access to the # corpus: # # 1. @fetch # 2. @fetchUsers # # Three other server-request methods are defined here: # # 3. @removeUserFromCorpus # 4. @grantRoleToUser # 5. @updateCorpus class CorpusModel extends BaseModel initialize: (options) -> @applicationSettings = options.applicationSettings @pouchname = options.pouchname ############################################################################ # CORS methods ############################################################################ # Fetch the corpus data. # GET `<CorpusServiceURL>/<corpusname>/_design/deprecated/_view/private_corpuses` fetch: -> @trigger 'fetchStart' CorpusModel.cors.request( method: 'GET' timeout: 10000 url: "#{@getCorpusServerURL()}/_design/deprecated/_view/private_corpuses" onload: (responseJSON) => fieldDBCorpusObject = @getFieldDBCorpusObject responseJSON # TODO @jrwdunham: should this `set` be a `save`? if fieldDBCorpusObject then @set fieldDBCorpusObject @trigger 'fetchEnd' onerror: (responseJSON) => console.log "Failed to fetch a corpus at #{@url()}." @trigger 'fetchEnd' ontimeout: => console.log "Failed to fetch a corpus at #{@url()}. Request timed out." @trigger 'fetchEnd' ) # Fetch the users with access to a corpus. # POST `<AuthServiceURL>/corpusteam` fetchUsers: -> @trigger 'fetchUsersStart' payload = @getDefaultPayload() CorpusModel.cors.request( method: 'POST' timeout: 10000 url: "#{payload.authUrl}/corpusteam" payload: payload onload: (responseJSON) => if responseJSON.users @set 'users', responseJSON.users @trigger 'fetchUsersEnd' else @trigger 'fetchUsersEnd' console.log 'Failed request to /corpusteam: no users attribute.' onerror: (responseJSON) => @trigger 'fetchUsersEnd' console.log 'Failed request to /corpusteam: error.' ontimeout: => @trigger 'fetchUsersEnd' console.log 'Failed request to /corpusteam: timed out.' ) # Grant a role on a corpus to a user. # POST `<AuthServiceURL>/updateroles` grantRoleToUser: (role, username) -> @trigger 'grantRoleToUserStart' payload = @getDefaultPayload() payload.userRoleInfo = admin: if role is 'admin' then true else false writer: if role is 'reader' then false else true reader: true pouchname: payload.pouchname role: @getFieldDBRole role usernameToModify: username CorpusModel.cors.request( method: 'POST' timeout: 10000 url: "#{payload.authUrl}/updateroles" payload: payload onload: (responseJSON) => @trigger 'grantRoleToUserEnd' if responseJSON.corpusadded @trigger 'grantRoleToUserSuccess', role, username else console.log 'Failed request to /updateroles: no `corpusadded` attribute.' onerror: (responseJSON) => @trigger 'grantRoleToUserEnd' console.log 'Failed request to /updateroles: error.' ontimeout: => @trigger 'grantRoleToUserEnd' console.log 'Failed request to /updateroles: timed out.' ) # Remove a user from a corpus. # POST `<AuthServiceURL>/updateroles` removeUserFromCorpus: (username) -> @trigger 'removeUserFromCorpusStart' payload = @getDefaultPayload() payload.userRoleInfo = pouchname: payload.pouchname removeUser: true usernameToModify: username CorpusModel.cors.request( method: 'POST' timeout: 10000 url: "#{payload.authUrl}/updateroles" payload: payload onload: (responseJSON) => @trigger 'removeUserFromCorpusEnd' if responseJSON.corpusadded @trigger 'removeUserFromCorpusSuccess', username else console.log 'Failed request to /updateroles: no `corpusadded` attribute.' onerror: (responseJSON) => @trigger 'removeUserFromCorpusEnd' console.log 'Failed request to /updateroles: error.' ontimeout: => @trigger 'removeUserFromCorpusEnd' console.log 'Failed request to /updateroles: timed out.' ) # NOTE: @jrwdunham, @cesine: NOT IMPLEMENTED # See https://github.com/jrwdunham/dative/issues/78 # Update the details of a corpus # PUT `<CorpusServiceURL>/<pouchname>/<corpusUUID> # QUESTIONS: # 1. do I need to manually change `titleAsURL`? What about the other fields? # TODO: # set title to new title # set description to new description # update dateModified timestamp: (new Date().getTime() # allow user to modify gravatar # show gravatar in corpus list # updateCorpus: (title, description) -> console.log 'in updateCorpus of corpus model' console.log JSON.stringify(@, undefined, 2) # for attr in _.keys(@attributes).sort() # if attr not in ['applicationSettings', 'isActive'] # console.log '\n' # console.log attr # console.log JSON.stringify(@attributes[attr]) # console.log '\n' updateCorpus_: (title, description) -> @trigger 'updateCorpusStart' payload = @getDefaultPayload() payload.userRoleInfo = pouchname: payload.pouchname removeUser: true usernameToModify: username CorpusModel.cors.request( method: 'PUT' timeout: 10000 url: "#{payload.authUrl}/updateroles" payload: payload onload: (responseJSON) => @trigger 'updateCorpusEnd' if responseJSON.corpusadded @trigger 'updateCorpusSuccess', username else console.log 'Failed request to /updateroles: no `corpusadded` attribute.' onerror: (responseJSON) => @trigger 'updateCorpusEnd' console.log 'Failed request to /updateroles: error.' ontimeout: => @trigger 'updateCorpusEnd' console.log 'Failed request to /updateroles: timed out.' ) ### # This is the object that is sent to PUT `<CorpusServiceURL>/<pouchname>/<corpusUUID> # on an update request. It is _id: "63ff8fd7b5be6becbd9e5413b3060dd5" _rev: "12-d1e6a51f42377dc3803207bbf6a13baa" api: "private_corpuses" authUrl: FieldDB.Database.prototype.BASE_AUTH_URL collection: "private_corpuses" comments: [] confidential: {fieldDBtype: "Confidential", secretkey: "PI:KEY:<KEY>END_PI",…} conversationFields: [,…] copyright: "Default: Add names of the copyright holders of the corpus." *** dateModified: 1421953770590 # timestamp of last modification (I think) datumFields: [{fieldDBtype: "DatumField", labelFieldLinguists: "Judgement", mask: "grammatical",…},…] datumStates: [{color: "success", showInSearchResults: "checked", selected: "selected", state: "Checked"},…] dbname: "jrwdunham-firstcorpus" description: "Best corpus ever" fieldDBtype: "Corpus" *** gravatar: "33b8cbbfd6c4PI:PASSWORD:<PASSWORD>END_PI8PI:PASSWORD:<PASSWORD>END_PI67bPI:PASSWORD:<PASSWORD>END_PI0" license: {title: "Default: Creative Commons Attribution-ShareAlike (CC BY-SA).",…} modifiedByUser: {value: "jrwdunham, jrwdunham, jrwdunham, jrwdunham, jrwdunham",…} participantFields: [,…] pouchname: "jrwdunham-firstcorpus" publicCorpus: "Private" searchKeywords: "Froggo" sessionFields: [{fieldDBtype: "DatumField", labelFieldLinguists: "Goal", value: "", mask: "", encryptedValue: "",…},…] termsOfUse: {,…} *** timestamp: 1399303339523 # timestamp of corpus creation (I think) title: "Big Bear Corpus" titleAsUrl: "big_bear_corpus" url: FieldDB.Database.prototype.BASE_DB_URL+"/jrwdunham-firstcorpus" version: "v2.38.16" ### ############################################################################ # utility methods ############################################################################ getCorpusServerURL: -> url = @applicationSettings.get 'baseDBURL' "#{url}/#{@pouchname}" getFieldDBCorpusObject: (responseJSON) -> result = {} if responseJSON.rows? [..., tmp] = responseJSON.rows # Last element in array, a la CoffeeScript result = tmp.value getDefaultPayload: -> authUrl: @applicationSettings.get?('activeServer')?.get?('url') username: @applicationSettings.get?('username') password: @applicationSettings.get?('password') # TODO trigger authenticate:mustconfirmidentity serverCode: @applicationSettings.get?('activeServer')?.get?('serverCode') pouchname: @get 'pouchname' getFieldDBRole: (role) -> switch role when 'admin' then 'admin' when 'writer' then 'read_write' when 'reader' then 'read_only'
[ { "context": "inal script can be found here: https://github.com/shaundon/hubot-standup-alarm\n# This file is taken from a", "end": 349, "score": 0.999540388584137, "start": 341, "tag": "USERNAME", "value": "shaundon" }, { "context": "his file is taken from a fork: https://github.co...
scripts/standup.coffee
sagasu/doc
1
# Description: # Have Hubot remind you to do standups. # hh:mm must be in the same timezone as the server Hubot is on. Probably UTC. # # This is configured to work for Hipchat. You may need to change the 'create # standup' command to match the adapter you're using. # # The original script can be found here: https://github.com/shaundon/hubot-standup-alarm # This file is taken from a fork: https://github.com/sagasu/hubot-standup-alarm # # Configuration: # HUBOT_STANDUP_PREPEND # # Commands: # hubot standup help - See a help document explaining how to use. # hubot create standup hh:mm - Creates a standup at hh:mm every weekday for this room # hubot create standup hh:mm at location/url - Creates a standup at hh:mm (UTC) every weekday for this chat room with a reminder for a physical location or url # hubot create standup Monday@hh:mm - Creates a standup at hh:mm every Monday for this room # hubot create standup hh:mm UTC+2 - Creates a standup at hh:mm every weekday for this room (relative to UTC) # hubot create standup Monday@hh:mm UTC+2 - Creates a standup at hh:mm every Monday for this room (relative to UTC) # hubot list standups - See all standups for this room # hubot list all standups - See all standups in every room # hubot delete standup hh:mm - If you have a standup on weekdays at hh:mm, delete it. Can also supply a weekday and/or UTC offset # hubot delete all standups - Deletes all standups for this room. # # Dependencies: # underscore # cron ###jslint node: true### cronJob = require('cron').CronJob _ = require('underscore') module.exports = (robot) -> # Compares current time to the time of the standup to see if it should be fired. standupShouldFire = (standup) -> standupTime = standup.time standupDayOfWeek = getDayOfWeek(standup.dayOfWeek) now = new Date() standupDate = new Date() utcOffset = -standup.utc or (now.getTimezoneOffset() / 60) standupHours = parseInt(standupTime.split(":")[0], 10) standupMinutes = parseInt(standupTime.split(":")[1], 10) standupDate.setUTCMinutes(standupMinutes) standupDate.setUTCHours(standupHours + utcOffset) result = (standupDate.getUTCHours() == now.getUTCHours()) and (standupDate.getUTCMinutes() == now.getUTCMinutes()) and (standupDayOfWeek == -1 or (standupDayOfWeek == standupDate.getDay() == now.getUTCDay())) if result then true else false # Returns the number of a day of the week from a supplied string. Will only attempt to match the first 3 characters # Sat/Sun currently aren't supported by the cron but are included to ensure indexes are correct getDayOfWeek = (day) -> if (!day) return -1 ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].indexOf(day.toLowerCase().substring(0,3)) # Returns all standups. getStandups = -> robot.brain.get('standups') or [] # Returns just standups for a given room. getStandupsForRoom = (room) -> _.where getStandups(), room: room # Gets all standups, fires ones that should be. checkStandups = -> standups = getStandups() _.chain(standups).filter(standupShouldFire).pluck('room').each doStandup return # Fires the standup message. doStandup = (room) -> standups = getStandupsForRoom(room) if standups.length > 0 # Do some magic here to loop through the standups and find the one for right now theStandup = standups.filter(standupShouldFire) message = "#{PREPEND_MESSAGE} #{_.sample(STANDUP_MESSAGES)} #{theStandup[0].location}" else message = "#{PREPEND_MESSAGE} #{_.sample(STANDUP_MESSAGES)} #{standups[0].location}" robot.messageRoom room, message return # Finds the room for most adaptors findRoom = (msg) -> room = msg.envelope.room if _.isUndefined(room) room = msg.envelope.user.reply_to room # Confirm a time is in the valid 00:00 format timeIsValid = (time) -> validateTimePattern = /([01]?[0-9]|2[0-4]):[0-5]?[0-9]/ return validateTimePattern.test time # Stores a standup in the brain. saveStandup = (room, dayOfWeek, time, utcOffset, location, msg) -> if !timeIsValid time msg.send "Sorry, but I couldn't find a time to create the standup at." return standups = getStandups() newStandup = room: room dayOfWeek: dayOfWeek time: time utc: utcOffset location: location.trim() standups.push newStandup updateBrain standups displayDate = dayOfWeek or 'weekday' msg.send 'Ok, from now on I\'ll remind this room to do a standup every ' + displayDate + ' at ' + time + (if location then location else '') return # Updates the brain's standup knowledge. updateBrain = (standups) -> robot.brain.set 'standups', standups return # Remove all standups for a room clearAllStandupsForRoom = (room, msg) -> standups = getStandups() standupsToKeep = _.reject(standups, room: room) updateBrain standupsToKeep standupsCleared = standups.length - (standupsToKeep.length) msg.send 'Deleted ' + standupsCleared + ' standups for ' + room return # Remove specific standups for a room clearSpecificStandupForRoom = (room, time, msg) -> if !timeIsValid time msg.send "Sorry, but I couldn't spot a time in your command." return standups = getStandups() standupsToKeep = _.reject(standups, room: room time: time) updateBrain standupsToKeep standupsCleared = standups.length - (standupsToKeep.length) if standupsCleared == 0 msg.send 'Nice try. You don\'t even have a standup at ' + time else msg.send 'Deleted your ' + time + ' standup.' return # Responsd to the help command sendHelp = (msg) -> message = [] message.push 'I can remind you to do your standups!' message.push 'Use me to create a standup, and then I\'ll post in this room at the times you specify. Here\'s how:' message.push '' message.push robot.name + ' create standup hh:mm - I\'ll remind you to standup in this room at hh:mm every weekday.' message.push robot.name + ' create standup hh:mm UTC+2 - I\'ll remind you to standup in this room at hh:mm UTC+2 every weekday.' message.push robot.name + ' create standup hh:mm at location/url - Creates a standup at hh:mm (UTC) every weekday for this chat room with a reminder for a physical location or url' message.push robot.name + ' create standup Monday@hh:mm UTC+2 - I\'ll remind you to standup in this room at hh:mm UTC+2 every Monday.' message.push robot.name + ' list standups - See all standups for this room.' message.push robot.name + ' list all standups- Be nosey and see when other rooms have their standup.' message.push robot.name + ' delete standup hh:mm - If you have a standup at hh:mm, I\'ll delete it.' message.push robot.name + ' delete all standups - Deletes all standups for this room.' msg.send message.join('\n') return # List the standups within a specific room listStandupsForRoom = (room, msg) -> standups = getStandupsForRoom(findRoom(msg)) if standups.length == 0 msg.send 'Well this is awkward. You haven\'t got any standups set :-/' else standupsText = [ 'Here\'s your standups:' ].concat(_.map(standups, (standup) -> text = 'Time: ' + standup.time if standup.utc text += ' UTC' + standup.utc if standup.location text +=', Location: '+ standup.location text )) msg.send standupsText.join('\n') return listStandupsForAllRooms = (msg) -> standups = getStandups() if standups.length == 0 msg.send 'No, because there aren\'t any.' else standupsText = [ 'Here\'s the standups for every room:' ].concat(_.map(standups, (standup) -> text = 'Room: ' + standup.room + ', Time: ' + standup.time if standup.utc text += ' UTC' + standup.utc if standup.location text +=', Location: '+ standup.location text )) msg.send standupsText.join('\n') return 'use strict' # Constants. STANDUP_MESSAGES = [ # 'Standup time!' # 'Time for standup, y\'all.' # 'It\'s standup time once again!' # 'Get up, stand up (it\'s time for our standup)' # 'Standup time. Get up, humans' # 'Standup time! Now! Go go go!' # 'Time to learn what Sachin did yesterday. Standup!' # 'Is CBRIS going to rule the world? Let\'s learn during standup.' # ':richard: approves, it is time for standup.' # 'To standup or to sitdown that is the question' # 'Kostas is rapping this stadup so gather to hear' # 'Let\'s hear how many bugs :ahsan: found, just now on stadup' 'I feel so lonely here... no conversations' 'Am I the only person left on Slack' 'Dr Matt may you please migrate me to MS Teams' 'I am all alone here... please, please migrate me' 'No one loves me that\'s why they left me here all alone' 'Can someone invite me to MS Teams' 'Everyone left.... I am the last man standing on Slack' 'Lonely... I am sooo lonely... :notes: ' 'Dr Matt I don\'t want to die here all alone, I am begging you' 'And I thought that :kostas: was my friend, but he left me here and moved to MS Teams' 'Sachin you said that I am your friend, yet you are leaving and I am left alone on Slack :(' 'Even :richard: doesn\'t love me, he left me here and moved on to MS Teams' 'It is sad how quickly people forget about their friends... otherwise why would they leave me here all alone.' 'Dr Matt take me with you to the new place' ] PREPEND_MESSAGE = process.env.HUBOT_STANDUP_PREPEND or '' if PREPEND_MESSAGE.length > 0 and PREPEND_MESSAGE.slice(-1) != ' ' PREPEND_MESSAGE += ' ' # Check for standups that need to be fired, once a minute # Monday to Friday. new cronJob('1 * * * * 1-5', checkStandups, null, true) # Global regex should match all possible options robot.respond /(.*?)standups? ?(?:([A-z]*)\s?\@\s?)?((?:[01]?[0-9]|2[0-4]):[0-5]?[0-9])?(?: UTC([- +]\d\d?))?(.*)/i, (msg) -> action = msg.match[1].trim().toLowerCase() dayOfWeek = msg.match[2] time = msg.match[3] utcOffset = msg.match[4] location = msg.match[5] room = findRoom msg switch action when 'create' then saveStandup room, dayOfWeek, time, utcOffset, location, msg when 'list' then listStandupsForRoom room, msg when 'list all' then listStandupsForAllRooms msg when 'delete' then clearSpecificStandupForRoom room, time, msg when 'delete all' then clearAllStandupsForRoom room, msg else sendHelp msg return return
167593
# Description: # Have Hubot remind you to do standups. # hh:mm must be in the same timezone as the server Hubot is on. Probably UTC. # # This is configured to work for Hipchat. You may need to change the 'create # standup' command to match the adapter you're using. # # The original script can be found here: https://github.com/shaundon/hubot-standup-alarm # This file is taken from a fork: https://github.com/sagasu/hubot-standup-alarm # # Configuration: # HUBOT_STANDUP_PREPEND # # Commands: # hubot standup help - See a help document explaining how to use. # hubot create standup hh:mm - Creates a standup at hh:mm every weekday for this room # hubot create standup hh:mm at location/url - Creates a standup at hh:mm (UTC) every weekday for this chat room with a reminder for a physical location or url # hubot create standup Monday@hh:mm - Creates a standup at hh:mm every Monday for this room # hubot create standup hh:mm UTC+2 - Creates a standup at hh:mm every weekday for this room (relative to UTC) # hubot create standup Monday@hh:mm UTC+2 - Creates a standup at hh:mm every Monday for this room (relative to UTC) # hubot list standups - See all standups for this room # hubot list all standups - See all standups in every room # hubot delete standup hh:mm - If you have a standup on weekdays at hh:mm, delete it. Can also supply a weekday and/or UTC offset # hubot delete all standups - Deletes all standups for this room. # # Dependencies: # underscore # cron ###jslint node: true### cronJob = require('cron').CronJob _ = require('underscore') module.exports = (robot) -> # Compares current time to the time of the standup to see if it should be fired. standupShouldFire = (standup) -> standupTime = standup.time standupDayOfWeek = getDayOfWeek(standup.dayOfWeek) now = new Date() standupDate = new Date() utcOffset = -standup.utc or (now.getTimezoneOffset() / 60) standupHours = parseInt(standupTime.split(":")[0], 10) standupMinutes = parseInt(standupTime.split(":")[1], 10) standupDate.setUTCMinutes(standupMinutes) standupDate.setUTCHours(standupHours + utcOffset) result = (standupDate.getUTCHours() == now.getUTCHours()) and (standupDate.getUTCMinutes() == now.getUTCMinutes()) and (standupDayOfWeek == -1 or (standupDayOfWeek == standupDate.getDay() == now.getUTCDay())) if result then true else false # Returns the number of a day of the week from a supplied string. Will only attempt to match the first 3 characters # Sat/Sun currently aren't supported by the cron but are included to ensure indexes are correct getDayOfWeek = (day) -> if (!day) return -1 ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].indexOf(day.toLowerCase().substring(0,3)) # Returns all standups. getStandups = -> robot.brain.get('standups') or [] # Returns just standups for a given room. getStandupsForRoom = (room) -> _.where getStandups(), room: room # Gets all standups, fires ones that should be. checkStandups = -> standups = getStandups() _.chain(standups).filter(standupShouldFire).pluck('room').each doStandup return # Fires the standup message. doStandup = (room) -> standups = getStandupsForRoom(room) if standups.length > 0 # Do some magic here to loop through the standups and find the one for right now theStandup = standups.filter(standupShouldFire) message = "#{PREPEND_MESSAGE} #{_.sample(STANDUP_MESSAGES)} #{theStandup[0].location}" else message = "#{PREPEND_MESSAGE} #{_.sample(STANDUP_MESSAGES)} #{standups[0].location}" robot.messageRoom room, message return # Finds the room for most adaptors findRoom = (msg) -> room = msg.envelope.room if _.isUndefined(room) room = msg.envelope.user.reply_to room # Confirm a time is in the valid 00:00 format timeIsValid = (time) -> validateTimePattern = /([01]?[0-9]|2[0-4]):[0-5]?[0-9]/ return validateTimePattern.test time # Stores a standup in the brain. saveStandup = (room, dayOfWeek, time, utcOffset, location, msg) -> if !timeIsValid time msg.send "Sorry, but I couldn't find a time to create the standup at." return standups = getStandups() newStandup = room: room dayOfWeek: dayOfWeek time: time utc: utcOffset location: location.trim() standups.push newStandup updateBrain standups displayDate = dayOfWeek or 'weekday' msg.send 'Ok, from now on I\'ll remind this room to do a standup every ' + displayDate + ' at ' + time + (if location then location else '') return # Updates the brain's standup knowledge. updateBrain = (standups) -> robot.brain.set 'standups', standups return # Remove all standups for a room clearAllStandupsForRoom = (room, msg) -> standups = getStandups() standupsToKeep = _.reject(standups, room: room) updateBrain standupsToKeep standupsCleared = standups.length - (standupsToKeep.length) msg.send 'Deleted ' + standupsCleared + ' standups for ' + room return # Remove specific standups for a room clearSpecificStandupForRoom = (room, time, msg) -> if !timeIsValid time msg.send "Sorry, but I couldn't spot a time in your command." return standups = getStandups() standupsToKeep = _.reject(standups, room: room time: time) updateBrain standupsToKeep standupsCleared = standups.length - (standupsToKeep.length) if standupsCleared == 0 msg.send 'Nice try. You don\'t even have a standup at ' + time else msg.send 'Deleted your ' + time + ' standup.' return # Responsd to the help command sendHelp = (msg) -> message = [] message.push 'I can remind you to do your standups!' message.push 'Use me to create a standup, and then I\'ll post in this room at the times you specify. Here\'s how:' message.push '' message.push robot.name + ' create standup hh:mm - I\'ll remind you to standup in this room at hh:mm every weekday.' message.push robot.name + ' create standup hh:mm UTC+2 - I\'ll remind you to standup in this room at hh:mm UTC+2 every weekday.' message.push robot.name + ' create standup hh:mm at location/url - Creates a standup at hh:mm (UTC) every weekday for this chat room with a reminder for a physical location or url' message.push robot.name + ' create standup Monday@hh:mm UTC+2 - I\'ll remind you to standup in this room at hh:mm UTC+2 every Monday.' message.push robot.name + ' list standups - See all standups for this room.' message.push robot.name + ' list all standups- Be nosey and see when other rooms have their standup.' message.push robot.name + ' delete standup hh:mm - If you have a standup at hh:mm, I\'ll delete it.' message.push robot.name + ' delete all standups - Deletes all standups for this room.' msg.send message.join('\n') return # List the standups within a specific room listStandupsForRoom = (room, msg) -> standups = getStandupsForRoom(findRoom(msg)) if standups.length == 0 msg.send 'Well this is awkward. You haven\'t got any standups set :-/' else standupsText = [ 'Here\'s your standups:' ].concat(_.map(standups, (standup) -> text = 'Time: ' + standup.time if standup.utc text += ' UTC' + standup.utc if standup.location text +=', Location: '+ standup.location text )) msg.send standupsText.join('\n') return listStandupsForAllRooms = (msg) -> standups = getStandups() if standups.length == 0 msg.send 'No, because there aren\'t any.' else standupsText = [ 'Here\'s the standups for every room:' ].concat(_.map(standups, (standup) -> text = 'Room: ' + standup.room + ', Time: ' + standup.time if standup.utc text += ' UTC' + standup.utc if standup.location text +=', Location: '+ standup.location text )) msg.send standupsText.join('\n') return 'use strict' # Constants. STANDUP_MESSAGES = [ # 'Standup time!' # 'Time for standup, y\'all.' # 'It\'s standup time once again!' # 'Get up, stand up (it\'s time for our standup)' # 'Standup time. Get up, humans' # 'Standup time! Now! Go go go!' # 'Time to learn what <NAME> did yesterday. Standup!' # 'Is CBRIS going to rule the world? Let\'s learn during standup.' # ':richard: approves, it is time for standup.' # 'To standup or to sitdown that is the question' # 'Kostas is rapping this stadup so gather to hear' # 'Let\'s hear how many bugs :ahsan: found, just now on stadup' 'I feel so lonely here... no conversations' 'Am I the only person left on Slack' 'Dr <NAME> may you please migrate me to MS Teams' 'I am all alone here... please, please migrate me' 'No one loves me that\'s why they left me here all alone' 'Can someone invite me to MS Teams' 'Everyone left.... I am the last man standing on Slack' 'Lonely... I am sooo lonely... :notes: ' 'Dr <NAME> I don\'t want to die here all alone, I am begging you' 'And I thought that :kostas: was my friend, but he left me here and moved to MS Teams' 'Sachin you said that I am your friend, yet you are leaving and I am left alone on Slack :(' 'Even :richard: doesn\'t love me, he left me here and moved on to MS Teams' 'It is sad how quickly people forget about their friends... otherwise why would they leave me here all alone.' 'Dr <NAME> take me with you to the new place' ] PREPEND_MESSAGE = process.env.HUBOT_STANDUP_PREPEND or '' if PREPEND_MESSAGE.length > 0 and PREPEND_MESSAGE.slice(-1) != ' ' PREPEND_MESSAGE += ' ' # Check for standups that need to be fired, once a minute # Monday to Friday. new cronJob('1 * * * * 1-5', checkStandups, null, true) # Global regex should match all possible options robot.respond /(.*?)standups? ?(?:([A-z]*)\s?\@\s?)?((?:[01]?[0-9]|2[0-4]):[0-5]?[0-9])?(?: UTC([- +]\d\d?))?(.*)/i, (msg) -> action = msg.match[1].trim().toLowerCase() dayOfWeek = msg.match[2] time = msg.match[3] utcOffset = msg.match[4] location = msg.match[5] room = findRoom msg switch action when 'create' then saveStandup room, dayOfWeek, time, utcOffset, location, msg when 'list' then listStandupsForRoom room, msg when 'list all' then listStandupsForAllRooms msg when 'delete' then clearSpecificStandupForRoom room, time, msg when 'delete all' then clearAllStandupsForRoom room, msg else sendHelp msg return return
true
# Description: # Have Hubot remind you to do standups. # hh:mm must be in the same timezone as the server Hubot is on. Probably UTC. # # This is configured to work for Hipchat. You may need to change the 'create # standup' command to match the adapter you're using. # # The original script can be found here: https://github.com/shaundon/hubot-standup-alarm # This file is taken from a fork: https://github.com/sagasu/hubot-standup-alarm # # Configuration: # HUBOT_STANDUP_PREPEND # # Commands: # hubot standup help - See a help document explaining how to use. # hubot create standup hh:mm - Creates a standup at hh:mm every weekday for this room # hubot create standup hh:mm at location/url - Creates a standup at hh:mm (UTC) every weekday for this chat room with a reminder for a physical location or url # hubot create standup Monday@hh:mm - Creates a standup at hh:mm every Monday for this room # hubot create standup hh:mm UTC+2 - Creates a standup at hh:mm every weekday for this room (relative to UTC) # hubot create standup Monday@hh:mm UTC+2 - Creates a standup at hh:mm every Monday for this room (relative to UTC) # hubot list standups - See all standups for this room # hubot list all standups - See all standups in every room # hubot delete standup hh:mm - If you have a standup on weekdays at hh:mm, delete it. Can also supply a weekday and/or UTC offset # hubot delete all standups - Deletes all standups for this room. # # Dependencies: # underscore # cron ###jslint node: true### cronJob = require('cron').CronJob _ = require('underscore') module.exports = (robot) -> # Compares current time to the time of the standup to see if it should be fired. standupShouldFire = (standup) -> standupTime = standup.time standupDayOfWeek = getDayOfWeek(standup.dayOfWeek) now = new Date() standupDate = new Date() utcOffset = -standup.utc or (now.getTimezoneOffset() / 60) standupHours = parseInt(standupTime.split(":")[0], 10) standupMinutes = parseInt(standupTime.split(":")[1], 10) standupDate.setUTCMinutes(standupMinutes) standupDate.setUTCHours(standupHours + utcOffset) result = (standupDate.getUTCHours() == now.getUTCHours()) and (standupDate.getUTCMinutes() == now.getUTCMinutes()) and (standupDayOfWeek == -1 or (standupDayOfWeek == standupDate.getDay() == now.getUTCDay())) if result then true else false # Returns the number of a day of the week from a supplied string. Will only attempt to match the first 3 characters # Sat/Sun currently aren't supported by the cron but are included to ensure indexes are correct getDayOfWeek = (day) -> if (!day) return -1 ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].indexOf(day.toLowerCase().substring(0,3)) # Returns all standups. getStandups = -> robot.brain.get('standups') or [] # Returns just standups for a given room. getStandupsForRoom = (room) -> _.where getStandups(), room: room # Gets all standups, fires ones that should be. checkStandups = -> standups = getStandups() _.chain(standups).filter(standupShouldFire).pluck('room').each doStandup return # Fires the standup message. doStandup = (room) -> standups = getStandupsForRoom(room) if standups.length > 0 # Do some magic here to loop through the standups and find the one for right now theStandup = standups.filter(standupShouldFire) message = "#{PREPEND_MESSAGE} #{_.sample(STANDUP_MESSAGES)} #{theStandup[0].location}" else message = "#{PREPEND_MESSAGE} #{_.sample(STANDUP_MESSAGES)} #{standups[0].location}" robot.messageRoom room, message return # Finds the room for most adaptors findRoom = (msg) -> room = msg.envelope.room if _.isUndefined(room) room = msg.envelope.user.reply_to room # Confirm a time is in the valid 00:00 format timeIsValid = (time) -> validateTimePattern = /([01]?[0-9]|2[0-4]):[0-5]?[0-9]/ return validateTimePattern.test time # Stores a standup in the brain. saveStandup = (room, dayOfWeek, time, utcOffset, location, msg) -> if !timeIsValid time msg.send "Sorry, but I couldn't find a time to create the standup at." return standups = getStandups() newStandup = room: room dayOfWeek: dayOfWeek time: time utc: utcOffset location: location.trim() standups.push newStandup updateBrain standups displayDate = dayOfWeek or 'weekday' msg.send 'Ok, from now on I\'ll remind this room to do a standup every ' + displayDate + ' at ' + time + (if location then location else '') return # Updates the brain's standup knowledge. updateBrain = (standups) -> robot.brain.set 'standups', standups return # Remove all standups for a room clearAllStandupsForRoom = (room, msg) -> standups = getStandups() standupsToKeep = _.reject(standups, room: room) updateBrain standupsToKeep standupsCleared = standups.length - (standupsToKeep.length) msg.send 'Deleted ' + standupsCleared + ' standups for ' + room return # Remove specific standups for a room clearSpecificStandupForRoom = (room, time, msg) -> if !timeIsValid time msg.send "Sorry, but I couldn't spot a time in your command." return standups = getStandups() standupsToKeep = _.reject(standups, room: room time: time) updateBrain standupsToKeep standupsCleared = standups.length - (standupsToKeep.length) if standupsCleared == 0 msg.send 'Nice try. You don\'t even have a standup at ' + time else msg.send 'Deleted your ' + time + ' standup.' return # Responsd to the help command sendHelp = (msg) -> message = [] message.push 'I can remind you to do your standups!' message.push 'Use me to create a standup, and then I\'ll post in this room at the times you specify. Here\'s how:' message.push '' message.push robot.name + ' create standup hh:mm - I\'ll remind you to standup in this room at hh:mm every weekday.' message.push robot.name + ' create standup hh:mm UTC+2 - I\'ll remind you to standup in this room at hh:mm UTC+2 every weekday.' message.push robot.name + ' create standup hh:mm at location/url - Creates a standup at hh:mm (UTC) every weekday for this chat room with a reminder for a physical location or url' message.push robot.name + ' create standup Monday@hh:mm UTC+2 - I\'ll remind you to standup in this room at hh:mm UTC+2 every Monday.' message.push robot.name + ' list standups - See all standups for this room.' message.push robot.name + ' list all standups- Be nosey and see when other rooms have their standup.' message.push robot.name + ' delete standup hh:mm - If you have a standup at hh:mm, I\'ll delete it.' message.push robot.name + ' delete all standups - Deletes all standups for this room.' msg.send message.join('\n') return # List the standups within a specific room listStandupsForRoom = (room, msg) -> standups = getStandupsForRoom(findRoom(msg)) if standups.length == 0 msg.send 'Well this is awkward. You haven\'t got any standups set :-/' else standupsText = [ 'Here\'s your standups:' ].concat(_.map(standups, (standup) -> text = 'Time: ' + standup.time if standup.utc text += ' UTC' + standup.utc if standup.location text +=', Location: '+ standup.location text )) msg.send standupsText.join('\n') return listStandupsForAllRooms = (msg) -> standups = getStandups() if standups.length == 0 msg.send 'No, because there aren\'t any.' else standupsText = [ 'Here\'s the standups for every room:' ].concat(_.map(standups, (standup) -> text = 'Room: ' + standup.room + ', Time: ' + standup.time if standup.utc text += ' UTC' + standup.utc if standup.location text +=', Location: '+ standup.location text )) msg.send standupsText.join('\n') return 'use strict' # Constants. STANDUP_MESSAGES = [ # 'Standup time!' # 'Time for standup, y\'all.' # 'It\'s standup time once again!' # 'Get up, stand up (it\'s time for our standup)' # 'Standup time. Get up, humans' # 'Standup time! Now! Go go go!' # 'Time to learn what PI:NAME:<NAME>END_PI did yesterday. Standup!' # 'Is CBRIS going to rule the world? Let\'s learn during standup.' # ':richard: approves, it is time for standup.' # 'To standup or to sitdown that is the question' # 'Kostas is rapping this stadup so gather to hear' # 'Let\'s hear how many bugs :ahsan: found, just now on stadup' 'I feel so lonely here... no conversations' 'Am I the only person left on Slack' 'Dr PI:NAME:<NAME>END_PI may you please migrate me to MS Teams' 'I am all alone here... please, please migrate me' 'No one loves me that\'s why they left me here all alone' 'Can someone invite me to MS Teams' 'Everyone left.... I am the last man standing on Slack' 'Lonely... I am sooo lonely... :notes: ' 'Dr PI:NAME:<NAME>END_PI I don\'t want to die here all alone, I am begging you' 'And I thought that :kostas: was my friend, but he left me here and moved to MS Teams' 'Sachin you said that I am your friend, yet you are leaving and I am left alone on Slack :(' 'Even :richard: doesn\'t love me, he left me here and moved on to MS Teams' 'It is sad how quickly people forget about their friends... otherwise why would they leave me here all alone.' 'Dr PI:NAME:<NAME>END_PI take me with you to the new place' ] PREPEND_MESSAGE = process.env.HUBOT_STANDUP_PREPEND or '' if PREPEND_MESSAGE.length > 0 and PREPEND_MESSAGE.slice(-1) != ' ' PREPEND_MESSAGE += ' ' # Check for standups that need to be fired, once a minute # Monday to Friday. new cronJob('1 * * * * 1-5', checkStandups, null, true) # Global regex should match all possible options robot.respond /(.*?)standups? ?(?:([A-z]*)\s?\@\s?)?((?:[01]?[0-9]|2[0-4]):[0-5]?[0-9])?(?: UTC([- +]\d\d?))?(.*)/i, (msg) -> action = msg.match[1].trim().toLowerCase() dayOfWeek = msg.match[2] time = msg.match[3] utcOffset = msg.match[4] location = msg.match[5] room = findRoom msg switch action when 'create' then saveStandup room, dayOfWeek, time, utcOffset, location, msg when 'list' then listStandupsForRoom room, msg when 'list all' then listStandupsForAllRooms msg when 'delete' then clearSpecificStandupForRoom room, time, msg when 'delete all' then clearAllStandupsForRoom room, msg else sendHelp msg return return
[ { "context": "add \"Стратегические карты\",list:UL\n\ts81.push add \"Диаграмма Гантта\",list:UL\n\n\tpres.push s90=adf \"Ок, что дальше?\", k", "end": 6800, "score": 0.7272639274597168, "start": 6784, "tag": "NAME", "value": "Диаграмма Гантта" } ]
sample-slides.coffee
agershun/minday
0
##################################################### # MINDAY 0.008BI # sample-slidea.coffee # Примеры презентация и слайдов # Используется для презентации возможностей программы ##################################################### sample.slides = -> pres = adf "Minday - презентация программы", kind:PRESENTATION guide: add "Для просмотра презентации нажмите клавишу <b>F5</b>" description: add "Пример \"быстрой\" презентации, выполнненной в программе Minday" state:PRESENTATION pres.push s10=adf "Minday - первые шаги", kind:SLIDE list:OL guide: add "Для перехода на следующий слайд нажмите <b>пробел</b>." description: add "Это пример презентации" s10.push add "Здравствуйте!" s10.push add "Это - презентационный ролик, демонстрирующий возможности программы Minday. В нем отражены назначение программ и показаны ее основные возможности, а также способы управления программой", plain:yes s10.push s11=add "Клавиши управления презентацией" s11.push add "Для перемещения между слайдами используйте клавиши (они такие же, как и в Microsoft PowerPoint):",plain:yes s11.push add "Следущий слайд: <b>пробел, стрелка вправо (\u2192), стрелка вниз (\u2193), PgDn</b>",plain:yes,list:UL s11.push add "Предыдущий слайд: <b>Alt-Backspace (\u232B), стрелка влево (\u2190), стрелка вверх (\u2191), PgUp</b>",plain:yes,list:UL s11.push add "Начало презентации: <b>Home</b>",plain:yes,list:UL s11.push add "Конец презентации: <b>End</b>",plain:yes,list:UL s11.push add "Белый цвет экрана: <b>W</b>",plain:yes,list:UL s11.push add "Черный экрана: <b>B</b>",plain:yes,list:UL s11.push add "Начать презентацию с начала: <b>Alt-F5</b>",plain:yes,list:UL s11.push add "Начать презентацию с текущего слайда: <b>Shift-F5</b>",plain:yes,list:UL s11.push add "Завершить показ презентации: <b>Esc</b>",plain:yes,list:UL s11.push add "Перейти/выйти из режима редактирования презентации: <b>Ctrl-Alt-R</b>",plain:yes,list:UL pres.push s20=adf "Что такое Minday?", kind:SLIDE,list:OL s20.push add "Minday - это программа, предназначенная для:",plain:yes s20.push add "Проведения мозговых штурмов",plain:yes,list:UL s20.push add "Написания быстрых заметок и записи идей",plain:yes,list:UL s20.push add "Записи и структуризации идей и другие неструктурированных знаний",plain:yes,list:UL s20.push add "Использования различных методологий анализа (например, SWOT-анализ)",plain:yes,list:UL s20.push add "Подобора похожих решений бизнес-задач",plain:yes,list:UL s20.push add "Разработки сложных документов, например, предложение или стратегию",plain:yes,list:UL s20.push add "Разработки планов и презентаций для проведения обучения",plain:yes,list:UL s20.push add "Организации обмена и сохранения знаний в компании",plain:yes,list:UL pres.push s30=adf "Факты", kind:SLIDE,list:OL s30.push add "В среднем разработка стратегии развития требует применения около 10 различных моделей анализа: SWOT-анализ, PEST-анализ и т.п.",plain:yes,list:UL s30.push add "Разработанная стратегия для крупной компании включает более 100 диаграмм стандартных моделей",plain:yes,list:UL s30.push add "Средняя дипломная работа студента MBA включает минимум 5 моделей",plain:yes,list:UL s30.push add "Большинство современных управленческих технологий, применяемых во всех компаниях, предусматривают совместную работу и проведение \"мозговых штурмов\"",plain:yes,list:UL pres.push s40=adf "Аудитория", kind:SLIDE,list:OL s40.push s41=add "Это задачи, которые <br>выполняют ежедневно по всему<br> миру тысячи людей",plain:yes,list:SPAN s41.push add "Консультанты",plain:yes,list:UL s41.push add "Аналитики",plain:yes,list:UL s41.push add "Разработчики",plain:yes,list:UL s41.push add "Преподаватели",plain:yes,list:UL s41.push add "Студенты вузов<br>и бизнес-школ",plain:yes,list:UL s41.push add "Руководители<br>и предприниматели",plain:yes,list:UL s40.push s42=add "Обычно это люди:",plain:yes,list:SPAN s42.push s43=add "Пользователи" s43.push add "умные и умеющие думать",plain:yes,list:UL s43.push add "креативные и создающие знания",plain:yes,list:UL s43.push add "с высшим образованием, умеющие использовать методологии",plain:yes,list:UL s43.push add "активные, готовые создавать и делиться знаниями",plain:yes,list:UL s42.kindMindmap() pres.push s50=adf "Проблемы существующих инструментов", kind:SLIDE,list:OL s50col = add [(add "Программа"),(add "Сложности использования")] s50.push s51=add "",column:s50col s51.push add [(add "Книги"),(add "линейны, нет шаблонов, не всегда под рукой")] s51.push add [(add "Консалтинг, коучинг"),(add "дорого, требует человека")] s51.push add [(add "Википедия, электронные библиотеки и словари "),(add "неинтерактивны, нет возможности работать со своими данными")] s51.push add [(add "Brainstorming"),(add "мало моделей")] s51.push add [(add "Cooperation"),(add "мало методологий, нет примеров")] s51.push add [(add "Word, Excel, PowerPoint, Visio, Mindmaps"),(add " много свободы, нет специализированных библиотек, плохие wizards, неудобная структуризация")] s51.push add [(add "ARIS, Mega и т.п."),(add "дорогие, закрытые пакеты")] s51.kindMatrix() pres.push s60=adf "Предлагаемое решение", kind:SLIDE,list:OL s60.push s61=add "Программа для:",plain:yes,list:UL s61.push add "индивидуальной и совместной работы",plain:yes,list:UL s61.push add "свободной и ведомой методологиями работы",plain:yes,list:UL s61.push add "записи и структурирования данных и идей",plain:yes,list:UL s60.push add "Портал: библиотека моделей, методологий, примеров",plain:yes,list:UL s60.push add "Площадка для обмена моделями, разработанными пользователей",plain:yes,list:UL s60.push add "Удобный инструмент",plain:yes,list:UL s60.push add "Стандарт по созданию и обмену моделей, методологий в интернете",plain:yes,list:UL pres.push s70=adf "Отличительные характеристики программы", kind:SLIDE,list:OL s70.push add "Простой и быстрый интерфейс",list:UL s70.push add "Минимум нажатий клавиш и движений мышью",list:UL s70.push add "Неограниченная свобода мышления и помощь в структуризации",list:UL s70.push add "Красивые автоформатированные диаграммы",list:UL s70.push add "Быстрый подбор нужных моделей и методологий",list:UL s70.push add "Ненавязчивые и полезные инструкции",list:UL s70.push add "Одновременная работа нескольких пользователей с одним документом",list:UL s70.push add "Экспорт в популярные форматы данных (Word, PowerPoint)",list:UL pres.push s80=adf "Типы данных", kind:SLIDE,list:OL s80.push s81=add "Дотупные форматы" s81.push add "Идеи",list:UL s81.push add "Матрицы",list:UL s81.push add "Интеллектуальные карты",list:UL s81.push add "Пирамиды",list:UL s81.push add "Сегменты",list:UL s81.push add "Стратегические карты",list:UL s81.push add "Диаграмма Гантта",list:UL pres.push s90=adf "Ок, что дальше?", kind:SLIDE,list:OL s90.push add "Далее вы можете ознакомиться с основными возможностями программы и попробовать ее в действии. Для этого нажмите клавиши <b>Ctrl-Home</b> и вернитесь к началу модели." pres
47134
##################################################### # MINDAY 0.008BI # sample-slidea.coffee # Примеры презентация и слайдов # Используется для презентации возможностей программы ##################################################### sample.slides = -> pres = adf "Minday - презентация программы", kind:PRESENTATION guide: add "Для просмотра презентации нажмите клавишу <b>F5</b>" description: add "Пример \"быстрой\" презентации, выполнненной в программе Minday" state:PRESENTATION pres.push s10=adf "Minday - первые шаги", kind:SLIDE list:OL guide: add "Для перехода на следующий слайд нажмите <b>пробел</b>." description: add "Это пример презентации" s10.push add "Здравствуйте!" s10.push add "Это - презентационный ролик, демонстрирующий возможности программы Minday. В нем отражены назначение программ и показаны ее основные возможности, а также способы управления программой", plain:yes s10.push s11=add "Клавиши управления презентацией" s11.push add "Для перемещения между слайдами используйте клавиши (они такие же, как и в Microsoft PowerPoint):",plain:yes s11.push add "Следущий слайд: <b>пробел, стрелка вправо (\u2192), стрелка вниз (\u2193), PgDn</b>",plain:yes,list:UL s11.push add "Предыдущий слайд: <b>Alt-Backspace (\u232B), стрелка влево (\u2190), стрелка вверх (\u2191), PgUp</b>",plain:yes,list:UL s11.push add "Начало презентации: <b>Home</b>",plain:yes,list:UL s11.push add "Конец презентации: <b>End</b>",plain:yes,list:UL s11.push add "Белый цвет экрана: <b>W</b>",plain:yes,list:UL s11.push add "Черный экрана: <b>B</b>",plain:yes,list:UL s11.push add "Начать презентацию с начала: <b>Alt-F5</b>",plain:yes,list:UL s11.push add "Начать презентацию с текущего слайда: <b>Shift-F5</b>",plain:yes,list:UL s11.push add "Завершить показ презентации: <b>Esc</b>",plain:yes,list:UL s11.push add "Перейти/выйти из режима редактирования презентации: <b>Ctrl-Alt-R</b>",plain:yes,list:UL pres.push s20=adf "Что такое Minday?", kind:SLIDE,list:OL s20.push add "Minday - это программа, предназначенная для:",plain:yes s20.push add "Проведения мозговых штурмов",plain:yes,list:UL s20.push add "Написания быстрых заметок и записи идей",plain:yes,list:UL s20.push add "Записи и структуризации идей и другие неструктурированных знаний",plain:yes,list:UL s20.push add "Использования различных методологий анализа (например, SWOT-анализ)",plain:yes,list:UL s20.push add "Подобора похожих решений бизнес-задач",plain:yes,list:UL s20.push add "Разработки сложных документов, например, предложение или стратегию",plain:yes,list:UL s20.push add "Разработки планов и презентаций для проведения обучения",plain:yes,list:UL s20.push add "Организации обмена и сохранения знаний в компании",plain:yes,list:UL pres.push s30=adf "Факты", kind:SLIDE,list:OL s30.push add "В среднем разработка стратегии развития требует применения около 10 различных моделей анализа: SWOT-анализ, PEST-анализ и т.п.",plain:yes,list:UL s30.push add "Разработанная стратегия для крупной компании включает более 100 диаграмм стандартных моделей",plain:yes,list:UL s30.push add "Средняя дипломная работа студента MBA включает минимум 5 моделей",plain:yes,list:UL s30.push add "Большинство современных управленческих технологий, применяемых во всех компаниях, предусматривают совместную работу и проведение \"мозговых штурмов\"",plain:yes,list:UL pres.push s40=adf "Аудитория", kind:SLIDE,list:OL s40.push s41=add "Это задачи, которые <br>выполняют ежедневно по всему<br> миру тысячи людей",plain:yes,list:SPAN s41.push add "Консультанты",plain:yes,list:UL s41.push add "Аналитики",plain:yes,list:UL s41.push add "Разработчики",plain:yes,list:UL s41.push add "Преподаватели",plain:yes,list:UL s41.push add "Студенты вузов<br>и бизнес-школ",plain:yes,list:UL s41.push add "Руководители<br>и предприниматели",plain:yes,list:UL s40.push s42=add "Обычно это люди:",plain:yes,list:SPAN s42.push s43=add "Пользователи" s43.push add "умные и умеющие думать",plain:yes,list:UL s43.push add "креативные и создающие знания",plain:yes,list:UL s43.push add "с высшим образованием, умеющие использовать методологии",plain:yes,list:UL s43.push add "активные, готовые создавать и делиться знаниями",plain:yes,list:UL s42.kindMindmap() pres.push s50=adf "Проблемы существующих инструментов", kind:SLIDE,list:OL s50col = add [(add "Программа"),(add "Сложности использования")] s50.push s51=add "",column:s50col s51.push add [(add "Книги"),(add "линейны, нет шаблонов, не всегда под рукой")] s51.push add [(add "Консалтинг, коучинг"),(add "дорого, требует человека")] s51.push add [(add "Википедия, электронные библиотеки и словари "),(add "неинтерактивны, нет возможности работать со своими данными")] s51.push add [(add "Brainstorming"),(add "мало моделей")] s51.push add [(add "Cooperation"),(add "мало методологий, нет примеров")] s51.push add [(add "Word, Excel, PowerPoint, Visio, Mindmaps"),(add " много свободы, нет специализированных библиотек, плохие wizards, неудобная структуризация")] s51.push add [(add "ARIS, Mega и т.п."),(add "дорогие, закрытые пакеты")] s51.kindMatrix() pres.push s60=adf "Предлагаемое решение", kind:SLIDE,list:OL s60.push s61=add "Программа для:",plain:yes,list:UL s61.push add "индивидуальной и совместной работы",plain:yes,list:UL s61.push add "свободной и ведомой методологиями работы",plain:yes,list:UL s61.push add "записи и структурирования данных и идей",plain:yes,list:UL s60.push add "Портал: библиотека моделей, методологий, примеров",plain:yes,list:UL s60.push add "Площадка для обмена моделями, разработанными пользователей",plain:yes,list:UL s60.push add "Удобный инструмент",plain:yes,list:UL s60.push add "Стандарт по созданию и обмену моделей, методологий в интернете",plain:yes,list:UL pres.push s70=adf "Отличительные характеристики программы", kind:SLIDE,list:OL s70.push add "Простой и быстрый интерфейс",list:UL s70.push add "Минимум нажатий клавиш и движений мышью",list:UL s70.push add "Неограниченная свобода мышления и помощь в структуризации",list:UL s70.push add "Красивые автоформатированные диаграммы",list:UL s70.push add "Быстрый подбор нужных моделей и методологий",list:UL s70.push add "Ненавязчивые и полезные инструкции",list:UL s70.push add "Одновременная работа нескольких пользователей с одним документом",list:UL s70.push add "Экспорт в популярные форматы данных (Word, PowerPoint)",list:UL pres.push s80=adf "Типы данных", kind:SLIDE,list:OL s80.push s81=add "Дотупные форматы" s81.push add "Идеи",list:UL s81.push add "Матрицы",list:UL s81.push add "Интеллектуальные карты",list:UL s81.push add "Пирамиды",list:UL s81.push add "Сегменты",list:UL s81.push add "Стратегические карты",list:UL s81.push add "<NAME>",list:UL pres.push s90=adf "Ок, что дальше?", kind:SLIDE,list:OL s90.push add "Далее вы можете ознакомиться с основными возможностями программы и попробовать ее в действии. Для этого нажмите клавиши <b>Ctrl-Home</b> и вернитесь к началу модели." pres
true
##################################################### # MINDAY 0.008BI # sample-slidea.coffee # Примеры презентация и слайдов # Используется для презентации возможностей программы ##################################################### sample.slides = -> pres = adf "Minday - презентация программы", kind:PRESENTATION guide: add "Для просмотра презентации нажмите клавишу <b>F5</b>" description: add "Пример \"быстрой\" презентации, выполнненной в программе Minday" state:PRESENTATION pres.push s10=adf "Minday - первые шаги", kind:SLIDE list:OL guide: add "Для перехода на следующий слайд нажмите <b>пробел</b>." description: add "Это пример презентации" s10.push add "Здравствуйте!" s10.push add "Это - презентационный ролик, демонстрирующий возможности программы Minday. В нем отражены назначение программ и показаны ее основные возможности, а также способы управления программой", plain:yes s10.push s11=add "Клавиши управления презентацией" s11.push add "Для перемещения между слайдами используйте клавиши (они такие же, как и в Microsoft PowerPoint):",plain:yes s11.push add "Следущий слайд: <b>пробел, стрелка вправо (\u2192), стрелка вниз (\u2193), PgDn</b>",plain:yes,list:UL s11.push add "Предыдущий слайд: <b>Alt-Backspace (\u232B), стрелка влево (\u2190), стрелка вверх (\u2191), PgUp</b>",plain:yes,list:UL s11.push add "Начало презентации: <b>Home</b>",plain:yes,list:UL s11.push add "Конец презентации: <b>End</b>",plain:yes,list:UL s11.push add "Белый цвет экрана: <b>W</b>",plain:yes,list:UL s11.push add "Черный экрана: <b>B</b>",plain:yes,list:UL s11.push add "Начать презентацию с начала: <b>Alt-F5</b>",plain:yes,list:UL s11.push add "Начать презентацию с текущего слайда: <b>Shift-F5</b>",plain:yes,list:UL s11.push add "Завершить показ презентации: <b>Esc</b>",plain:yes,list:UL s11.push add "Перейти/выйти из режима редактирования презентации: <b>Ctrl-Alt-R</b>",plain:yes,list:UL pres.push s20=adf "Что такое Minday?", kind:SLIDE,list:OL s20.push add "Minday - это программа, предназначенная для:",plain:yes s20.push add "Проведения мозговых штурмов",plain:yes,list:UL s20.push add "Написания быстрых заметок и записи идей",plain:yes,list:UL s20.push add "Записи и структуризации идей и другие неструктурированных знаний",plain:yes,list:UL s20.push add "Использования различных методологий анализа (например, SWOT-анализ)",plain:yes,list:UL s20.push add "Подобора похожих решений бизнес-задач",plain:yes,list:UL s20.push add "Разработки сложных документов, например, предложение или стратегию",plain:yes,list:UL s20.push add "Разработки планов и презентаций для проведения обучения",plain:yes,list:UL s20.push add "Организации обмена и сохранения знаний в компании",plain:yes,list:UL pres.push s30=adf "Факты", kind:SLIDE,list:OL s30.push add "В среднем разработка стратегии развития требует применения около 10 различных моделей анализа: SWOT-анализ, PEST-анализ и т.п.",plain:yes,list:UL s30.push add "Разработанная стратегия для крупной компании включает более 100 диаграмм стандартных моделей",plain:yes,list:UL s30.push add "Средняя дипломная работа студента MBA включает минимум 5 моделей",plain:yes,list:UL s30.push add "Большинство современных управленческих технологий, применяемых во всех компаниях, предусматривают совместную работу и проведение \"мозговых штурмов\"",plain:yes,list:UL pres.push s40=adf "Аудитория", kind:SLIDE,list:OL s40.push s41=add "Это задачи, которые <br>выполняют ежедневно по всему<br> миру тысячи людей",plain:yes,list:SPAN s41.push add "Консультанты",plain:yes,list:UL s41.push add "Аналитики",plain:yes,list:UL s41.push add "Разработчики",plain:yes,list:UL s41.push add "Преподаватели",plain:yes,list:UL s41.push add "Студенты вузов<br>и бизнес-школ",plain:yes,list:UL s41.push add "Руководители<br>и предприниматели",plain:yes,list:UL s40.push s42=add "Обычно это люди:",plain:yes,list:SPAN s42.push s43=add "Пользователи" s43.push add "умные и умеющие думать",plain:yes,list:UL s43.push add "креативные и создающие знания",plain:yes,list:UL s43.push add "с высшим образованием, умеющие использовать методологии",plain:yes,list:UL s43.push add "активные, готовые создавать и делиться знаниями",plain:yes,list:UL s42.kindMindmap() pres.push s50=adf "Проблемы существующих инструментов", kind:SLIDE,list:OL s50col = add [(add "Программа"),(add "Сложности использования")] s50.push s51=add "",column:s50col s51.push add [(add "Книги"),(add "линейны, нет шаблонов, не всегда под рукой")] s51.push add [(add "Консалтинг, коучинг"),(add "дорого, требует человека")] s51.push add [(add "Википедия, электронные библиотеки и словари "),(add "неинтерактивны, нет возможности работать со своими данными")] s51.push add [(add "Brainstorming"),(add "мало моделей")] s51.push add [(add "Cooperation"),(add "мало методологий, нет примеров")] s51.push add [(add "Word, Excel, PowerPoint, Visio, Mindmaps"),(add " много свободы, нет специализированных библиотек, плохие wizards, неудобная структуризация")] s51.push add [(add "ARIS, Mega и т.п."),(add "дорогие, закрытые пакеты")] s51.kindMatrix() pres.push s60=adf "Предлагаемое решение", kind:SLIDE,list:OL s60.push s61=add "Программа для:",plain:yes,list:UL s61.push add "индивидуальной и совместной работы",plain:yes,list:UL s61.push add "свободной и ведомой методологиями работы",plain:yes,list:UL s61.push add "записи и структурирования данных и идей",plain:yes,list:UL s60.push add "Портал: библиотека моделей, методологий, примеров",plain:yes,list:UL s60.push add "Площадка для обмена моделями, разработанными пользователей",plain:yes,list:UL s60.push add "Удобный инструмент",plain:yes,list:UL s60.push add "Стандарт по созданию и обмену моделей, методологий в интернете",plain:yes,list:UL pres.push s70=adf "Отличительные характеристики программы", kind:SLIDE,list:OL s70.push add "Простой и быстрый интерфейс",list:UL s70.push add "Минимум нажатий клавиш и движений мышью",list:UL s70.push add "Неограниченная свобода мышления и помощь в структуризации",list:UL s70.push add "Красивые автоформатированные диаграммы",list:UL s70.push add "Быстрый подбор нужных моделей и методологий",list:UL s70.push add "Ненавязчивые и полезные инструкции",list:UL s70.push add "Одновременная работа нескольких пользователей с одним документом",list:UL s70.push add "Экспорт в популярные форматы данных (Word, PowerPoint)",list:UL pres.push s80=adf "Типы данных", kind:SLIDE,list:OL s80.push s81=add "Дотупные форматы" s81.push add "Идеи",list:UL s81.push add "Матрицы",list:UL s81.push add "Интеллектуальные карты",list:UL s81.push add "Пирамиды",list:UL s81.push add "Сегменты",list:UL s81.push add "Стратегические карты",list:UL s81.push add "PI:NAME:<NAME>END_PI",list:UL pres.push s90=adf "Ок, что дальше?", kind:SLIDE,list:OL s90.push add "Далее вы можете ознакомиться с основными возможностями программы и попробовать ее в действии. Для этого нажмите клавиши <b>Ctrl-Home</b> и вернитесь к началу модели." pres
[ { "context": " set with a key and value\", ->\n key = \"testkey1\"\n value = {foo: \"foo1\"}\n va", "end": 8766, "score": 0.8979418873786926, "start": 8758, "tag": "KEY", "value": "testkey1" }, { "context": "alue (PK default of 'id')\", ->\n ...
test/test.coffee
YuzuJS/storeit
0
"use strict" _ = require("underscore") StoreIt = require("..") # load StoreIt! StoreitError = StoreIt.StoreitError; describe "StoreIt.StoreitError", -> describe "(before calling new)", -> it "exists as a static property", -> StoreitError.should.not.equal(undefined) it "exposes the correct types", -> StoreitError.should.have.property("loadUninitialized") StoreitError.should.have.property("undefinedValue") StoreitError.should.have.property("invalidNamespace") StoreitError.should.have.property("nonexistentKey") StoreitError.should.have.property("invalidKey") describe "(after calling new)", -> err = new StoreitError(StoreitError.invalidNamespace) it "should be an instance of StoreitError", -> (err instanceof StoreitError).should.equal(true) it "should expose a `name` property", -> err.should.have.property("name") err.name.should.equal("StoreitError") it "should expose a `type` property", -> err.should.have.property("name") err.type.should.equal("invalidNamespace") it "should expose a `message` property", -> err.should.have.property("message") err.message.should.equal("namespace can not contain a hash character (#).") it "should expose a `stack` property", -> err.should.have.property("message") describe "StoreIt!", -> service = null testSet = (key, value, value2, setArgs, pk) -> beforeEach -> @value = value @value2 = value2 @publishAdded = sinon.stub() service.on("added", @publishAdded) @publishModified = sinon.stub() service.on("modified", @publishModified) if (pk && pk != "id") service.options = {primaryKey: pk} @result = service.set.apply(null, setArgs[0]) @result2 = service.set.apply(null, setArgs[1]) @result3 = service.set.apply(null, setArgs[2]) afterEach -> service.off("added", @publishAdded) service.off("modified", @publishModified) it "shold call storageProvider.setItem with the object", -> @storageProvider.setItem.should.be.calledWith("testns:" + key, @value) it "should publish a 'added' event", -> @publishAdded.should.have.been.called it "...with a CLONE of value", -> spyCall = @publishAdded.getCall(0) JSON.stringify(spyCall.args[0]).should.equal(JSON.stringify(@value)) spyCall.args[0].should.not.equal(@value) it "should publish a 'modified' event (if key exists)", -> @publishModified.should.have.been.called it "should publish a 'modified' event (if key exists) with the proper arguments", -> spyCall = @publishModified.getCall(0) publishedValue = @value2 if (pk) publishedValue = _.omit(publishedValue, pk) console.log(spyCall.args[0], publishedValue, pk) JSON.stringify(spyCall.args[0]).should.equal(JSON.stringify(publishedValue)) spyCall.args[1].should.equal(key) publishedValue = @value if (pk) publishedValue = _.omit(publishedValue, pk) JSON.stringify(spyCall.args[2]).should.equal(JSON.stringify(publishedValue)) spyCall.args[0].should.not.equal(@value) it "should NOT publish (if key exists and value is unchanged)", -> @publishModified.should.have.been.calledOnce it "should return a proper result object", -> @result.should.have.property("key") @result.key.should.equal(key) @result.should.have.property("value") @result.value.should.equal(@value) @result.should.have.property("action") @result.action.should.equal(StoreIt.Action.added) @result2.action.should.equal(StoreIt.Action.modified) @result3.action.should.equal(StoreIt.Action.none) it "should result in the correct value for keys", -> service.keys.length.should.equal(1) service.keys[0].should.equal(key) beforeEach -> @storageProvider = { name: "TestProvider" metadataSerializer: "TestMetadataSerializer" itemSerializer: "TestItemSerializer" } @getItem = sinon.stub() @getItem.withArgs("testns:testkey1").returns("test") @getItem.withArgs("testns:testkey2").returns(null) @getItem.withArgs("testns:testkey5").returns("test") @getItem.withArgs("loadns:testkey5").returns("test") @setItem = sinon.stub() @removeItem = sinon.stub() @setMetadata = sinon.stub() @getMetadata = sinon.stub() @getMetadata.withArgs("testns").returns(null) @getMetadata.withArgs("testns#index:primary").returns([]) @getMetadata.withArgs("loadns").returns(null) @getMetadata.withArgs("loadns#index:primary").returns(["testkey5"]) @storageProvider.getMetadata = @getMetadata @storageProvider.setMetadata = @setMetadata @storageProvider.getItem = @getItem @storageProvider.setItem = @setItem @storageProvider.removeItem = @removeItem describe "with no pre-loaded data", -> beforeEach -> service = new StoreIt("testns", @storageProvider) service.load() it "implements the correct interface", -> service.should.respondTo("has") service.should.respondTo("get") service.should.respondTo("fetch") service.should.respondTo("set") service.should.respondTo("metadata") service.should.respondTo("delete") service.should.respondTo("remove") service.should.respondTo("forEach") service.should.respondTo("clear") service.should.respondTo("load") service.should.respondTo("on") service.should.respondTo("off") service.should.respondTo("once") service.delete.should.equal(service.remove) it "should have an options property with correct defaults", -> service.options.publish.should.equal(true) it "should have a keys property with correct defaults", -> service.keys.should.be.an("array") service.keys.length.should.equal(0) it "should have a static enum Action with correct values", -> StoreIt.Action["none"].should.equal(0) StoreIt.Action["added"].should.equal(1) StoreIt.Action["modified"].should.equal(2) StoreIt.Action["removed"].should.equal(3) it "should have a static enum EventName with correct values", -> StoreIt.EventName["added"].should.equal("added") StoreIt.EventName["modified"].should.equal("modified") StoreIt.EventName["removed"].should.equal("removed") StoreIt.EventName["cleared"].should.equal("cleared") it "should throw a StoreitError when calling remove", -> (=> service.remove("key") ).should.throw(StoreitError) # ).should.throw(new StoreitError(StoreitError.nonexistentKey)) describe "calling set then modify the stored object", -> beforeEach -> @value = {foo: "foo"} service.set("key1", @value) @value.moo = "New property added" @retrievedValue = service.get("key1") it "should not modify the stored object", -> @retrievedValue.should.not.have.property("moo") describe "when calling has", -> it "on a valid key... should return true", -> service.set("testkey1", "test") @return = service.has("testkey1") @return.should.equal(true) it "on an invalid key... should return false", -> @return = service.has("testkey2") @return.should.equal(false) describe "when calling get", -> it "on a valid key... should return the correct value", -> @value = {foo: "foo"} service.set("testkey1", @value) @return = service.get("testkey1", "fun hater") @return.should.deep.equal(@value) it "on an invalid key... should return default value", -> @return = service.get("testkeyINVALID", "fun hater") @return.should.equal("fun hater") describe "when calling set with a key and value", -> key = "testkey1" value = {foo: "foo1"} value2 = {foo: "bar1"} setArgs = [[key, value], [key, value2], [key, value2]] testSet(key, value, value2, setArgs) describe "when calling set with only a value (PK default of 'id')", -> key = "testkey1" value = {id: key, foo: "foo2"} value2 = {id: key, foo: "bar2"} setArgs = [[value], [value2], [value2]] testSet(key, value, value2, setArgs, "id") describe "when calling set with only a value (PK of 'dw')", -> key = "testkey1" value = {dw: key, foo: "foo2"} value2 = {dw: key, foo: "bar2"} setArgs = [[value], [value2], [value2]] testSet(key, value, value2, setArgs, "dw") describe "when calling set on a key that exists (object)", -> beforeEach -> @key = "testkey1" @value = {foo: "foo"} @results = service.set("testkey1", @value) describe "the returned results.key", -> it "should return the key", -> @results.key.should.equal(@key) it "should return the value", -> @results.value.should.eql(@value) describe "when setting a partial object with a new property", -> it "should result in an extended object with both properties", -> service.set("testkey1", {bar: "bar"}) service.get("testkey1").should.eql({foo: "foo", bar: "bar"}) describe "when setting a partial object with the same property, different value", -> it "should result in the property changed", -> service.set("testkey1", {foo: "bar"}) service.get("testkey1").should.eql({foo: "bar"}) describe "when setting the new value to a string", -> it "should result in the property changed", -> service.set("testkey1", "foo") service.get("testkey1").should.equal("foo") describe "when setting the new value to a number", -> it "should result in the property changed", -> service.set("testkey1", 123) service.get("testkey1").should.equal(123) describe "when setting the new value to an array", -> it "should result in the property changed", -> service.set("testkey1", [1, 2, 3]) service.get("testkey1").should.eql([1, 2, 3]) describe "when calling set on a key that exists (string)", -> beforeEach -> service.set("testkey1", "xxx") describe "when setting an object", -> it "should result in the setting the new object", -> @value = {foo: "foo"} service.set("testkey1", @value) service.get("testkey1").should.eql(@value) describe "when setting the new value to a string", -> it "should result in the property changed", -> @value = "foo" service.set("testkey1", @value) service.get("testkey1").should.equal(@value) describe "when setting the new value to a number", -> it "should result in the property changed", -> @value = 123 service.set("testkey1", @value) service.get("testkey1").should.equal(@value) describe "when calling set on a key that exists (array)", -> beforeEach -> service.set("testkey1", [1,2,3]) describe "when setting an array", -> it "should result in the setting the new object", -> @value = [4, 5, 6] service.set("testkey1", @value) service.get("testkey1").should.eql(@value) describe "when setting an object", -> it "should result in the setting the new object", -> @value = {foo: "foo"} service.set("testkey1", @value) service.get("testkey1").should.eql(@value) describe "when setting the new value to a string", -> it "should result in the property changed", -> @value = "foo" service.set("testkey1", @value) service.get("testkey1").should.equal(@value) describe "when setting the new value to a number", -> it "should result in the property changed", -> @value = 123 service.set("testkey1", @value) service.get("testkey1").should.equal(@value) describe "modifying the object that was stored without setting it to the store again", -> beforeEach -> @value = {"location":{"path":"3!@0.01951123900822323:0.028598665395614873"},"id":"62","text":"J"} @value2 = {"location":{"path":"modified@path"}} service.set("testbug", @value) # Add service.set("testbug", @value2) # Modify it "should not affect the value in the store", -> valueInStore = service.get("testbug") valueInStore.location.path.should.equal("modified@path") delete @value2.location.path valueInStore = service.get("testbug") valueInStore.location.should.have.property("path") describe "when calling set with a partial object", -> describe "which contains a new property", -> beforeEach -> service.set("testkey1", {foo: "foo"}) @result = service.set("testkey1", {bar: "bar"}) it "should return the entire object in results.value", -> @result.value.should.eql({foo: "foo", bar: "bar"}) it "should write the serializer name to storageProvider", -> spyCall = @storageProvider.setMetadata.getCall(0) spyCall.args[0].should.equal("testns") JSON.stringify(spyCall.args[1]).should.equal(JSON.stringify({itemSerializer:null})) it "should write the index to storageProvider", -> # @storageProvider.setItem.should.be.calledWith("testns:testkey1", JSON.stringify({foo: "foo", bar: "bar"})) spyCall = @storageProvider.setMetadata.getCall(1) spyCall.args[0].should.equal("testns#index:primary") JSON.stringify(spyCall.args[1]).should.equal(JSON.stringify(["testkey1"])) it "should write the first object to storageProvider", -> spyCall = @storageProvider.setItem.getCall(0) spyCall.args[0].should.equal("testns:testkey1") JSON.stringify(spyCall.args[1]).should.equal(JSON.stringify({foo: "foo"})) it "should write the entire extended object to storageProvider", -> spyCall = @storageProvider.setItem.getCall(1) spyCall.args[0].should.equal("testns:testkey1") JSON.stringify(spyCall.args[1]).should.equal(JSON.stringify({foo: "foo", bar: "bar"})) describe "which resets an existing property's value from an object to a primitive", -> beforeEach -> service.set("testkey1", {foo: {name: "foo"}}) @result = service.set("testkey1", {foo: "foo"}) it "should return the entire object in results.value", -> @result.value.should.eql({foo: "foo"}) describe "when accessing metadata", -> describe "on an INVALID key", -> it "should thow an exception", -> (-> service.metadata("testkey1002")).should.throw(Error) describe "on a valid key", -> beforeEach -> service.set("testkey1", "foo") @metadata = service.metadata("testkey1") it "should return a proper object", -> @metadata.should.have.property("get") @metadata.should.have.property("set") describe "and when calling set with undefined", -> it "should thow an exception", -> (-> @metadata.set(undefined)).should.throw(Error) describe "and when calling set with a valid argument", -> beforeEach -> @value = 123 @metadata.set(@value) it "should call storageProvider.setItem with JSON.stringified object", -> @storageProvider.setItem.should.be.calledWith("testns#metadata:testkey1", @value) describe "and a call to get", -> it "should return the same value", -> @metadata.get().should.equal(@value) describe "using the shorthand `set` syntax", -> beforeEach -> @key = "testkey1" @value = "bar" @results = service.set(@key, "foo", @value) describe "the returned results.metadata", -> it "should return the same value", -> @results.metadata.should.equal(@value) describe "and a call to get", -> it "should return the same value", -> service.metadata(@key).get().should.equal(@value) describe "when calling delete", -> beforeEach -> @value = {foo: "foo"} @publishRemoved = sinon.stub() service.on("removed", @publishRemoved) service.set("testkey1", @value) @result = service.delete("testkey1") afterEach -> service.off("removed", @publishRemoved) it "should call storageProvider.removeItem with JSON.stringified object", -> @storageProvider.removeItem.should.be.calledWith("testns:testkey1") @storageProvider.removeItem.should.be.calledWith("testns#metadata:testkey1") it "should thow an exception when called with an invalid key", -> (-> service.delete("testkey1002")).should.throw(Error) it "should publish an 'removed' event passing the correct value", -> spyCall = @publishRemoved.getCall(0) JSON.stringify(spyCall.args[0]).should.equal(JSON.stringify(@value)) it "should return a proper result object", -> @result.should.have.property("key") @result.key.should.equal("testkey1") @result.should.have.property("value") @result.value.should.deep.equal(@value) @result.should.have.property("action") @result.action.should.equal(StoreIt.Action.removed) describe "when calling forEach (with nothing set)", -> beforeEach -> @forEach = sinon.stub() service.forEach @forEach it "should do nothing when there are no items", -> @forEach.should.not.be.called describe "when calling forEach (with three items set)", -> beforeEach -> service.set("testkey1", 1) service.set("testkey2", 2) service.set("testkey3", 3) @forEach = sinon.stub() service.forEach @forEach it "should call the callback with arguments (value, key, obj)", -> spyCall = @forEach.getCall(0) spyCall.args[0].should.equal(1) spyCall.args[1].should.equal("testkey1") spyCall.args[2].should.equal(service) it "should call the callback once for each item", -> @forEach.should.have.been.calledThrice describe "when calling clear", -> beforeEach -> @publishReady = sinon.stub() service.on("ready", @publishReady) service.set("testkey1", 1) service.set("testkey2", 2) service.set("testkey3", 3) service.clear() afterEach -> service.off("ready", @publishReady) it "should call storageProvider.getItem for the index", -> spyCall = @getMetadata.getCall(0) spyCall.args[0].should.equal("testns#index:primary") it "should call storageProvider.removeItem for each item/metadata plus the index", -> spyCall = @removeItem.getCall(0) spyCall.args[0].should.equal("testns#index:primary") spyCall = @removeItem.getCall(1) spyCall.args[0].should.equal("testns") # spyCall = @removeItem.getCall(2) # spyCall.args[0].should.equal("testns#metadata:testkey5") # spyCall = @removeItem.getCall(3) # spyCall.args[0].should.equal("testns:testkey5") it "should result in an empty array for keys", -> @keys = service.keys @keys.length.should.equal(0) it "should NOT publish a 'ready' event", -> @publishReady.should.not.have.been.called describe "with one item of pre-loaded data", -> beforeEach -> @publishAdded = sinon.stub() service = new StoreIt("loadns", @storageProvider) service.on("added", @publishAdded) afterEach -> service.off("added", @publishAdded) describe "when calling load", -> beforeEach -> service.load() it "should have a keys property with correct defaults", -> service.keys.should.be.an("array") service.keys.length.should.equal(1) it "it should call storageProvider.getItem for the index and each item", -> spyCall = @getMetadata.getCall(0) spyCall.args[0].should.equal("loadns#index:primary") spyCall = @getItem.getCall(0) spyCall.args[0].should.equal("loadns:testkey5") it "items loaded should be available with has", -> service.has("testkey5").should.equal(true) it "items loaded should be available with get", -> service.get("testkey5").should.equal("test") it "should publish an 'added' event for each item", -> @publishAdded.should.be.calledWith("test", "testkey5") it "should NOT throw a StoreitError when calling remove", -> (=> service.remove("testkey5") ).should.not.throw(StoreitError) describe "when calling set with options.publish = false", -> beforeEach -> service.options = {publish:false} service.load() it "should be publish nothing", -> @publishAdded.should.not.be.called describe "without calling `load`", -> beforeEach -> service = new StoreIt("testns", @storageProvider) it "should have `isInitialized` set to false", -> service.isInitialized.should.equal(false) it "should throw a StoreitError when calling has", -> (=> service.has("key") ).should.throw(StoreitError) it "should throw a StoreitError when calling get", -> (=> service.get("key") ).should.throw(StoreitError) it "should throw a StoreitError when calling set", -> (=> service.set("key", "value") ).should.throw(StoreitError) it "should throw a StoreitError when calling remove", -> (=> service.remove("key") ).should.throw(StoreitError) describe "then once we call load()", -> beforeEach -> @publishReady = sinon.stub() service.on("ready", @publishReady) service.load() afterEach -> service.off("ready", @publishReady) it "should have `isInitialized` set to true", -> service.isInitialized.should.equal(true) it "should publish a 'ready' event", -> @publishReady.should.have.been.called describe "then once we call clear()", -> beforeEach -> @publishReady = sinon.stub() service.on("ready", @publishReady) service.clear() afterEach -> service.off("ready", @publishReady) it "should have `isInitialized` set to true", -> service.isInitialized.should.equal(true) it "should publish a 'ready' event", -> @publishReady.should.have.been.called
203779
"use strict" _ = require("underscore") StoreIt = require("..") # load StoreIt! StoreitError = StoreIt.StoreitError; describe "StoreIt.StoreitError", -> describe "(before calling new)", -> it "exists as a static property", -> StoreitError.should.not.equal(undefined) it "exposes the correct types", -> StoreitError.should.have.property("loadUninitialized") StoreitError.should.have.property("undefinedValue") StoreitError.should.have.property("invalidNamespace") StoreitError.should.have.property("nonexistentKey") StoreitError.should.have.property("invalidKey") describe "(after calling new)", -> err = new StoreitError(StoreitError.invalidNamespace) it "should be an instance of StoreitError", -> (err instanceof StoreitError).should.equal(true) it "should expose a `name` property", -> err.should.have.property("name") err.name.should.equal("StoreitError") it "should expose a `type` property", -> err.should.have.property("name") err.type.should.equal("invalidNamespace") it "should expose a `message` property", -> err.should.have.property("message") err.message.should.equal("namespace can not contain a hash character (#).") it "should expose a `stack` property", -> err.should.have.property("message") describe "StoreIt!", -> service = null testSet = (key, value, value2, setArgs, pk) -> beforeEach -> @value = value @value2 = value2 @publishAdded = sinon.stub() service.on("added", @publishAdded) @publishModified = sinon.stub() service.on("modified", @publishModified) if (pk && pk != "id") service.options = {primaryKey: pk} @result = service.set.apply(null, setArgs[0]) @result2 = service.set.apply(null, setArgs[1]) @result3 = service.set.apply(null, setArgs[2]) afterEach -> service.off("added", @publishAdded) service.off("modified", @publishModified) it "shold call storageProvider.setItem with the object", -> @storageProvider.setItem.should.be.calledWith("testns:" + key, @value) it "should publish a 'added' event", -> @publishAdded.should.have.been.called it "...with a CLONE of value", -> spyCall = @publishAdded.getCall(0) JSON.stringify(spyCall.args[0]).should.equal(JSON.stringify(@value)) spyCall.args[0].should.not.equal(@value) it "should publish a 'modified' event (if key exists)", -> @publishModified.should.have.been.called it "should publish a 'modified' event (if key exists) with the proper arguments", -> spyCall = @publishModified.getCall(0) publishedValue = @value2 if (pk) publishedValue = _.omit(publishedValue, pk) console.log(spyCall.args[0], publishedValue, pk) JSON.stringify(spyCall.args[0]).should.equal(JSON.stringify(publishedValue)) spyCall.args[1].should.equal(key) publishedValue = @value if (pk) publishedValue = _.omit(publishedValue, pk) JSON.stringify(spyCall.args[2]).should.equal(JSON.stringify(publishedValue)) spyCall.args[0].should.not.equal(@value) it "should NOT publish (if key exists and value is unchanged)", -> @publishModified.should.have.been.calledOnce it "should return a proper result object", -> @result.should.have.property("key") @result.key.should.equal(key) @result.should.have.property("value") @result.value.should.equal(@value) @result.should.have.property("action") @result.action.should.equal(StoreIt.Action.added) @result2.action.should.equal(StoreIt.Action.modified) @result3.action.should.equal(StoreIt.Action.none) it "should result in the correct value for keys", -> service.keys.length.should.equal(1) service.keys[0].should.equal(key) beforeEach -> @storageProvider = { name: "TestProvider" metadataSerializer: "TestMetadataSerializer" itemSerializer: "TestItemSerializer" } @getItem = sinon.stub() @getItem.withArgs("testns:testkey1").returns("test") @getItem.withArgs("testns:testkey2").returns(null) @getItem.withArgs("testns:testkey5").returns("test") @getItem.withArgs("loadns:testkey5").returns("test") @setItem = sinon.stub() @removeItem = sinon.stub() @setMetadata = sinon.stub() @getMetadata = sinon.stub() @getMetadata.withArgs("testns").returns(null) @getMetadata.withArgs("testns#index:primary").returns([]) @getMetadata.withArgs("loadns").returns(null) @getMetadata.withArgs("loadns#index:primary").returns(["testkey5"]) @storageProvider.getMetadata = @getMetadata @storageProvider.setMetadata = @setMetadata @storageProvider.getItem = @getItem @storageProvider.setItem = @setItem @storageProvider.removeItem = @removeItem describe "with no pre-loaded data", -> beforeEach -> service = new StoreIt("testns", @storageProvider) service.load() it "implements the correct interface", -> service.should.respondTo("has") service.should.respondTo("get") service.should.respondTo("fetch") service.should.respondTo("set") service.should.respondTo("metadata") service.should.respondTo("delete") service.should.respondTo("remove") service.should.respondTo("forEach") service.should.respondTo("clear") service.should.respondTo("load") service.should.respondTo("on") service.should.respondTo("off") service.should.respondTo("once") service.delete.should.equal(service.remove) it "should have an options property with correct defaults", -> service.options.publish.should.equal(true) it "should have a keys property with correct defaults", -> service.keys.should.be.an("array") service.keys.length.should.equal(0) it "should have a static enum Action with correct values", -> StoreIt.Action["none"].should.equal(0) StoreIt.Action["added"].should.equal(1) StoreIt.Action["modified"].should.equal(2) StoreIt.Action["removed"].should.equal(3) it "should have a static enum EventName with correct values", -> StoreIt.EventName["added"].should.equal("added") StoreIt.EventName["modified"].should.equal("modified") StoreIt.EventName["removed"].should.equal("removed") StoreIt.EventName["cleared"].should.equal("cleared") it "should throw a StoreitError when calling remove", -> (=> service.remove("key") ).should.throw(StoreitError) # ).should.throw(new StoreitError(StoreitError.nonexistentKey)) describe "calling set then modify the stored object", -> beforeEach -> @value = {foo: "foo"} service.set("key1", @value) @value.moo = "New property added" @retrievedValue = service.get("key1") it "should not modify the stored object", -> @retrievedValue.should.not.have.property("moo") describe "when calling has", -> it "on a valid key... should return true", -> service.set("testkey1", "test") @return = service.has("testkey1") @return.should.equal(true) it "on an invalid key... should return false", -> @return = service.has("testkey2") @return.should.equal(false) describe "when calling get", -> it "on a valid key... should return the correct value", -> @value = {foo: "foo"} service.set("testkey1", @value) @return = service.get("testkey1", "fun hater") @return.should.deep.equal(@value) it "on an invalid key... should return default value", -> @return = service.get("testkeyINVALID", "fun hater") @return.should.equal("fun hater") describe "when calling set with a key and value", -> key = "<KEY>" value = {foo: "foo1"} value2 = {foo: "bar1"} setArgs = [[key, value], [key, value2], [key, value2]] testSet(key, value, value2, setArgs) describe "when calling set with only a value (PK default of 'id')", -> key = "<KEY>" value = {id: key, foo: "foo2"} value2 = {id: key, foo: "bar2"} setArgs = [[value], [value2], [value2]] testSet(key, value, value2, setArgs, "id") describe "when calling set with only a value (PK of 'dw')", -> key = "<KEY>" value = {dw: key, foo: "foo2"} value2 = {dw: key, foo: "bar2"} setArgs = [[value], [value2], [value2]] testSet(key, value, value2, setArgs, "dw") describe "when calling set on a key that exists (object)", -> beforeEach -> @key = "<KEY>1" @value = {foo: "foo"} @results = service.set("testkey1", @value) describe "the returned results.key", -> it "should return the key", -> @results.key.should.equal(@key) it "should return the value", -> @results.value.should.eql(@value) describe "when setting a partial object with a new property", -> it "should result in an extended object with both properties", -> service.set("testkey1", {bar: "bar"}) service.get("testkey1").should.eql({foo: "foo", bar: "bar"}) describe "when setting a partial object with the same property, different value", -> it "should result in the property changed", -> service.set("testkey1", {foo: "bar"}) service.get("testkey1").should.eql({foo: "bar"}) describe "when setting the new value to a string", -> it "should result in the property changed", -> service.set("testkey1", "foo") service.get("testkey1").should.equal("foo") describe "when setting the new value to a number", -> it "should result in the property changed", -> service.set("testkey1", 123) service.get("testkey1").should.equal(123) describe "when setting the new value to an array", -> it "should result in the property changed", -> service.set("testkey1", [1, 2, 3]) service.get("testkey1").should.eql([1, 2, 3]) describe "when calling set on a key that exists (string)", -> beforeEach -> service.set("testkey1", "xxx") describe "when setting an object", -> it "should result in the setting the new object", -> @value = {foo: "foo"} service.set("testkey1", @value) service.get("testkey1").should.eql(@value) describe "when setting the new value to a string", -> it "should result in the property changed", -> @value = "foo" service.set("testkey1", @value) service.get("testkey1").should.equal(@value) describe "when setting the new value to a number", -> it "should result in the property changed", -> @value = 123 service.set("testkey1", @value) service.get("testkey1").should.equal(@value) describe "when calling set on a key that exists (array)", -> beforeEach -> service.set("testkey1", [1,2,3]) describe "when setting an array", -> it "should result in the setting the new object", -> @value = [4, 5, 6] service.set("testkey1", @value) service.get("testkey1").should.eql(@value) describe "when setting an object", -> it "should result in the setting the new object", -> @value = {foo: "foo"} service.set("testkey1", @value) service.get("testkey1").should.eql(@value) describe "when setting the new value to a string", -> it "should result in the property changed", -> @value = "foo" service.set("testkey1", @value) service.get("testkey1").should.equal(@value) describe "when setting the new value to a number", -> it "should result in the property changed", -> @value = 123 service.set("testkey1", @value) service.get("testkey1").should.equal(@value) describe "modifying the object that was stored without setting it to the store again", -> beforeEach -> @value = {"location":{"path":"3!@0.01951123900822323:0.028598665395614873"},"id":"62","text":"J"} @value2 = {"location":{"path":"modified@path"}} service.set("testbug", @value) # Add service.set("testbug", @value2) # Modify it "should not affect the value in the store", -> valueInStore = service.get("testbug") valueInStore.location.path.should.equal("modified@path") delete @value2.location.path valueInStore = service.get("testbug") valueInStore.location.should.have.property("path") describe "when calling set with a partial object", -> describe "which contains a new property", -> beforeEach -> service.set("testkey1", {foo: "foo"}) @result = service.set("testkey1", {bar: "bar"}) it "should return the entire object in results.value", -> @result.value.should.eql({foo: "foo", bar: "bar"}) it "should write the serializer name to storageProvider", -> spyCall = @storageProvider.setMetadata.getCall(0) spyCall.args[0].should.equal("testns") JSON.stringify(spyCall.args[1]).should.equal(JSON.stringify({itemSerializer:null})) it "should write the index to storageProvider", -> # @storageProvider.setItem.should.be.calledWith("testns:testkey1", JSON.stringify({foo: "foo", bar: "bar"})) spyCall = @storageProvider.setMetadata.getCall(1) spyCall.args[0].should.equal("testns#index:primary") JSON.stringify(spyCall.args[1]).should.equal(JSON.stringify(["testkey1"])) it "should write the first object to storageProvider", -> spyCall = @storageProvider.setItem.getCall(0) spyCall.args[0].should.equal("testns:testkey1") JSON.stringify(spyCall.args[1]).should.equal(JSON.stringify({foo: "foo"})) it "should write the entire extended object to storageProvider", -> spyCall = @storageProvider.setItem.getCall(1) spyCall.args[0].should.equal("testns:testkey1") JSON.stringify(spyCall.args[1]).should.equal(JSON.stringify({foo: "foo", bar: "bar"})) describe "which resets an existing property's value from an object to a primitive", -> beforeEach -> service.set("testkey1", {foo: {name: "foo"}}) @result = service.set("testkey1", {foo: "foo"}) it "should return the entire object in results.value", -> @result.value.should.eql({foo: "foo"}) describe "when accessing metadata", -> describe "on an INVALID key", -> it "should thow an exception", -> (-> service.metadata("testkey1002")).should.throw(Error) describe "on a valid key", -> beforeEach -> service.set("testkey1", "foo") @metadata = service.metadata("testkey1") it "should return a proper object", -> @metadata.should.have.property("get") @metadata.should.have.property("set") describe "and when calling set with undefined", -> it "should thow an exception", -> (-> @metadata.set(undefined)).should.throw(Error) describe "and when calling set with a valid argument", -> beforeEach -> @value = 123 @metadata.set(@value) it "should call storageProvider.setItem with JSON.stringified object", -> @storageProvider.setItem.should.be.calledWith("testns#metadata:testkey1", @value) describe "and a call to get", -> it "should return the same value", -> @metadata.get().should.equal(@value) describe "using the shorthand `set` syntax", -> beforeEach -> @key = "<KEY>" @value = "bar" @results = service.set(@key, "foo", @value) describe "the returned results.metadata", -> it "should return the same value", -> @results.metadata.should.equal(@value) describe "and a call to get", -> it "should return the same value", -> service.metadata(@key).get().should.equal(@value) describe "when calling delete", -> beforeEach -> @value = {foo: "foo"} @publishRemoved = sinon.stub() service.on("removed", @publishRemoved) service.set("testkey1", @value) @result = service.delete("testkey1") afterEach -> service.off("removed", @publishRemoved) it "should call storageProvider.removeItem with JSON.stringified object", -> @storageProvider.removeItem.should.be.calledWith("testns:testkey1") @storageProvider.removeItem.should.be.calledWith("testns#metadata:testkey1") it "should thow an exception when called with an invalid key", -> (-> service.delete("testkey1002")).should.throw(Error) it "should publish an 'removed' event passing the correct value", -> spyCall = @publishRemoved.getCall(0) JSON.stringify(spyCall.args[0]).should.equal(JSON.stringify(@value)) it "should return a proper result object", -> @result.should.have.property("key") @result.key.should.equal("<KEY>") @result.should.have.property("value") @result.value.should.deep.equal(@value) @result.should.have.property("action") @result.action.should.equal(StoreIt.Action.removed) describe "when calling forEach (with nothing set)", -> beforeEach -> @forEach = sinon.stub() service.forEach @forEach it "should do nothing when there are no items", -> @forEach.should.not.be.called describe "when calling forEach (with three items set)", -> beforeEach -> service.set("testkey1", 1) service.set("testkey2", 2) service.set("testkey3", 3) @forEach = sinon.stub() service.forEach @forEach it "should call the callback with arguments (value, key, obj)", -> spyCall = @forEach.getCall(0) spyCall.args[0].should.equal(1) spyCall.args[1].should.equal("testkey1") spyCall.args[2].should.equal(service) it "should call the callback once for each item", -> @forEach.should.have.been.calledThrice describe "when calling clear", -> beforeEach -> @publishReady = sinon.stub() service.on("ready", @publishReady) service.set("testkey1", 1) service.set("testkey2", 2) service.set("testkey3", 3) service.clear() afterEach -> service.off("ready", @publishReady) it "should call storageProvider.getItem for the index", -> spyCall = @getMetadata.getCall(0) spyCall.args[0].should.equal("testns#index:primary") it "should call storageProvider.removeItem for each item/metadata plus the index", -> spyCall = @removeItem.getCall(0) spyCall.args[0].should.equal("testns#index:primary") spyCall = @removeItem.getCall(1) spyCall.args[0].should.equal("testns") # spyCall = @removeItem.getCall(2) # spyCall.args[0].should.equal("testns#metadata:testkey5") # spyCall = @removeItem.getCall(3) # spyCall.args[0].should.equal("testns:testkey5") it "should result in an empty array for keys", -> @keys = service.keys @keys.length.should.equal(0) it "should NOT publish a 'ready' event", -> @publishReady.should.not.have.been.called describe "with one item of pre-loaded data", -> beforeEach -> @publishAdded = sinon.stub() service = new StoreIt("loadns", @storageProvider) service.on("added", @publishAdded) afterEach -> service.off("added", @publishAdded) describe "when calling load", -> beforeEach -> service.load() it "should have a keys property with correct defaults", -> service.keys.should.be.an("array") service.keys.length.should.equal(1) it "it should call storageProvider.getItem for the index and each item", -> spyCall = @getMetadata.getCall(0) spyCall.args[0].should.equal("loadns#index:primary") spyCall = @getItem.getCall(0) spyCall.args[0].should.equal("loadns:testkey5") it "items loaded should be available with has", -> service.has("testkey5").should.equal(true) it "items loaded should be available with get", -> service.get("testkey5").should.equal("test") it "should publish an 'added' event for each item", -> @publishAdded.should.be.calledWith("test", "testkey5") it "should NOT throw a StoreitError when calling remove", -> (=> service.remove("testkey5") ).should.not.throw(StoreitError) describe "when calling set with options.publish = false", -> beforeEach -> service.options = {publish:false} service.load() it "should be publish nothing", -> @publishAdded.should.not.be.called describe "without calling `load`", -> beforeEach -> service = new StoreIt("testns", @storageProvider) it "should have `isInitialized` set to false", -> service.isInitialized.should.equal(false) it "should throw a StoreitError when calling has", -> (=> service.has("key") ).should.throw(StoreitError) it "should throw a StoreitError when calling get", -> (=> service.get("key") ).should.throw(StoreitError) it "should throw a StoreitError when calling set", -> (=> service.set("key", "value") ).should.throw(StoreitError) it "should throw a StoreitError when calling remove", -> (=> service.remove("key") ).should.throw(StoreitError) describe "then once we call load()", -> beforeEach -> @publishReady = sinon.stub() service.on("ready", @publishReady) service.load() afterEach -> service.off("ready", @publishReady) it "should have `isInitialized` set to true", -> service.isInitialized.should.equal(true) it "should publish a 'ready' event", -> @publishReady.should.have.been.called describe "then once we call clear()", -> beforeEach -> @publishReady = sinon.stub() service.on("ready", @publishReady) service.clear() afterEach -> service.off("ready", @publishReady) it "should have `isInitialized` set to true", -> service.isInitialized.should.equal(true) it "should publish a 'ready' event", -> @publishReady.should.have.been.called
true
"use strict" _ = require("underscore") StoreIt = require("..") # load StoreIt! StoreitError = StoreIt.StoreitError; describe "StoreIt.StoreitError", -> describe "(before calling new)", -> it "exists as a static property", -> StoreitError.should.not.equal(undefined) it "exposes the correct types", -> StoreitError.should.have.property("loadUninitialized") StoreitError.should.have.property("undefinedValue") StoreitError.should.have.property("invalidNamespace") StoreitError.should.have.property("nonexistentKey") StoreitError.should.have.property("invalidKey") describe "(after calling new)", -> err = new StoreitError(StoreitError.invalidNamespace) it "should be an instance of StoreitError", -> (err instanceof StoreitError).should.equal(true) it "should expose a `name` property", -> err.should.have.property("name") err.name.should.equal("StoreitError") it "should expose a `type` property", -> err.should.have.property("name") err.type.should.equal("invalidNamespace") it "should expose a `message` property", -> err.should.have.property("message") err.message.should.equal("namespace can not contain a hash character (#).") it "should expose a `stack` property", -> err.should.have.property("message") describe "StoreIt!", -> service = null testSet = (key, value, value2, setArgs, pk) -> beforeEach -> @value = value @value2 = value2 @publishAdded = sinon.stub() service.on("added", @publishAdded) @publishModified = sinon.stub() service.on("modified", @publishModified) if (pk && pk != "id") service.options = {primaryKey: pk} @result = service.set.apply(null, setArgs[0]) @result2 = service.set.apply(null, setArgs[1]) @result3 = service.set.apply(null, setArgs[2]) afterEach -> service.off("added", @publishAdded) service.off("modified", @publishModified) it "shold call storageProvider.setItem with the object", -> @storageProvider.setItem.should.be.calledWith("testns:" + key, @value) it "should publish a 'added' event", -> @publishAdded.should.have.been.called it "...with a CLONE of value", -> spyCall = @publishAdded.getCall(0) JSON.stringify(spyCall.args[0]).should.equal(JSON.stringify(@value)) spyCall.args[0].should.not.equal(@value) it "should publish a 'modified' event (if key exists)", -> @publishModified.should.have.been.called it "should publish a 'modified' event (if key exists) with the proper arguments", -> spyCall = @publishModified.getCall(0) publishedValue = @value2 if (pk) publishedValue = _.omit(publishedValue, pk) console.log(spyCall.args[0], publishedValue, pk) JSON.stringify(spyCall.args[0]).should.equal(JSON.stringify(publishedValue)) spyCall.args[1].should.equal(key) publishedValue = @value if (pk) publishedValue = _.omit(publishedValue, pk) JSON.stringify(spyCall.args[2]).should.equal(JSON.stringify(publishedValue)) spyCall.args[0].should.not.equal(@value) it "should NOT publish (if key exists and value is unchanged)", -> @publishModified.should.have.been.calledOnce it "should return a proper result object", -> @result.should.have.property("key") @result.key.should.equal(key) @result.should.have.property("value") @result.value.should.equal(@value) @result.should.have.property("action") @result.action.should.equal(StoreIt.Action.added) @result2.action.should.equal(StoreIt.Action.modified) @result3.action.should.equal(StoreIt.Action.none) it "should result in the correct value for keys", -> service.keys.length.should.equal(1) service.keys[0].should.equal(key) beforeEach -> @storageProvider = { name: "TestProvider" metadataSerializer: "TestMetadataSerializer" itemSerializer: "TestItemSerializer" } @getItem = sinon.stub() @getItem.withArgs("testns:testkey1").returns("test") @getItem.withArgs("testns:testkey2").returns(null) @getItem.withArgs("testns:testkey5").returns("test") @getItem.withArgs("loadns:testkey5").returns("test") @setItem = sinon.stub() @removeItem = sinon.stub() @setMetadata = sinon.stub() @getMetadata = sinon.stub() @getMetadata.withArgs("testns").returns(null) @getMetadata.withArgs("testns#index:primary").returns([]) @getMetadata.withArgs("loadns").returns(null) @getMetadata.withArgs("loadns#index:primary").returns(["testkey5"]) @storageProvider.getMetadata = @getMetadata @storageProvider.setMetadata = @setMetadata @storageProvider.getItem = @getItem @storageProvider.setItem = @setItem @storageProvider.removeItem = @removeItem describe "with no pre-loaded data", -> beforeEach -> service = new StoreIt("testns", @storageProvider) service.load() it "implements the correct interface", -> service.should.respondTo("has") service.should.respondTo("get") service.should.respondTo("fetch") service.should.respondTo("set") service.should.respondTo("metadata") service.should.respondTo("delete") service.should.respondTo("remove") service.should.respondTo("forEach") service.should.respondTo("clear") service.should.respondTo("load") service.should.respondTo("on") service.should.respondTo("off") service.should.respondTo("once") service.delete.should.equal(service.remove) it "should have an options property with correct defaults", -> service.options.publish.should.equal(true) it "should have a keys property with correct defaults", -> service.keys.should.be.an("array") service.keys.length.should.equal(0) it "should have a static enum Action with correct values", -> StoreIt.Action["none"].should.equal(0) StoreIt.Action["added"].should.equal(1) StoreIt.Action["modified"].should.equal(2) StoreIt.Action["removed"].should.equal(3) it "should have a static enum EventName with correct values", -> StoreIt.EventName["added"].should.equal("added") StoreIt.EventName["modified"].should.equal("modified") StoreIt.EventName["removed"].should.equal("removed") StoreIt.EventName["cleared"].should.equal("cleared") it "should throw a StoreitError when calling remove", -> (=> service.remove("key") ).should.throw(StoreitError) # ).should.throw(new StoreitError(StoreitError.nonexistentKey)) describe "calling set then modify the stored object", -> beforeEach -> @value = {foo: "foo"} service.set("key1", @value) @value.moo = "New property added" @retrievedValue = service.get("key1") it "should not modify the stored object", -> @retrievedValue.should.not.have.property("moo") describe "when calling has", -> it "on a valid key... should return true", -> service.set("testkey1", "test") @return = service.has("testkey1") @return.should.equal(true) it "on an invalid key... should return false", -> @return = service.has("testkey2") @return.should.equal(false) describe "when calling get", -> it "on a valid key... should return the correct value", -> @value = {foo: "foo"} service.set("testkey1", @value) @return = service.get("testkey1", "fun hater") @return.should.deep.equal(@value) it "on an invalid key... should return default value", -> @return = service.get("testkeyINVALID", "fun hater") @return.should.equal("fun hater") describe "when calling set with a key and value", -> key = "PI:KEY:<KEY>END_PI" value = {foo: "foo1"} value2 = {foo: "bar1"} setArgs = [[key, value], [key, value2], [key, value2]] testSet(key, value, value2, setArgs) describe "when calling set with only a value (PK default of 'id')", -> key = "PI:KEY:<KEY>END_PI" value = {id: key, foo: "foo2"} value2 = {id: key, foo: "bar2"} setArgs = [[value], [value2], [value2]] testSet(key, value, value2, setArgs, "id") describe "when calling set with only a value (PK of 'dw')", -> key = "PI:KEY:<KEY>END_PI" value = {dw: key, foo: "foo2"} value2 = {dw: key, foo: "bar2"} setArgs = [[value], [value2], [value2]] testSet(key, value, value2, setArgs, "dw") describe "when calling set on a key that exists (object)", -> beforeEach -> @key = "PI:KEY:<KEY>END_PI1" @value = {foo: "foo"} @results = service.set("testkey1", @value) describe "the returned results.key", -> it "should return the key", -> @results.key.should.equal(@key) it "should return the value", -> @results.value.should.eql(@value) describe "when setting a partial object with a new property", -> it "should result in an extended object with both properties", -> service.set("testkey1", {bar: "bar"}) service.get("testkey1").should.eql({foo: "foo", bar: "bar"}) describe "when setting a partial object with the same property, different value", -> it "should result in the property changed", -> service.set("testkey1", {foo: "bar"}) service.get("testkey1").should.eql({foo: "bar"}) describe "when setting the new value to a string", -> it "should result in the property changed", -> service.set("testkey1", "foo") service.get("testkey1").should.equal("foo") describe "when setting the new value to a number", -> it "should result in the property changed", -> service.set("testkey1", 123) service.get("testkey1").should.equal(123) describe "when setting the new value to an array", -> it "should result in the property changed", -> service.set("testkey1", [1, 2, 3]) service.get("testkey1").should.eql([1, 2, 3]) describe "when calling set on a key that exists (string)", -> beforeEach -> service.set("testkey1", "xxx") describe "when setting an object", -> it "should result in the setting the new object", -> @value = {foo: "foo"} service.set("testkey1", @value) service.get("testkey1").should.eql(@value) describe "when setting the new value to a string", -> it "should result in the property changed", -> @value = "foo" service.set("testkey1", @value) service.get("testkey1").should.equal(@value) describe "when setting the new value to a number", -> it "should result in the property changed", -> @value = 123 service.set("testkey1", @value) service.get("testkey1").should.equal(@value) describe "when calling set on a key that exists (array)", -> beforeEach -> service.set("testkey1", [1,2,3]) describe "when setting an array", -> it "should result in the setting the new object", -> @value = [4, 5, 6] service.set("testkey1", @value) service.get("testkey1").should.eql(@value) describe "when setting an object", -> it "should result in the setting the new object", -> @value = {foo: "foo"} service.set("testkey1", @value) service.get("testkey1").should.eql(@value) describe "when setting the new value to a string", -> it "should result in the property changed", -> @value = "foo" service.set("testkey1", @value) service.get("testkey1").should.equal(@value) describe "when setting the new value to a number", -> it "should result in the property changed", -> @value = 123 service.set("testkey1", @value) service.get("testkey1").should.equal(@value) describe "modifying the object that was stored without setting it to the store again", -> beforeEach -> @value = {"location":{"path":"3!@0.01951123900822323:0.028598665395614873"},"id":"62","text":"J"} @value2 = {"location":{"path":"modified@path"}} service.set("testbug", @value) # Add service.set("testbug", @value2) # Modify it "should not affect the value in the store", -> valueInStore = service.get("testbug") valueInStore.location.path.should.equal("modified@path") delete @value2.location.path valueInStore = service.get("testbug") valueInStore.location.should.have.property("path") describe "when calling set with a partial object", -> describe "which contains a new property", -> beforeEach -> service.set("testkey1", {foo: "foo"}) @result = service.set("testkey1", {bar: "bar"}) it "should return the entire object in results.value", -> @result.value.should.eql({foo: "foo", bar: "bar"}) it "should write the serializer name to storageProvider", -> spyCall = @storageProvider.setMetadata.getCall(0) spyCall.args[0].should.equal("testns") JSON.stringify(spyCall.args[1]).should.equal(JSON.stringify({itemSerializer:null})) it "should write the index to storageProvider", -> # @storageProvider.setItem.should.be.calledWith("testns:testkey1", JSON.stringify({foo: "foo", bar: "bar"})) spyCall = @storageProvider.setMetadata.getCall(1) spyCall.args[0].should.equal("testns#index:primary") JSON.stringify(spyCall.args[1]).should.equal(JSON.stringify(["testkey1"])) it "should write the first object to storageProvider", -> spyCall = @storageProvider.setItem.getCall(0) spyCall.args[0].should.equal("testns:testkey1") JSON.stringify(spyCall.args[1]).should.equal(JSON.stringify({foo: "foo"})) it "should write the entire extended object to storageProvider", -> spyCall = @storageProvider.setItem.getCall(1) spyCall.args[0].should.equal("testns:testkey1") JSON.stringify(spyCall.args[1]).should.equal(JSON.stringify({foo: "foo", bar: "bar"})) describe "which resets an existing property's value from an object to a primitive", -> beforeEach -> service.set("testkey1", {foo: {name: "foo"}}) @result = service.set("testkey1", {foo: "foo"}) it "should return the entire object in results.value", -> @result.value.should.eql({foo: "foo"}) describe "when accessing metadata", -> describe "on an INVALID key", -> it "should thow an exception", -> (-> service.metadata("testkey1002")).should.throw(Error) describe "on a valid key", -> beforeEach -> service.set("testkey1", "foo") @metadata = service.metadata("testkey1") it "should return a proper object", -> @metadata.should.have.property("get") @metadata.should.have.property("set") describe "and when calling set with undefined", -> it "should thow an exception", -> (-> @metadata.set(undefined)).should.throw(Error) describe "and when calling set with a valid argument", -> beforeEach -> @value = 123 @metadata.set(@value) it "should call storageProvider.setItem with JSON.stringified object", -> @storageProvider.setItem.should.be.calledWith("testns#metadata:testkey1", @value) describe "and a call to get", -> it "should return the same value", -> @metadata.get().should.equal(@value) describe "using the shorthand `set` syntax", -> beforeEach -> @key = "PI:KEY:<KEY>END_PI" @value = "bar" @results = service.set(@key, "foo", @value) describe "the returned results.metadata", -> it "should return the same value", -> @results.metadata.should.equal(@value) describe "and a call to get", -> it "should return the same value", -> service.metadata(@key).get().should.equal(@value) describe "when calling delete", -> beforeEach -> @value = {foo: "foo"} @publishRemoved = sinon.stub() service.on("removed", @publishRemoved) service.set("testkey1", @value) @result = service.delete("testkey1") afterEach -> service.off("removed", @publishRemoved) it "should call storageProvider.removeItem with JSON.stringified object", -> @storageProvider.removeItem.should.be.calledWith("testns:testkey1") @storageProvider.removeItem.should.be.calledWith("testns#metadata:testkey1") it "should thow an exception when called with an invalid key", -> (-> service.delete("testkey1002")).should.throw(Error) it "should publish an 'removed' event passing the correct value", -> spyCall = @publishRemoved.getCall(0) JSON.stringify(spyCall.args[0]).should.equal(JSON.stringify(@value)) it "should return a proper result object", -> @result.should.have.property("key") @result.key.should.equal("PI:KEY:<KEY>END_PI") @result.should.have.property("value") @result.value.should.deep.equal(@value) @result.should.have.property("action") @result.action.should.equal(StoreIt.Action.removed) describe "when calling forEach (with nothing set)", -> beforeEach -> @forEach = sinon.stub() service.forEach @forEach it "should do nothing when there are no items", -> @forEach.should.not.be.called describe "when calling forEach (with three items set)", -> beforeEach -> service.set("testkey1", 1) service.set("testkey2", 2) service.set("testkey3", 3) @forEach = sinon.stub() service.forEach @forEach it "should call the callback with arguments (value, key, obj)", -> spyCall = @forEach.getCall(0) spyCall.args[0].should.equal(1) spyCall.args[1].should.equal("testkey1") spyCall.args[2].should.equal(service) it "should call the callback once for each item", -> @forEach.should.have.been.calledThrice describe "when calling clear", -> beforeEach -> @publishReady = sinon.stub() service.on("ready", @publishReady) service.set("testkey1", 1) service.set("testkey2", 2) service.set("testkey3", 3) service.clear() afterEach -> service.off("ready", @publishReady) it "should call storageProvider.getItem for the index", -> spyCall = @getMetadata.getCall(0) spyCall.args[0].should.equal("testns#index:primary") it "should call storageProvider.removeItem for each item/metadata plus the index", -> spyCall = @removeItem.getCall(0) spyCall.args[0].should.equal("testns#index:primary") spyCall = @removeItem.getCall(1) spyCall.args[0].should.equal("testns") # spyCall = @removeItem.getCall(2) # spyCall.args[0].should.equal("testns#metadata:testkey5") # spyCall = @removeItem.getCall(3) # spyCall.args[0].should.equal("testns:testkey5") it "should result in an empty array for keys", -> @keys = service.keys @keys.length.should.equal(0) it "should NOT publish a 'ready' event", -> @publishReady.should.not.have.been.called describe "with one item of pre-loaded data", -> beforeEach -> @publishAdded = sinon.stub() service = new StoreIt("loadns", @storageProvider) service.on("added", @publishAdded) afterEach -> service.off("added", @publishAdded) describe "when calling load", -> beforeEach -> service.load() it "should have a keys property with correct defaults", -> service.keys.should.be.an("array") service.keys.length.should.equal(1) it "it should call storageProvider.getItem for the index and each item", -> spyCall = @getMetadata.getCall(0) spyCall.args[0].should.equal("loadns#index:primary") spyCall = @getItem.getCall(0) spyCall.args[0].should.equal("loadns:testkey5") it "items loaded should be available with has", -> service.has("testkey5").should.equal(true) it "items loaded should be available with get", -> service.get("testkey5").should.equal("test") it "should publish an 'added' event for each item", -> @publishAdded.should.be.calledWith("test", "testkey5") it "should NOT throw a StoreitError when calling remove", -> (=> service.remove("testkey5") ).should.not.throw(StoreitError) describe "when calling set with options.publish = false", -> beforeEach -> service.options = {publish:false} service.load() it "should be publish nothing", -> @publishAdded.should.not.be.called describe "without calling `load`", -> beforeEach -> service = new StoreIt("testns", @storageProvider) it "should have `isInitialized` set to false", -> service.isInitialized.should.equal(false) it "should throw a StoreitError when calling has", -> (=> service.has("key") ).should.throw(StoreitError) it "should throw a StoreitError when calling get", -> (=> service.get("key") ).should.throw(StoreitError) it "should throw a StoreitError when calling set", -> (=> service.set("key", "value") ).should.throw(StoreitError) it "should throw a StoreitError when calling remove", -> (=> service.remove("key") ).should.throw(StoreitError) describe "then once we call load()", -> beforeEach -> @publishReady = sinon.stub() service.on("ready", @publishReady) service.load() afterEach -> service.off("ready", @publishReady) it "should have `isInitialized` set to true", -> service.isInitialized.should.equal(true) it "should publish a 'ready' event", -> @publishReady.should.have.been.called describe "then once we call clear()", -> beforeEach -> @publishReady = sinon.stub() service.on("ready", @publishReady) service.clear() afterEach -> service.off("ready", @publishReady) it "should have `isInitialized` set to true", -> service.isInitialized.should.equal(true) it "should publish a 'ready' event", -> @publishReady.should.have.been.called
[ { "context": "Id])\n return Meteor.reconnect()\n loginFn(@toUserId)\n 'click .add-new' :->\n history = Session.get", "end": 3420, "score": 0.7448407411575317, "start": 3412, "tag": "USERNAME", "value": "toUserId" }, { "context": "ve': (e, t)->\n e.stopPropagation()\n ...
hotShareMobile/client/user/management/management.coffee
fay1986/mobile_app_server
7
Meteor['_unsubscribeAll'] = _.bind(Meteor.connection['_unsubscribeAll'], Meteor.connection); is_loading = new ReactiveVar([]) loginFn = (id)-> Meteor._unsubscribeAll() Meteor.loginWithUserId id, false, (err)-> # 切换帐号时清空PostSearch history Session.set("searchContent","") #PostsSearch.cleanHistory() if err is 'RESET_LOGIN' return navigator.notification.confirm('切换帐号失败~' (index)-> if index is 1 then loginFn id '提示', ['知道了', '重新切换'] ) else if err is 'NOT_LOGIN' return navigator.notification.confirm('切换帐号时发生异常,需要重新登录您的帐号!' ()-> return Router.go '/loginForm' '提示', ['重新登录'] ) else if err is 'WAIT_TIME' return navigator.notification.confirm '切换帐号太频繁了(间隔至少10秒),请稍后再试!', null, '提示', ['知道了'] window.plugins.userinfo.setUserInfo( Meteor.userId() ()-> console.log("setUserInfo was success ") ()-> console.log("setUserInfo was Error!") ) Router.go '/my_accounts_management' Meteor.defer ()-> Session.setPersistent('persistentMySavedDrafts', SavedDrafts.find({},{sort: {createdAt: -1},limit:2}).fetch()) Session.setPersistent('persistentMyOwnPosts', Posts.find({owner: Meteor.userId(),publish:{"$ne":false}}, {sort: {createdAt: -1},limit:4}).fetch()) Session.setPersistent('myFollowedByCount',Counts.get('myFollowedByCount')) Session.setPersistent('mySavedDraftsCount',Counts.get('mySavedDraftsCount')) Session.setPersistent('myPostsCount',Counts.get('myPostsCount')) Session.setPersistent('myFollowToCount',Counts.get('myFollowToCount')) Session.setPersistent('myFollowToCount',Counts.get('myEmailFollowerCount')) is_loading.set([]) navigator.notification.confirm '切换帐号成功~', null, '提示', ['知道了'] Template.accounts_management.rendered=-> is_loading = new ReactiveVar([]) Tracker.autorun ()-> if Meteor.status().connected && is_loading.get().length > 0 loginFn is_loading.get().pop() is_loading.set([]) $('.dashboard').css 'min-height', $(window).height() # userIds = [] # AssociatedUsers.find({}).forEach((item)-> # if Meteor.userId() isnt item.userIdA and !~ userIds.indexOf(item.userIdA) # userIds.push(item.userIdA) # if Meteor.userId() isnt item.userIdB and !~ userIds.indexOf(item.userIdB) # userIds.push(item.userIdB) # ) # Meteor.subscribe('associateduserdetails', userIds) # return Template.accounts_management.helpers is_me: (id)-> return id is Meteor.userId() connecting: -> return is_loading.get().length > 0 loging: -> return Meteor.loggingIn() accountList :-> UserRelation.find({userId: Meteor.userId()}) # userIds = [] # AssociatedUsers.find({}).forEach((item)-> # if Meteor.userId() isnt item.userIdA and !~ userIds.indexOf(item.userIdA) # userIds.push(item.userIdA) # if Meteor.userId() isnt item.userIdB and !~ userIds.indexOf(item.userIdB) # userIds.push(item.userIdB) # ) # return Meteor.users.find({_id: {'$in': userIds}}) Template.accounts_management.events 'click dl.my_account': -> if is_loading.get().length > 0 return navigator.notification.confirm '正在切换中,请稍后在试~', null, '提示', ['知道了'] slef = this unless Meteor.status().connected is_loading.set([@toUserId]) return Meteor.reconnect() loginFn(@toUserId) 'click .add-new' :-> history = Session.get("history_view") history.push { view: 'my_accounts_management' scrollTop: document.body.scrollTop } Session.set "history_view", history Router.go '/my_accounts_management_addnew' 'click .remove': (e, t)-> e.stopPropagation() id = @toUserId #console.log(this._id) #console.log(e.currentTarget) PUB.confirm( '确定要删除吗?' ()-> Meteor.call( 'removeAssociatedUserNew' id ) ) 'click .leftButton' :-> Router.go '/dashboard' Template.accounts_management_addnew.rendered=-> $('.dashboard').css 'min-height', $(window).height() return Template.accounts_management_addnew.events 'click .leftButton' :-> PUB.back() 'submit #form-addnew': (e, t)-> e.preventDefault() # need wait method response $(e.target).find('input[type=submit]').attr('disabled','').removeClass('active').val('添加中...') userInfo = { username: $(e.target).find('input[name=username]').val(), password: Package.sha.SHA256($(e.target).find('input[name=password]').val()), type: Meteor.user().type, token: Meteor.user().token } Meteor.call('addAssociatedUserNew', userInfo, (err, data)-> $(e.target).find('input[type=submit]').removeAttr('disabled').addClass('active').val('添加') if data and data.status is 'ERROR' if data.message is 'Invalid Username' PUB.toast('用户不存在') else if data.message is 'Can not add their own' PUB.toast('不能添加自己') else if data.message is 'Exist Associate User' PUB.toast('该用户已关联') else if data.message is 'Invalid Password' PUB.toast('密码不正确') else PUB.toast('用户名或密码不正确') else Router.go '/my_accounts_management' ); Template.accounts_management_prompt.rendered=-> $(".spinner .spinner-blade").css({"width":"0.104em","height":"0.4777em","transform-origin":"center -0.4222em"}) $("body,html").css({"overflow":"hidden"}) return Template.accounts_management_prompt.events 'click .prompt-close' :-> $('.page-accounts-management-prompt').remove() Template.accounts_management_prompt.destroyed=-> $(".spinner .spinner-blade").css({"width":"0.074em","height":"0.2777em","transform-origin":"center -0.2222em"}) $("body,html").css({"overflow":""}) return
15638
Meteor['_unsubscribeAll'] = _.bind(Meteor.connection['_unsubscribeAll'], Meteor.connection); is_loading = new ReactiveVar([]) loginFn = (id)-> Meteor._unsubscribeAll() Meteor.loginWithUserId id, false, (err)-> # 切换帐号时清空PostSearch history Session.set("searchContent","") #PostsSearch.cleanHistory() if err is 'RESET_LOGIN' return navigator.notification.confirm('切换帐号失败~' (index)-> if index is 1 then loginFn id '提示', ['知道了', '重新切换'] ) else if err is 'NOT_LOGIN' return navigator.notification.confirm('切换帐号时发生异常,需要重新登录您的帐号!' ()-> return Router.go '/loginForm' '提示', ['重新登录'] ) else if err is 'WAIT_TIME' return navigator.notification.confirm '切换帐号太频繁了(间隔至少10秒),请稍后再试!', null, '提示', ['知道了'] window.plugins.userinfo.setUserInfo( Meteor.userId() ()-> console.log("setUserInfo was success ") ()-> console.log("setUserInfo was Error!") ) Router.go '/my_accounts_management' Meteor.defer ()-> Session.setPersistent('persistentMySavedDrafts', SavedDrafts.find({},{sort: {createdAt: -1},limit:2}).fetch()) Session.setPersistent('persistentMyOwnPosts', Posts.find({owner: Meteor.userId(),publish:{"$ne":false}}, {sort: {createdAt: -1},limit:4}).fetch()) Session.setPersistent('myFollowedByCount',Counts.get('myFollowedByCount')) Session.setPersistent('mySavedDraftsCount',Counts.get('mySavedDraftsCount')) Session.setPersistent('myPostsCount',Counts.get('myPostsCount')) Session.setPersistent('myFollowToCount',Counts.get('myFollowToCount')) Session.setPersistent('myFollowToCount',Counts.get('myEmailFollowerCount')) is_loading.set([]) navigator.notification.confirm '切换帐号成功~', null, '提示', ['知道了'] Template.accounts_management.rendered=-> is_loading = new ReactiveVar([]) Tracker.autorun ()-> if Meteor.status().connected && is_loading.get().length > 0 loginFn is_loading.get().pop() is_loading.set([]) $('.dashboard').css 'min-height', $(window).height() # userIds = [] # AssociatedUsers.find({}).forEach((item)-> # if Meteor.userId() isnt item.userIdA and !~ userIds.indexOf(item.userIdA) # userIds.push(item.userIdA) # if Meteor.userId() isnt item.userIdB and !~ userIds.indexOf(item.userIdB) # userIds.push(item.userIdB) # ) # Meteor.subscribe('associateduserdetails', userIds) # return Template.accounts_management.helpers is_me: (id)-> return id is Meteor.userId() connecting: -> return is_loading.get().length > 0 loging: -> return Meteor.loggingIn() accountList :-> UserRelation.find({userId: Meteor.userId()}) # userIds = [] # AssociatedUsers.find({}).forEach((item)-> # if Meteor.userId() isnt item.userIdA and !~ userIds.indexOf(item.userIdA) # userIds.push(item.userIdA) # if Meteor.userId() isnt item.userIdB and !~ userIds.indexOf(item.userIdB) # userIds.push(item.userIdB) # ) # return Meteor.users.find({_id: {'$in': userIds}}) Template.accounts_management.events 'click dl.my_account': -> if is_loading.get().length > 0 return navigator.notification.confirm '正在切换中,请稍后在试~', null, '提示', ['知道了'] slef = this unless Meteor.status().connected is_loading.set([@toUserId]) return Meteor.reconnect() loginFn(@toUserId) 'click .add-new' :-> history = Session.get("history_view") history.push { view: 'my_accounts_management' scrollTop: document.body.scrollTop } Session.set "history_view", history Router.go '/my_accounts_management_addnew' 'click .remove': (e, t)-> e.stopPropagation() id = @toUserId #console.log(this._id) #console.log(e.currentTarget) PUB.confirm( '确定要删除吗?' ()-> Meteor.call( 'removeAssociatedUserNew' id ) ) 'click .leftButton' :-> Router.go '/dashboard' Template.accounts_management_addnew.rendered=-> $('.dashboard').css 'min-height', $(window).height() return Template.accounts_management_addnew.events 'click .leftButton' :-> PUB.back() 'submit #form-addnew': (e, t)-> e.preventDefault() # need wait method response $(e.target).find('input[type=submit]').attr('disabled','').removeClass('active').val('添加中...') userInfo = { username: $(e.target).find('input[name=username]').val(), password: <PASSWORD>($(e.<PASSWORD>).find('input[name=password]').val()), type: Meteor.user().type, token: Meteor.user().token } Meteor.call('addAssociatedUserNew', userInfo, (err, data)-> $(e.target).find('input[type=submit]').removeAttr('disabled').addClass('active').val('添加') if data and data.status is 'ERROR' if data.message is 'Invalid Username' PUB.toast('用户不存在') else if data.message is 'Can not add their own' PUB.toast('不能添加自己') else if data.message is 'Exist Associate User' PUB.toast('该用户已关联') else if data.message is 'Invalid Password' PUB.toast('密码不正确') else PUB.toast('用户名或密码不正确') else Router.go '/my_accounts_management' ); Template.accounts_management_prompt.rendered=-> $(".spinner .spinner-blade").css({"width":"0.104em","height":"0.4777em","transform-origin":"center -0.4222em"}) $("body,html").css({"overflow":"hidden"}) return Template.accounts_management_prompt.events 'click .prompt-close' :-> $('.page-accounts-management-prompt').remove() Template.accounts_management_prompt.destroyed=-> $(".spinner .spinner-blade").css({"width":"0.074em","height":"0.2777em","transform-origin":"center -0.2222em"}) $("body,html").css({"overflow":""}) return
true
Meteor['_unsubscribeAll'] = _.bind(Meteor.connection['_unsubscribeAll'], Meteor.connection); is_loading = new ReactiveVar([]) loginFn = (id)-> Meteor._unsubscribeAll() Meteor.loginWithUserId id, false, (err)-> # 切换帐号时清空PostSearch history Session.set("searchContent","") #PostsSearch.cleanHistory() if err is 'RESET_LOGIN' return navigator.notification.confirm('切换帐号失败~' (index)-> if index is 1 then loginFn id '提示', ['知道了', '重新切换'] ) else if err is 'NOT_LOGIN' return navigator.notification.confirm('切换帐号时发生异常,需要重新登录您的帐号!' ()-> return Router.go '/loginForm' '提示', ['重新登录'] ) else if err is 'WAIT_TIME' return navigator.notification.confirm '切换帐号太频繁了(间隔至少10秒),请稍后再试!', null, '提示', ['知道了'] window.plugins.userinfo.setUserInfo( Meteor.userId() ()-> console.log("setUserInfo was success ") ()-> console.log("setUserInfo was Error!") ) Router.go '/my_accounts_management' Meteor.defer ()-> Session.setPersistent('persistentMySavedDrafts', SavedDrafts.find({},{sort: {createdAt: -1},limit:2}).fetch()) Session.setPersistent('persistentMyOwnPosts', Posts.find({owner: Meteor.userId(),publish:{"$ne":false}}, {sort: {createdAt: -1},limit:4}).fetch()) Session.setPersistent('myFollowedByCount',Counts.get('myFollowedByCount')) Session.setPersistent('mySavedDraftsCount',Counts.get('mySavedDraftsCount')) Session.setPersistent('myPostsCount',Counts.get('myPostsCount')) Session.setPersistent('myFollowToCount',Counts.get('myFollowToCount')) Session.setPersistent('myFollowToCount',Counts.get('myEmailFollowerCount')) is_loading.set([]) navigator.notification.confirm '切换帐号成功~', null, '提示', ['知道了'] Template.accounts_management.rendered=-> is_loading = new ReactiveVar([]) Tracker.autorun ()-> if Meteor.status().connected && is_loading.get().length > 0 loginFn is_loading.get().pop() is_loading.set([]) $('.dashboard').css 'min-height', $(window).height() # userIds = [] # AssociatedUsers.find({}).forEach((item)-> # if Meteor.userId() isnt item.userIdA and !~ userIds.indexOf(item.userIdA) # userIds.push(item.userIdA) # if Meteor.userId() isnt item.userIdB and !~ userIds.indexOf(item.userIdB) # userIds.push(item.userIdB) # ) # Meteor.subscribe('associateduserdetails', userIds) # return Template.accounts_management.helpers is_me: (id)-> return id is Meteor.userId() connecting: -> return is_loading.get().length > 0 loging: -> return Meteor.loggingIn() accountList :-> UserRelation.find({userId: Meteor.userId()}) # userIds = [] # AssociatedUsers.find({}).forEach((item)-> # if Meteor.userId() isnt item.userIdA and !~ userIds.indexOf(item.userIdA) # userIds.push(item.userIdA) # if Meteor.userId() isnt item.userIdB and !~ userIds.indexOf(item.userIdB) # userIds.push(item.userIdB) # ) # return Meteor.users.find({_id: {'$in': userIds}}) Template.accounts_management.events 'click dl.my_account': -> if is_loading.get().length > 0 return navigator.notification.confirm '正在切换中,请稍后在试~', null, '提示', ['知道了'] slef = this unless Meteor.status().connected is_loading.set([@toUserId]) return Meteor.reconnect() loginFn(@toUserId) 'click .add-new' :-> history = Session.get("history_view") history.push { view: 'my_accounts_management' scrollTop: document.body.scrollTop } Session.set "history_view", history Router.go '/my_accounts_management_addnew' 'click .remove': (e, t)-> e.stopPropagation() id = @toUserId #console.log(this._id) #console.log(e.currentTarget) PUB.confirm( '确定要删除吗?' ()-> Meteor.call( 'removeAssociatedUserNew' id ) ) 'click .leftButton' :-> Router.go '/dashboard' Template.accounts_management_addnew.rendered=-> $('.dashboard').css 'min-height', $(window).height() return Template.accounts_management_addnew.events 'click .leftButton' :-> PUB.back() 'submit #form-addnew': (e, t)-> e.preventDefault() # need wait method response $(e.target).find('input[type=submit]').attr('disabled','').removeClass('active').val('添加中...') userInfo = { username: $(e.target).find('input[name=username]').val(), password: PI:PASSWORD:<PASSWORD>END_PI($(e.PI:PASSWORD:<PASSWORD>END_PI).find('input[name=password]').val()), type: Meteor.user().type, token: Meteor.user().token } Meteor.call('addAssociatedUserNew', userInfo, (err, data)-> $(e.target).find('input[type=submit]').removeAttr('disabled').addClass('active').val('添加') if data and data.status is 'ERROR' if data.message is 'Invalid Username' PUB.toast('用户不存在') else if data.message is 'Can not add their own' PUB.toast('不能添加自己') else if data.message is 'Exist Associate User' PUB.toast('该用户已关联') else if data.message is 'Invalid Password' PUB.toast('密码不正确') else PUB.toast('用户名或密码不正确') else Router.go '/my_accounts_management' ); Template.accounts_management_prompt.rendered=-> $(".spinner .spinner-blade").css({"width":"0.104em","height":"0.4777em","transform-origin":"center -0.4222em"}) $("body,html").css({"overflow":"hidden"}) return Template.accounts_management_prompt.events 'click .prompt-close' :-> $('.page-accounts-management-prompt').remove() Template.accounts_management_prompt.destroyed=-> $(".spinner .spinner-blade").css({"width":"0.074em","height":"0.2777em","transform-origin":"center -0.2222em"}) $("body,html").css({"overflow":""}) return
[ { "context": "exports.Circle extends Entity\n\n\tentity :\n\t\tname: \"Circle\"\n\t\ttype: \"a-circle\"\n\n\t# -------------------------", "end": 110, "score": 0.6574981808662415, "start": 104, "tag": "NAME", "value": "Circle" } ]
src/Circle.coffee
etiennepinchon/hologram
89
{entityAttribute, Entity} = require "./Entity" class exports.Circle extends Entity entity : name: "Circle" type: "a-circle" # ---------------------------------------------------------------------------- # PROPERTIES @define "radius", entityAttribute("radius", "radius", 1) @define "segments", entityAttribute("segments", "segments", 32) @define "thetaLength", entityAttribute("thetaLength", "theta-length", 360) @define "thetaStart", entityAttribute("thetaStart", "theta-start", 0)
101630
{entityAttribute, Entity} = require "./Entity" class exports.Circle extends Entity entity : name: "<NAME>" type: "a-circle" # ---------------------------------------------------------------------------- # PROPERTIES @define "radius", entityAttribute("radius", "radius", 1) @define "segments", entityAttribute("segments", "segments", 32) @define "thetaLength", entityAttribute("thetaLength", "theta-length", 360) @define "thetaStart", entityAttribute("thetaStart", "theta-start", 0)
true
{entityAttribute, Entity} = require "./Entity" class exports.Circle extends Entity entity : name: "PI:NAME:<NAME>END_PI" type: "a-circle" # ---------------------------------------------------------------------------- # PROPERTIES @define "radius", entityAttribute("radius", "radius", 1) @define "segments", entityAttribute("segments", "segments", 32) @define "thetaLength", entityAttribute("thetaLength", "theta-length", 360) @define "thetaStart", entityAttribute("thetaStart", "theta-start", 0)
[ { "context": "\"\n return false\n\n user = resolveUsers(firstName, data.users)[0]\n\n params =\n \"assigned", "end": 2559, "score": 0.48177722096443176, "start": 2550, "tag": "NAME", "value": "firstName" }, { "context": ".reply \"Couldn't find any users with t...
src/scripts/redmine.coffee
atlassian/hubot-scripts
0
# Showing of redmine issuess via the REST API. # # (redmine|show) me <issue-id> - Show the issue status # show (my|user's) issues - Show your issues or another user's issues # assign <issue-id> to <user-first-name> ["notes"] - Assign the issue to the user (searches login or firstname) # *With optional notes # update <issue-id> with "<note>" - Adds a note to the issue # add <hours> hours to <issue-id> ["comments"] - Adds hours to the issue with the optional comments # Note: <issue-id> can be formatted in the following ways: # 1234, #1234, issue 1234, issue #1234 # #--- # # To get set up refer to the guide http://www.redmine.org/projects/redmine/wiki/Rest_api#Authentication # After that, heroku needs the following config # # heroku config:add HUBOT_REDMINE_BASE_URL="http://redmine.your-server.com" # heroku config:add HUBOT_REDMINE_TOKEN="your api token here" # # There may be issues if you have a lot of redmine users sharing a first name, but this can be avoided # by using redmine logins rather than firstnames # HTTP = require('http') URL = require('url') QUERY = require('querystring') module.exports = (robot) -> redmine = new Redmine process.env.HUBOT_REDMINE_BASE_URL, process.env.HUBOT_REDMINE_TOKEN # Robot add <hours> hours to <issue_id> ["comments for the time tracking"] robot.respond /add (\d{1,2}) hours? to (?:issue )?(?:#)?(\d+)(?: "?([^"]+)"?)?/i, (msg) -> [hours, id, userComments] = msg.match[1..3] if userComments? comments = "#{msg.message.user.name}: #{userComments}" else comments = "Time logged by: #{msg.message.user.name}" attributes = "issue_id": id "hours": hours "comments": comments redmine.TimeEntry(null).create attributes, (status,data) -> if status == 201 msg.reply "Your time was logged" else msg.reply "Nothing could be logged. Make sure RedMine has a default activity set for time tracking. (Settings -> Enumerations -> Activities)" # Robot show <my|user's> [redmine] issues robot.respond /show (?:my|(\w+\'s)) (?:redmine )?issues/i, (msg) -> userMode = true firstName = if msg.match[1]? userMode = false msg.match[1].replace(/\'.+/, '') else msg.message.user.name.split(/\s/)[0] redmine.Users name:firstName, (err,data) -> unless data.total_count > 0 msg.reply "Couldn't find any users with the name \"#{firstName}\"" return false user = resolveUsers(firstName, data.users)[0] params = "assigned_to_id": user.id "limit": 25, "status_id": "open" "sort": "priority:desc", redmine.Issues params, (err, data) -> if err? msg.reply "Couldn't get a list of issues for you!" else _ = [] if userMode _.push "You have #{data.total_count} issue(s)." else _.push "#{user.firstname} has #{data.total_count} issue(s)." for issue in data.issues do (issue) -> _.push "\n[#{issue.tracker.name} - #{issue.priority.name} - #{issue.status.name}] ##{issue.id}: #{issue.subject}" msg.reply _.join "\n" # Robot update <issue> with "<note>" robot.respond /update (?:issue )?(?:#)?(\d+)(?:\s*with\s*)?(?:[-:,])? (?:"?([^"]+)"?)/i, (msg) -> [id, note] = msg.match[1..2] attributes = "notes": "#{msg.message.user.name}: #{note}" redmine.Issue(id).update attributes, (err, data) -> if err? if err == 404 msg.reply "Issue ##{id} doesn't exist." else msg.reply "Couldn't update this issue, sorry :(" else msg.reply "Done! Updated ##{id} with \"#{note}\"" # Robot assign <issue> to <user> ["note to add with the assignment] robot.respond /assign (?:issue )?(?:#)?(\d+) to (\w+)(?: "?([^"]+)"?)?/i, (msg) -> [id, userName, note] = msg.match[1..3] redmine.Users name:userName, (err, data) -> unless data.total_count > 0 msg.reply "Couldn't find any users with the name \"#{userName}\"" return false # try to resolve the user using login/firstname -- take the first result (hacky) user = resolveUsers(userName, data.users)[0] attributes = "assigned_to_id": user.id # allow an optional note with the re-assign attributes["notes"] = "#{msg.message.user.name}: #{note}" if note? # get our issue redmine.Issue(id).update attributes, (err, data) -> if err? if err == 404 msg.reply "Issue ##{id} doesn't exist." else msg.reply "There was an error assigning this issue." else msg.reply "Assigned ##{id} to #{user.firstname}." # Robot redmine me <issue> robot.respond /(?:redmine|show)(?: me)? (?:issue )?(?:#)?(\d+)/i, (msg) -> id = msg.match[1] params = "include": "journals" redmine.Issue(id).show params, (err, data) -> unless data? msg.reply "Issue ##{id} doesn't exist." return false issue = data.issue _ = [] _.push "\n[#{issue.project.name} - #{issue.priority.name}] #{issue.tracker.name} ##{issue.id} (#{issue.status.name})" _.push "Assigned: #{issue.assigned_to?.name ? 'Nobody'} (opened by #{issue.author.name})" if issue.status.name.toLowerCase() != 'new' _.push "Progress: #{issue.done_ratio}% (#{issue.spent_hours} hours)" _.push "Subject: #{issue.subject}" _.push "\n#{issue.description}" # journals _.push "\n" + Array(10).join('-') + '8<' + Array(50).join('-') + "\n" for journal in issue.journals do (journal) -> if journal.notes? and journal.notes != "" date = formatDate journal.created_on, 'mm/dd/yyyy (hh:ii ap)' _.push "#{journal.user.name} on #{date}:" _.push " #{journal.notes}\n" msg.reply _.join "\n" # simple ghetto fab date formatter this should definitely be replaced, but didn't want to # introduce dependencies this early # # dateStamp - any string that can initialize a date # fmt - format string that may use the following elements # mm - month # dd - day # yyyy - full year # hh - hours # ii - minutes # ss - seconds # ap - am / pm # # returns the formatted date formatDate = (dateStamp, fmt = 'mm/dd/yyyy at hh:ii ap') -> d = new Date(dateStamp) # split up the date [m,d,y,h,i,s,ap] = [d.getMonth() + 1, d.getDate(), d.getFullYear(), d.getHours(), d.getMinutes(), d.getSeconds(), 'AM'] # leadig 0s i = "0#{i}" if i < 10 s = "0#{s}" if s < 10 # adjust hours if h > 12 h = h - 12 ap = "PM" # ghetto fab! fmt .replace(/mm/, m) .replace(/dd/, d) .replace(/yyyy/, y) .replace(/hh/, h) .replace(/ii/, i) .replace(/ss/, s) .replace(/ap/, ap) # tries to resolve ambiguous users by matching login or firstname # redmine's user search is pretty broad (using login/name/email/etc.) so # we're trying to just pull it in a bit and get a single user # # name - this should be the name you're trying to match # data - this is the array of users from redmine # # returns an array with a single user, or the original array if nothing matched resolveUsers = (name, data) -> name = name.toLowerCase(); # try matching login found = data.filter (user) -> user.login.toLowerCase() == name return found if found.length == 1 # try first name found = data.filter (user) -> user.firstname.toLowerCase() == name return found if found.length == 1 # give up data # Redmine API Mapping # This isn't 100% complete, but its the basics for what we would need in campfire class Redmine constructor: (url, token) -> @url = url @token = token Users: (params, callback) -> @get "/users.json", params, callback User: (id) -> show: (callback) => @get "/users/#{id}.json", {}, callback Projects: (params, callback) -> @get "/projects.json", params, callback Issues: (params, callback) -> @get "/issues.json", params, callback Issue: (id) -> show: (params, callback) => @get "/issues/#{id}.json", params, callback update: (attributes, callback) => @put "/issues/#{id}.json", {issue: attributes}, callback TimeEntry: (id) -> create: (attributes, callback) => @post "/time_entries.json", {time_entry: attributes}, callback # Private: do a GET request against the API get: (path, params, callback) -> path = "#{path}?#{QUERY.stringify params}" if params? @request "GET", path, null, callback # Private: do a POST request against the API post: (path, body, callback) -> @request "POST", path, body, callback # Private: do a PUT request against the API put: (path, body, callback) -> @request "PUT", path, body, callback # Private: Perform a request against the redmine REST API # from the campfire adapter :) request: (method, path, body, callback) -> headers = "Content-Type": "application/json" "X-Redmine-API-Key": @token endpoint = URL.parse(@url) pathname = endpoint.pathname.replace /^\/$/, '' options = "host" : endpoint.hostname "path" : "#{pathname}#{path}" "method" : method "headers": headers if method in ["POST", "PUT"] if typeof(body) isnt "string" body = JSON.stringify body options.headers["Content-Length"] = body.length request = HTTP.request options, (response) -> data = "" response.on "data", (chunk) -> data += chunk response.on "end", -> switch response.statusCode when 200 try callback null, JSON.parse(data) catch err callback null, data or { } when 401 throw new Error "401: Authentication failed." else console.error "Code: #{response.statusCode}" callback response.statusCode, null response.on "error", (err) -> console.error "Redmine response error: #{err}" callback err, null if method in ["POST", "PUT"] request.end(body, 'binary') else request.end() request.on "error", (err) -> console.error "Redmine request error: #{err}" callback err, null
43402
# Showing of redmine issuess via the REST API. # # (redmine|show) me <issue-id> - Show the issue status # show (my|user's) issues - Show your issues or another user's issues # assign <issue-id> to <user-first-name> ["notes"] - Assign the issue to the user (searches login or firstname) # *With optional notes # update <issue-id> with "<note>" - Adds a note to the issue # add <hours> hours to <issue-id> ["comments"] - Adds hours to the issue with the optional comments # Note: <issue-id> can be formatted in the following ways: # 1234, #1234, issue 1234, issue #1234 # #--- # # To get set up refer to the guide http://www.redmine.org/projects/redmine/wiki/Rest_api#Authentication # After that, heroku needs the following config # # heroku config:add HUBOT_REDMINE_BASE_URL="http://redmine.your-server.com" # heroku config:add HUBOT_REDMINE_TOKEN="your api token here" # # There may be issues if you have a lot of redmine users sharing a first name, but this can be avoided # by using redmine logins rather than firstnames # HTTP = require('http') URL = require('url') QUERY = require('querystring') module.exports = (robot) -> redmine = new Redmine process.env.HUBOT_REDMINE_BASE_URL, process.env.HUBOT_REDMINE_TOKEN # Robot add <hours> hours to <issue_id> ["comments for the time tracking"] robot.respond /add (\d{1,2}) hours? to (?:issue )?(?:#)?(\d+)(?: "?([^"]+)"?)?/i, (msg) -> [hours, id, userComments] = msg.match[1..3] if userComments? comments = "#{msg.message.user.name}: #{userComments}" else comments = "Time logged by: #{msg.message.user.name}" attributes = "issue_id": id "hours": hours "comments": comments redmine.TimeEntry(null).create attributes, (status,data) -> if status == 201 msg.reply "Your time was logged" else msg.reply "Nothing could be logged. Make sure RedMine has a default activity set for time tracking. (Settings -> Enumerations -> Activities)" # Robot show <my|user's> [redmine] issues robot.respond /show (?:my|(\w+\'s)) (?:redmine )?issues/i, (msg) -> userMode = true firstName = if msg.match[1]? userMode = false msg.match[1].replace(/\'.+/, '') else msg.message.user.name.split(/\s/)[0] redmine.Users name:firstName, (err,data) -> unless data.total_count > 0 msg.reply "Couldn't find any users with the name \"#{firstName}\"" return false user = resolveUsers(<NAME>, data.users)[0] params = "assigned_to_id": user.id "limit": 25, "status_id": "open" "sort": "priority:desc", redmine.Issues params, (err, data) -> if err? msg.reply "Couldn't get a list of issues for you!" else _ = [] if userMode _.push "You have #{data.total_count} issue(s)." else _.push "#{user.firstname} has #{data.total_count} issue(s)." for issue in data.issues do (issue) -> _.push "\n[#{issue.tracker.name} - #{issue.priority.name} - #{issue.status.name}] ##{issue.id}: #{issue.subject}" msg.reply _.join "\n" # Robot update <issue> with "<note>" robot.respond /update (?:issue )?(?:#)?(\d+)(?:\s*with\s*)?(?:[-:,])? (?:"?([^"]+)"?)/i, (msg) -> [id, note] = msg.match[1..2] attributes = "notes": "#{msg.message.user.name}: #{note}" redmine.Issue(id).update attributes, (err, data) -> if err? if err == 404 msg.reply "Issue ##{id} doesn't exist." else msg.reply "Couldn't update this issue, sorry :(" else msg.reply "Done! Updated ##{id} with \"#{note}\"" # Robot assign <issue> to <user> ["note to add with the assignment] robot.respond /assign (?:issue )?(?:#)?(\d+) to (\w+)(?: "?([^"]+)"?)?/i, (msg) -> [id, userName, note] = msg.match[1..3] redmine.Users name:userName, (err, data) -> unless data.total_count > 0 msg.reply "Couldn't find any users with the name \"#{userName}\"" return false # try to resolve the user using login/firstname -- take the first result (hacky) user = resolveUsers(userName, data.users)[0] attributes = "assigned_to_id": user.id # allow an optional note with the re-assign attributes["notes"] = "#{msg.message.user.name}: #{note}" if note? # get our issue redmine.Issue(id).update attributes, (err, data) -> if err? if err == 404 msg.reply "Issue ##{id} doesn't exist." else msg.reply "There was an error assigning this issue." else msg.reply "Assigned ##{id} to #{user.firstname}." # Robot redmine me <issue> robot.respond /(?:redmine|show)(?: me)? (?:issue )?(?:#)?(\d+)/i, (msg) -> id = msg.match[1] params = "include": "journals" redmine.Issue(id).show params, (err, data) -> unless data? msg.reply "Issue ##{id} doesn't exist." return false issue = data.issue _ = [] _.push "\n[#{issue.project.name} - #{issue.priority.name}] #{issue.tracker.name} ##{issue.id} (#{issue.status.name})" _.push "Assigned: #{issue.assigned_to?.name ? 'Nobody'} (opened by #{issue.author.name})" if issue.status.name.toLowerCase() != 'new' _.push "Progress: #{issue.done_ratio}% (#{issue.spent_hours} hours)" _.push "Subject: #{issue.subject}" _.push "\n#{issue.description}" # journals _.push "\n" + Array(10).join('-') + '8<' + Array(50).join('-') + "\n" for journal in issue.journals do (journal) -> if journal.notes? and journal.notes != "" date = formatDate journal.created_on, 'mm/dd/yyyy (hh:ii ap)' _.push "#{journal.user.name} on #{date}:" _.push " #{journal.notes}\n" msg.reply _.join "\n" # simple ghetto fab date formatter this should definitely be replaced, but didn't want to # introduce dependencies this early # # dateStamp - any string that can initialize a date # fmt - format string that may use the following elements # mm - month # dd - day # yyyy - full year # hh - hours # ii - minutes # ss - seconds # ap - am / pm # # returns the formatted date formatDate = (dateStamp, fmt = 'mm/dd/yyyy at hh:ii ap') -> d = new Date(dateStamp) # split up the date [m,d,y,h,i,s,ap] = [d.getMonth() + 1, d.getDate(), d.getFullYear(), d.getHours(), d.getMinutes(), d.getSeconds(), 'AM'] # leadig 0s i = "0#{i}" if i < 10 s = "0#{s}" if s < 10 # adjust hours if h > 12 h = h - 12 ap = "PM" # ghetto fab! fmt .replace(/mm/, m) .replace(/dd/, d) .replace(/yyyy/, y) .replace(/hh/, h) .replace(/ii/, i) .replace(/ss/, s) .replace(/ap/, ap) # tries to resolve ambiguous users by matching login or firstname # redmine's user search is pretty broad (using login/name/email/etc.) so # we're trying to just pull it in a bit and get a single user # # name - this should be the name you're trying to match # data - this is the array of users from redmine # # returns an array with a single user, or the original array if nothing matched resolveUsers = (name, data) -> name = name.toLowerCase(); # try matching login found = data.filter (user) -> user.login.toLowerCase() == name return found if found.length == 1 # try first name found = data.filter (user) -> user.firstname.toLowerCase() == name return found if found.length == 1 # give up data # Redmine API Mapping # This isn't 100% complete, but its the basics for what we would need in campfire class Redmine constructor: (url, token) -> @url = url @token = token Users: (params, callback) -> @get "/users.json", params, callback User: (id) -> show: (callback) => @get "/users/#{id}.json", {}, callback Projects: (params, callback) -> @get "/projects.json", params, callback Issues: (params, callback) -> @get "/issues.json", params, callback Issue: (id) -> show: (params, callback) => @get "/issues/#{id}.json", params, callback update: (attributes, callback) => @put "/issues/#{id}.json", {issue: attributes}, callback TimeEntry: (id) -> create: (attributes, callback) => @post "/time_entries.json", {time_entry: attributes}, callback # Private: do a GET request against the API get: (path, params, callback) -> path = "#{path}?#{QUERY.stringify params}" if params? @request "GET", path, null, callback # Private: do a POST request against the API post: (path, body, callback) -> @request "POST", path, body, callback # Private: do a PUT request against the API put: (path, body, callback) -> @request "PUT", path, body, callback # Private: Perform a request against the redmine REST API # from the campfire adapter :) request: (method, path, body, callback) -> headers = "Content-Type": "application/json" "X-Redmine-API-Key": @token endpoint = URL.parse(@url) pathname = endpoint.pathname.replace /^\/$/, '' options = "host" : endpoint.hostname "path" : "#{pathname}#{path}" "method" : method "headers": headers if method in ["POST", "PUT"] if typeof(body) isnt "string" body = JSON.stringify body options.headers["Content-Length"] = body.length request = HTTP.request options, (response) -> data = "" response.on "data", (chunk) -> data += chunk response.on "end", -> switch response.statusCode when 200 try callback null, JSON.parse(data) catch err callback null, data or { } when 401 throw new Error "401: Authentication failed." else console.error "Code: #{response.statusCode}" callback response.statusCode, null response.on "error", (err) -> console.error "Redmine response error: #{err}" callback err, null if method in ["POST", "PUT"] request.end(body, 'binary') else request.end() request.on "error", (err) -> console.error "Redmine request error: #{err}" callback err, null
true
# Showing of redmine issuess via the REST API. # # (redmine|show) me <issue-id> - Show the issue status # show (my|user's) issues - Show your issues or another user's issues # assign <issue-id> to <user-first-name> ["notes"] - Assign the issue to the user (searches login or firstname) # *With optional notes # update <issue-id> with "<note>" - Adds a note to the issue # add <hours> hours to <issue-id> ["comments"] - Adds hours to the issue with the optional comments # Note: <issue-id> can be formatted in the following ways: # 1234, #1234, issue 1234, issue #1234 # #--- # # To get set up refer to the guide http://www.redmine.org/projects/redmine/wiki/Rest_api#Authentication # After that, heroku needs the following config # # heroku config:add HUBOT_REDMINE_BASE_URL="http://redmine.your-server.com" # heroku config:add HUBOT_REDMINE_TOKEN="your api token here" # # There may be issues if you have a lot of redmine users sharing a first name, but this can be avoided # by using redmine logins rather than firstnames # HTTP = require('http') URL = require('url') QUERY = require('querystring') module.exports = (robot) -> redmine = new Redmine process.env.HUBOT_REDMINE_BASE_URL, process.env.HUBOT_REDMINE_TOKEN # Robot add <hours> hours to <issue_id> ["comments for the time tracking"] robot.respond /add (\d{1,2}) hours? to (?:issue )?(?:#)?(\d+)(?: "?([^"]+)"?)?/i, (msg) -> [hours, id, userComments] = msg.match[1..3] if userComments? comments = "#{msg.message.user.name}: #{userComments}" else comments = "Time logged by: #{msg.message.user.name}" attributes = "issue_id": id "hours": hours "comments": comments redmine.TimeEntry(null).create attributes, (status,data) -> if status == 201 msg.reply "Your time was logged" else msg.reply "Nothing could be logged. Make sure RedMine has a default activity set for time tracking. (Settings -> Enumerations -> Activities)" # Robot show <my|user's> [redmine] issues robot.respond /show (?:my|(\w+\'s)) (?:redmine )?issues/i, (msg) -> userMode = true firstName = if msg.match[1]? userMode = false msg.match[1].replace(/\'.+/, '') else msg.message.user.name.split(/\s/)[0] redmine.Users name:firstName, (err,data) -> unless data.total_count > 0 msg.reply "Couldn't find any users with the name \"#{firstName}\"" return false user = resolveUsers(PI:NAME:<NAME>END_PI, data.users)[0] params = "assigned_to_id": user.id "limit": 25, "status_id": "open" "sort": "priority:desc", redmine.Issues params, (err, data) -> if err? msg.reply "Couldn't get a list of issues for you!" else _ = [] if userMode _.push "You have #{data.total_count} issue(s)." else _.push "#{user.firstname} has #{data.total_count} issue(s)." for issue in data.issues do (issue) -> _.push "\n[#{issue.tracker.name} - #{issue.priority.name} - #{issue.status.name}] ##{issue.id}: #{issue.subject}" msg.reply _.join "\n" # Robot update <issue> with "<note>" robot.respond /update (?:issue )?(?:#)?(\d+)(?:\s*with\s*)?(?:[-:,])? (?:"?([^"]+)"?)/i, (msg) -> [id, note] = msg.match[1..2] attributes = "notes": "#{msg.message.user.name}: #{note}" redmine.Issue(id).update attributes, (err, data) -> if err? if err == 404 msg.reply "Issue ##{id} doesn't exist." else msg.reply "Couldn't update this issue, sorry :(" else msg.reply "Done! Updated ##{id} with \"#{note}\"" # Robot assign <issue> to <user> ["note to add with the assignment] robot.respond /assign (?:issue )?(?:#)?(\d+) to (\w+)(?: "?([^"]+)"?)?/i, (msg) -> [id, userName, note] = msg.match[1..3] redmine.Users name:userName, (err, data) -> unless data.total_count > 0 msg.reply "Couldn't find any users with the name \"#{userName}\"" return false # try to resolve the user using login/firstname -- take the first result (hacky) user = resolveUsers(userName, data.users)[0] attributes = "assigned_to_id": user.id # allow an optional note with the re-assign attributes["notes"] = "#{msg.message.user.name}: #{note}" if note? # get our issue redmine.Issue(id).update attributes, (err, data) -> if err? if err == 404 msg.reply "Issue ##{id} doesn't exist." else msg.reply "There was an error assigning this issue." else msg.reply "Assigned ##{id} to #{user.firstname}." # Robot redmine me <issue> robot.respond /(?:redmine|show)(?: me)? (?:issue )?(?:#)?(\d+)/i, (msg) -> id = msg.match[1] params = "include": "journals" redmine.Issue(id).show params, (err, data) -> unless data? msg.reply "Issue ##{id} doesn't exist." return false issue = data.issue _ = [] _.push "\n[#{issue.project.name} - #{issue.priority.name}] #{issue.tracker.name} ##{issue.id} (#{issue.status.name})" _.push "Assigned: #{issue.assigned_to?.name ? 'Nobody'} (opened by #{issue.author.name})" if issue.status.name.toLowerCase() != 'new' _.push "Progress: #{issue.done_ratio}% (#{issue.spent_hours} hours)" _.push "Subject: #{issue.subject}" _.push "\n#{issue.description}" # journals _.push "\n" + Array(10).join('-') + '8<' + Array(50).join('-') + "\n" for journal in issue.journals do (journal) -> if journal.notes? and journal.notes != "" date = formatDate journal.created_on, 'mm/dd/yyyy (hh:ii ap)' _.push "#{journal.user.name} on #{date}:" _.push " #{journal.notes}\n" msg.reply _.join "\n" # simple ghetto fab date formatter this should definitely be replaced, but didn't want to # introduce dependencies this early # # dateStamp - any string that can initialize a date # fmt - format string that may use the following elements # mm - month # dd - day # yyyy - full year # hh - hours # ii - minutes # ss - seconds # ap - am / pm # # returns the formatted date formatDate = (dateStamp, fmt = 'mm/dd/yyyy at hh:ii ap') -> d = new Date(dateStamp) # split up the date [m,d,y,h,i,s,ap] = [d.getMonth() + 1, d.getDate(), d.getFullYear(), d.getHours(), d.getMinutes(), d.getSeconds(), 'AM'] # leadig 0s i = "0#{i}" if i < 10 s = "0#{s}" if s < 10 # adjust hours if h > 12 h = h - 12 ap = "PM" # ghetto fab! fmt .replace(/mm/, m) .replace(/dd/, d) .replace(/yyyy/, y) .replace(/hh/, h) .replace(/ii/, i) .replace(/ss/, s) .replace(/ap/, ap) # tries to resolve ambiguous users by matching login or firstname # redmine's user search is pretty broad (using login/name/email/etc.) so # we're trying to just pull it in a bit and get a single user # # name - this should be the name you're trying to match # data - this is the array of users from redmine # # returns an array with a single user, or the original array if nothing matched resolveUsers = (name, data) -> name = name.toLowerCase(); # try matching login found = data.filter (user) -> user.login.toLowerCase() == name return found if found.length == 1 # try first name found = data.filter (user) -> user.firstname.toLowerCase() == name return found if found.length == 1 # give up data # Redmine API Mapping # This isn't 100% complete, but its the basics for what we would need in campfire class Redmine constructor: (url, token) -> @url = url @token = token Users: (params, callback) -> @get "/users.json", params, callback User: (id) -> show: (callback) => @get "/users/#{id}.json", {}, callback Projects: (params, callback) -> @get "/projects.json", params, callback Issues: (params, callback) -> @get "/issues.json", params, callback Issue: (id) -> show: (params, callback) => @get "/issues/#{id}.json", params, callback update: (attributes, callback) => @put "/issues/#{id}.json", {issue: attributes}, callback TimeEntry: (id) -> create: (attributes, callback) => @post "/time_entries.json", {time_entry: attributes}, callback # Private: do a GET request against the API get: (path, params, callback) -> path = "#{path}?#{QUERY.stringify params}" if params? @request "GET", path, null, callback # Private: do a POST request against the API post: (path, body, callback) -> @request "POST", path, body, callback # Private: do a PUT request against the API put: (path, body, callback) -> @request "PUT", path, body, callback # Private: Perform a request against the redmine REST API # from the campfire adapter :) request: (method, path, body, callback) -> headers = "Content-Type": "application/json" "X-Redmine-API-Key": @token endpoint = URL.parse(@url) pathname = endpoint.pathname.replace /^\/$/, '' options = "host" : endpoint.hostname "path" : "#{pathname}#{path}" "method" : method "headers": headers if method in ["POST", "PUT"] if typeof(body) isnt "string" body = JSON.stringify body options.headers["Content-Length"] = body.length request = HTTP.request options, (response) -> data = "" response.on "data", (chunk) -> data += chunk response.on "end", -> switch response.statusCode when 200 try callback null, JSON.parse(data) catch err callback null, data or { } when 401 throw new Error "401: Authentication failed." else console.error "Code: #{response.statusCode}" callback response.statusCode, null response.on "error", (err) -> console.error "Redmine response error: #{err}" callback err, null if method in ["POST", "PUT"] request.end(body, 'binary') else request.end() request.on "error", (err) -> console.error "Redmine request error: #{err}" callback err, null
[ { "context": "tp://html2canvas.hertzen.com>\n Copyright (c) 2013 Niklas von Hertzen\n\n Released under MIT License\n###\n\n((window, docu", "end": 96, "score": 0.999899685382843, "start": 78, "tag": "NAME", "value": "Niklas von Hertzen" }, { "context": " from jQuery css.js\n # F...
lib/modules/helper/html2canvas.coffee
puranjayjain/chrome-color-picker
17
### html2canvas 0.4.1 <http://html2canvas.hertzen.com> Copyright (c) 2013 Niklas von Hertzen Released under MIT License ### ((window, document) -> # global variables borderSide = undefined toPX = (element, attribute, value) -> rsLeft = element.runtimeStyle and element.runtimeStyle[attribute] left = undefined style = element.style # Check if we are not dealing with pixels, (Opera has issues with this) # Ported from jQuery css.js # From the awesome hack by Dean Edwards # http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 # If we're not dealing with a regular pixel number # but a number that has a weird ending, we need to convert it to pixels if not /^-?[0-9]+\.?[0-9]*(?:px)?$/i.test(value) and /^-?\d/.test(value) # Remember the original values left = style.left # Put in the new values to get a computed value out if rsLeft element.runtimeStyle.left = element.currentStyle.left style.left = if attribute is 'fontSize' then '1em' else value or 0 value = style.pixelLeft + 'px' # Revert the changed values style.left = left if rsLeft element.runtimeStyle.left = rsLeft if not /^(thin|medium|thick)$/i.test(value) return Math.round(parseFloat(value)) + 'px' value asInt = (val) -> parseInt val, 10 parseBackgroundSizePosition = (value, element, attribute, index) -> value = (value or '').split(',') value = value[index or 0] or value[0] or 'auto' value = _html2canvas.Util.trimText(value).split(' ') if attribute is 'backgroundSize' and (not value[0] or value[0].match(/cover|contain|auto/)) #these values will be handled in the parent function else value[0] = if value[0].indexOf('%') is -1 then toPX(element, attribute + 'X', value[0]) else value[0] if value[1] is undefined if attribute is 'backgroundSize' value[1] = 'auto' return value else # IE 9 doesn't return double digit always value[1] = value[0] value[1] = if value[1].indexOf('%') is -1 then toPX(element, attribute + 'Y', value[1]) else value[1] value backgroundBoundsFactory = (prop, el, bounds, image, imageIndex, backgroundSize) -> bgposition = _html2canvas.Util.getCSS(el, prop, imageIndex) topPos = undefined left = undefined percentage = undefined val = undefined if bgposition.length is 1 val = bgposition[0] bgposition = [] bgposition[0] = val bgposition[1] = val if bgposition[0].toString().indexOf('%') isnt -1 percentage = parseFloat(bgposition[0]) / 100 left = bounds.width * percentage if prop isnt 'backgroundSize' left -= (backgroundSize or image).width * percentage else if prop is 'backgroundSize' if bgposition[0] is 'auto' left = image.width else if /contain|cover/.test(bgposition[0]) resized = _html2canvas.Util.resizeBounds(image.width, image.height, bounds.width, bounds.height, bgposition[0]) left = resized.width topPos = resized.height else left = parseInt(bgposition[0], 10) else left = parseInt(bgposition[0], 10) if bgposition[1] is 'auto' topPos = left / image.width * image.height else if bgposition[1].toString().indexOf('%') isnt -1 percentage = parseFloat(bgposition[1]) / 100 topPos = bounds.height * percentage if prop isnt 'backgroundSize' topPos -= (backgroundSize or image).height * percentage else topPos = parseInt(bgposition[1], 10) [ left topPos ] h2cRenderContext = (width, height) -> storage = [] { storage: storage width: width height: height clip: -> storage.push type: 'function' name: 'clip' 'arguments': arguments return translate: -> storage.push type: 'function' name: 'translate' 'arguments': arguments return fill: -> storage.push type: 'function' name: 'fill' 'arguments': arguments return save: -> storage.push type: 'function' name: 'save' 'arguments': arguments return restore: -> storage.push type: 'function' name: 'restore' 'arguments': arguments return fillRect: -> storage.push type: 'function' name: 'fillRect' 'arguments': arguments return createPattern: -> storage.push type: 'function' name: 'createPattern' 'arguments': arguments return drawShape: -> shape = [] storage.push type: 'function' name: 'drawShape' 'arguments': shape { moveTo: -> shape.push name: 'moveTo' 'arguments': arguments return lineTo: -> shape.push name: 'lineTo' 'arguments': arguments return arcTo: -> shape.push name: 'arcTo' 'arguments': arguments return bezierCurveTo: -> shape.push name: 'bezierCurveTo' 'arguments': arguments return quadraticCurveTo: -> shape.push name: 'quadraticCurveTo' 'arguments': arguments return } drawImage: -> storage.push type: 'function' name: 'drawImage' 'arguments': arguments return fillText: -> storage.push type: 'function' name: 'fillText' 'arguments': arguments return setVariable: (variable, value) -> storage.push type: 'variable' name: variable 'arguments': value value } h2czContext = (zindex) -> { zindex: zindex children: [] } 'use strict' _html2canvas = {} previousElement = undefined computedCSS = undefined html2canvas = undefined _html2canvas.Util = {} _html2canvas.Util.log = (a) -> if _html2canvas.logging and window.console and window.console.log window.console.log a return _html2canvas.Util.trimText = ((isNative) -> (input) -> if isNative then isNative.apply(input) else ((input or '') + '').replace(/^\s+|\s+$/g, '') )(String::trim) _html2canvas.Util.asFloat = (v) -> parseFloat v do -> # TODO: support all possible length values TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g _html2canvas.Util.parseTextShadows = (value) -> if not value or value is 'none' return [] # find multiple shadow declarations shadows = value.match(TEXT_SHADOW_PROPERTY) results = [] i = 0 while shadows and i < shadows.length s = shadows[i].match(TEXT_SHADOW_VALUES) results.push color: s[0] offsetX: if s[1] then s[1].replace('px', '') else 0 offsetY: if s[2] then s[2].replace('px', '') else 0 blur: if s[3] then s[3].replace('px', '') else 0 i++ results return _html2canvas.Util.parseBackgroundImage = (value) -> whitespace = ' \u000d\n\u0009' method = undefined definition = undefined prefix = undefined prefix_i = undefined block = undefined results = [] c = undefined mode = 0 numParen = 0 quote = undefined args = undefined appendResult = -> if method if definition.substr(0, 1) is '"' definition = definition.substr(1, definition.length - 2) if definition args.push definition if method.substr(0, 1) is '-' and (prefix_i = method.indexOf('-', 1) + 1) > 0 prefix = method.substr(0, prefix_i) method = method.substr(prefix_i) results.push prefix: prefix method: method.toLowerCase() value: block args: args args = [] #for some odd reason, setting .length = 0 didn't work in safari method = prefix = definition = block = '' return appendResult() i = 0 ii = value.length while i < ii c = value[i] if mode is 0 and whitespace.indexOf(c) > -1 i++ continue switch c when '"' if not quote quote = c else if quote is c quote = null when '(' if quote break else if mode is 0 mode = 1 block += c i++ continue else numParen++ when ')' if quote break else if mode is 1 if numParen is 0 mode = 0 block += c appendResult() i++ continue else numParen-- when ',' if quote break else if mode is 0 appendResult() i++ continue else if mode is 1 if numParen is 0 and not method.match(/^url$/i) args.push definition definition = '' block += c i++ continue block += c if mode is 0 method += c else definition += c i++ appendResult() results _html2canvas.Util.Bounds = (element) -> clientRect = undefined bounds = {} if element.getBoundingClientRect clientRect = element.getBoundingClientRect() # TODO add scroll position to bounds, so no scrolling of window necessary bounds.top = clientRect.top bounds.bottom = clientRect.bottom or clientRect.top + clientRect.height bounds.left = clientRect.left bounds.width = element.offsetWidth bounds.height = element.offsetHeight bounds # TODO ideally, we'd want everything to go through this function instead of Util.Bounds, # but would require further work to calculate the correct positions for elements with offsetParents _html2canvas.Util.OffsetBounds = (element) -> parent = if element.offsetParent then _html2canvas.Util.OffsetBounds(element.offsetParent) else top: 0 left: 0 { top: element.offsetTop + parent.top bottom: element.offsetTop + element.offsetHeight + parent.top left: element.offsetLeft + parent.left width: element.offsetWidth height: element.offsetHeight } _html2canvas.Util.getCSS = (element, attribute, index) -> if previousElement isnt element computedCSS = document.defaultView.getComputedStyle(element, null) value = computedCSS[attribute] if /^background(Size|Position)$/.test(attribute) return parseBackgroundSizePosition(value, element, attribute, index) else if /border(Top|Bottom)(Left|Right)Radius/.test(attribute) arr = value.split(' ') if arr.length <= 1 arr[1] = arr[0] return arr.map(asInt) value _html2canvas.Util.resizeBounds = (current_width, current_height, target_width, target_height, stretch_mode) -> target_ratio = target_width / target_height current_ratio = current_width / current_height output_width = undefined output_height = undefined if not stretch_mode or stretch_mode is 'auto' output_width = target_width output_height = target_height else if target_ratio < current_ratio ^ stretch_mode is 'contain' output_height = target_height output_width = target_height * current_ratio else output_width = target_width output_height = target_width / current_ratio { width: output_width height: output_height } _html2canvas.Util.BackgroundPosition = (el, bounds, image, imageIndex, backgroundSize) -> result = backgroundBoundsFactory('backgroundPosition', el, bounds, image, imageIndex, backgroundSize) { left: result[0] top: result[1] } _html2canvas.Util.BackgroundSize = (el, bounds, image, imageIndex) -> result = backgroundBoundsFactory('backgroundSize', el, bounds, image, imageIndex) { width: result[0] height: result[1] } _html2canvas.Util.Extend = (options, defaults) -> for key of options if options.hasOwnProperty(key) defaults[key] = options[key] defaults ### # Derived from jQuery.contents() # Copyright 2010, John Resig # Dual licensed under the MIT or GPL Version 2 licenses. # http://jquery.org/license ### _html2canvas.Util.Children = (elem) -> children = undefined try children = if elem.nodeName and elem.nodeName.toUpperCase() is 'IFRAME' then elem.contentDocument or elem.contentWindow.document else ((array) -> ret = [] if array isnt null ((first, second) -> i = first.length j = 0 if typeof second.length is 'number' l = second.length while j < l first[i++] = second[j] j++ else while second[j] isnt undefined first[i++] = second[j++] first.length = i first ) ret, array ret )(elem.childNodes) catch ex _html2canvas.Util.log 'html2canvas.Util.Children failed with exception: ' + ex.message children = [] children _html2canvas.Util.isTransparent = (backgroundColor) -> backgroundColor is 'transparent' or backgroundColor is 'rgba(0, 0, 0, 0)' _html2canvas.Util.Font = do -> fontData = {} (font, fontSize, doc) -> if fontData[font + '-' + fontSize] isnt undefined return fontData[font + '-' + fontSize] container = doc.createElement('div') img = doc.createElement('img') span = doc.createElement('span') sampleText = 'Hidden Text' baseline = undefined middle = undefined metricsObj = undefined container.style.visibility = 'hidden' container.style.fontFamily = font container.style.fontSize = fontSize container.style.margin = 0 container.style.padding = 0 doc.body.appendChild container # http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever (handtinywhite.gif) img.src = 'data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACwAAAAAAQABAAACAkQBADs=' img.width = 1 img.height = 1 img.style.margin = 0 img.style.padding = 0 img.style.verticalAlign = 'baseline' span.style.fontFamily = font span.style.fontSize = fontSize span.style.margin = 0 span.style.padding = 0 span.appendChild doc.createTextNode(sampleText) container.appendChild span container.appendChild img baseline = img.offsetTop - (span.offsetTop) + 1 container.removeChild span container.appendChild doc.createTextNode(sampleText) container.style.lineHeight = 'normal' img.style.verticalAlign = 'super' middle = img.offsetTop - (container.offsetTop) + 1 metricsObj = baseline: baseline lineWidth: 1 middle: middle fontData[font + '-' + fontSize] = metricsObj doc.body.removeChild container metricsObj do -> Util = _html2canvas.Util Generate = {} addScrollStops = (grad) -> (colorStop) -> try grad.addColorStop colorStop.stop, colorStop.color catch e Util.log [ 'failed to add color stop: ' e '; tried to add: ' colorStop ] return _html2canvas.Generate = Generate reGradients = [ /^(-webkit-linear-gradient)\(([a-z\s]+)([\w\d\.\s,%\(\)]+)\)$/ /^(-o-linear-gradient)\(([a-z\s]+)([\w\d\.\s,%\(\)]+)\)$/ /^(-webkit-gradient)\((linear|radial),\s((?:\d{1,3}%?)\s(?:\d{1,3}%?),\s(?:\d{1,3}%?)\s(?:\d{1,3}%?))([\w\d\.\s,%\(\)\-]+)\)$/ /^(-moz-linear-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?))([\w\d\.\s,%\(\)]+)\)$/ /^(-webkit-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s([a-z\-]+)([\w\d\.\s,%\(\)]+)\)$/ /^(-moz-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s?([a-z\-]*)([\w\d\.\s,%\(\)]+)\)$/ /^(-o-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s([a-z\-]+)([\w\d\.\s,%\(\)]+)\)$/ ] ### # TODO: Add IE10 vendor prefix (-ms) support # TODO: Add W3C gradient (linear-gradient) support # TODO: Add old Webkit -webkit-gradient(radial, ...) support # TODO: Maybe some RegExp optimizations are possible ;o) ### Generate.parseGradient = (css, bounds) -> gradient = undefined i = undefined len = reGradients.length m1 = undefined stop = undefined m2 = undefined m2Len = undefined step = undefined m3 = undefined tl = undefined tr = undefined br = undefined bl = undefined i = 0 while i < len m1 = css.match(reGradients[i]) if m1 break i += 1 if m1 switch m1[1] when '-webkit-linear-gradient', '-o-linear-gradient' gradient = type: 'linear' x0: null y0: null x1: null y1: null colorStops: [] # get coordinates m2 = m1[2].match(/\w+/g) if m2 m2Len = m2.length i = 0 while i < m2Len switch m2[i] when 'top' gradient.y0 = 0 gradient.y1 = bounds.height when 'right' gradient.x0 = bounds.width gradient.x1 = 0 when 'bottom' gradient.y0 = bounds.height gradient.y1 = 0 when 'left' gradient.x0 = 0 gradient.x1 = bounds.width i += 1 if gradient.x0 is null and gradient.x1 is null # center gradient.x0 = gradient.x1 = bounds.width / 2 if gradient.y0 is null and gradient.y1 is null # center gradient.y0 = gradient.y1 = bounds.height / 2 # get colors and stops m2 = m1[3].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}(?:%|px))?)+/g) if m2 m2Len = m2.length step = 1 / Math.max(m2Len - 1, 1) i = 0 while i < m2Len m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/) if m3[2] stop = parseFloat(m3[2]) if m3[3] is '%' stop /= 100 else # px - stupid opera stop /= bounds.width else stop = i * step gradient.colorStops.push color: m3[1] stop: stop i += 1 when '-webkit-gradient' gradient = type: if m1[2] is 'radial' then 'circle' else m1[2] x0: 0 y0: 0 x1: 0 y1: 0 colorStops: [] # get coordinates m2 = m1[3].match(/(\d{1,3})%?\s(\d{1,3})%?,\s(\d{1,3})%?\s(\d{1,3})%?/) if m2 gradient.x0 = m2[1] * bounds.width / 100 gradient.y0 = m2[2] * bounds.height / 100 gradient.x1 = m2[3] * bounds.width / 100 gradient.y1 = m2[4] * bounds.height / 100 # get colors and stops m2 = m1[4].match(/((?:from|to|color-stop)\((?:[0-9\.]+,\s)?(?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)\))+/g) if m2 m2Len = m2.length i = 0 while i < m2Len m3 = m2[i].match(/(from|to|color-stop)\(([0-9\.]+)?(?:,\s)?((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\)/) stop = parseFloat(m3[2]) if m3[1] is 'from' stop = 0.0 if m3[1] is 'to' stop = 1.0 gradient.colorStops.push color: m3[3] stop: stop i += 1 when '-moz-linear-gradient' gradient = type: 'linear' x0: 0 y0: 0 x1: 0 y1: 0 colorStops: [] # get coordinates m2 = m1[2].match(/(\d{1,3})%?\s(\d{1,3})%?/) # m2[1] is 0% -> left # m2[1] is 50% -> center # m2[1] is 100% -> right # m2[2] is 0% -> top # m2[2] is 50% -> center # m2[2] is 100% -> bottom if m2 gradient.x0 = m2[1] * bounds.width / 100 gradient.y0 = m2[2] * bounds.height / 100 gradient.x1 = bounds.width - (gradient.x0) gradient.y1 = bounds.height - (gradient.y0) # get colors and stops m2 = m1[3].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}%)?)+/g) if m2 m2Len = m2.length step = 1 / Math.max(m2Len - 1, 1) i = 0 while i < m2Len m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%)?/) if m3[2] stop = parseFloat(m3[2]) if m3[3] # percentage stop /= 100 else stop = i * step gradient.colorStops.push color: m3[1] stop: stop i += 1 when '-webkit-radial-gradient', '-moz-radial-gradient', '-o-radial-gradient' gradient = type: 'circle' x0: 0 y0: 0 x1: bounds.width y1: bounds.height cx: 0 cy: 0 rx: 0 ry: 0 colorStops: [] # center m2 = m1[2].match(/(\d{1,3})%?\s(\d{1,3})%?/) if m2 gradient.cx = m2[1] * bounds.width / 100 gradient.cy = m2[2] * bounds.height / 100 # size m2 = m1[3].match(/\w+/) m3 = m1[4].match(/[a-z\-]*/) if m2 and m3 switch m3[0] # is equivalent to farthest-corner when 'farthest-corner', 'cover', '' # mozilla removes "cover" from definition :( tl = Math.sqrt(gradient.cx ** 2 + gradient.cy ** 2) tr = Math.sqrt(gradient.cx ** 2 + (gradient.y1 - (gradient.cy)) ** 2) br = Math.sqrt((gradient.x1 - (gradient.cx)) ** 2 + (gradient.y1 - (gradient.cy)) ** 2) bl = Math.sqrt((gradient.x1 - (gradient.cx)) ** 2 + gradient.cy ** 2) gradient.rx = gradient.ry = Math.max(tl, tr, br, bl) when 'closest-corner' tl = Math.sqrt(gradient.cx ** 2 + gradient.cy ** 2) tr = Math.sqrt(gradient.cx ** 2 + (gradient.y1 - (gradient.cy)) ** 2) br = Math.sqrt((gradient.x1 - (gradient.cx)) ** 2 + (gradient.y1 - (gradient.cy)) ** 2) bl = Math.sqrt((gradient.x1 - (gradient.cx)) ** 2 + gradient.cy ** 2) gradient.rx = gradient.ry = Math.min(tl, tr, br, bl) when 'farthest-side' if m2[0] is 'circle' gradient.rx = gradient.ry = Math.max(gradient.cx, gradient.cy, gradient.x1 - (gradient.cx), gradient.y1 - (gradient.cy)) else # ellipse gradient.type = m2[0] gradient.rx = Math.max(gradient.cx, gradient.x1 - (gradient.cx)) gradient.ry = Math.max(gradient.cy, gradient.y1 - (gradient.cy)) when 'closest-side', 'contain' # is equivalent to closest-side if m2[0] is 'circle' gradient.rx = gradient.ry = Math.min(gradient.cx, gradient.cy, gradient.x1 - (gradient.cx), gradient.y1 - (gradient.cy)) else # ellipse gradient.type = m2[0] gradient.rx = Math.min(gradient.cx, gradient.x1 - (gradient.cx)) gradient.ry = Math.min(gradient.cy, gradient.y1 - (gradient.cy)) # TODO: add support for "30px 40px" sizes (webkit only) # color stops m2 = m1[5].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}(?:%|px))?)+/g) if m2 m2Len = m2.length step = 1 / Math.max(m2Len - 1, 1) i = 0 while i < m2Len m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/) if m3[2] stop = parseFloat(m3[2]) if m3[3] is '%' stop /= 100 else # px - stupid opera stop /= bounds.width else stop = i * step gradient.colorStops.push color: m3[1] stop: stop i += 1 gradient Generate.Gradient = (src, bounds) -> if bounds.width is 0 or bounds.height is 0 return canvas = document.createElement('canvas') ctx = canvas.getContext('2d') gradient = undefined grad = undefined canvas.width = bounds.width canvas.height = bounds.height # TODO: add support for multi defined background gradients gradient = _html2canvas.Generate.parseGradient(src, bounds) if gradient switch gradient.type when 'linear' grad = ctx.createLinearGradient(gradient.x0, gradient.y0, gradient.x1, gradient.y1) gradient.colorStops.forEach addScrollStops(grad) ctx.fillStyle = grad ctx.fillRect 0, 0, bounds.width, bounds.height when 'circle' grad = ctx.createRadialGradient(gradient.cx, gradient.cy, 0, gradient.cx, gradient.cy, gradient.rx) gradient.colorStops.forEach addScrollStops(grad) ctx.fillStyle = grad ctx.fillRect 0, 0, bounds.width, bounds.height when 'ellipse' canvasRadial = document.createElement('canvas') ctxRadial = canvasRadial.getContext('2d') ri = Math.max(gradient.rx, gradient.ry) di = ri * 2 canvasRadial.width = canvasRadial.height = di grad = ctxRadial.createRadialGradient(gradient.rx, gradient.ry, 0, gradient.rx, gradient.ry, ri) gradient.colorStops.forEach addScrollStops(grad) ctxRadial.fillStyle = grad ctxRadial.fillRect 0, 0, di, di ctx.fillStyle = gradient.colorStops[gradient.colorStops.length - 1].color ctx.fillRect 0, 0, canvas.width, canvas.height ctx.drawImage canvasRadial, gradient.cx - (gradient.rx), gradient.cy - (gradient.ry), 2 * gradient.rx, 2 * gradient.ry canvas Generate.ListAlpha = (number) -> tmp = '' modulus = undefined loop modulus = number % 26 tmp = String.fromCharCode(modulus + 64) + tmp number = number / 26 unless number * 26 > 26 break tmp Generate.ListRoman = (number) -> romanArray = [ 'M' 'CM' 'D' 'CD' 'C' 'XC' 'L' 'XL' 'X' 'IX' 'V' 'IV' 'I' ] decimal = [ 1000 900 500 400 100 90 50 40 10 9 5 4 1 ] roman = '' v = undefined len = romanArray.length if number <= 0 or number >= 4000 return number v = 0 while v < len while number >= decimal[v] number -= decimal[v] roman += romanArray[v] v += 1 roman return _html2canvas.Parse = (images, options) -> documentWidth = -> Math.max Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth), Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth), Math.max(doc.body.clientWidth, doc.documentElement.clientWidth) documentHeight = -> Math.max Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight), Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight), Math.max(doc.body.clientHeight, doc.documentElement.clientHeight) getCSSInt = (element, attribute) -> val = parseInt(getCSS(element, attribute), 10) if isNaN(val) then 0 else val # borders in old IE are throwing 'medium' for demo.html renderRect = (ctx, x, y, w, h, bgcolor) -> if bgcolor isnt 'transparent' ctx.setVariable 'fillStyle', bgcolor ctx.fillRect x, y, w, h numDraws += 1 return capitalize = (m, p1, p2) -> if m.length > 0 return p1 + p2.toUpperCase() return textTransform = (text, transform) -> switch transform when 'lowercase' return text.toLowerCase() when 'capitalize' return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize) when 'uppercase' return text.toUpperCase() else return text return noLetterSpacing = (letter_spacing) -> /^(normal|none|0px)$/.test letter_spacing drawText = (currentText, x, y, ctx) -> if currentText isnt null and Util.trimText(currentText).length > 0 ctx.fillText currentText, x, y numDraws += 1 return setTextVariables = (ctx, el, text_decoration, color) -> align = false bold = getCSS(el, 'fontWeight') family = getCSS(el, 'fontFamily') size = getCSS(el, 'fontSize') shadows = Util.parseTextShadows(getCSS(el, 'textShadow')) switch parseInt(bold, 10) when 401 bold = 'bold' when 400 bold = 'normal' ctx.setVariable 'fillStyle', color ctx.setVariable 'font', [ getCSS(el, 'fontStyle') getCSS(el, 'fontVariant') bold size family ].join(' ') ctx.setVariable 'textAlign', if align then 'right' else 'left' if shadows.length # TODO: support multiple text shadows # apply the first text shadow ctx.setVariable 'shadowColor', shadows[0].color ctx.setVariable 'shadowOffsetX', shadows[0].offsetX ctx.setVariable 'shadowOffsetY', shadows[0].offsetY ctx.setVariable 'shadowBlur', shadows[0].blur if text_decoration isnt 'none' return Util.Font(family, size, doc) return renderTextDecoration = (ctx, text_decoration, bounds, metrics, color) -> switch text_decoration when 'underline' # Draws a line at the baseline of the font # TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size renderRect ctx, bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, color when 'overline' renderRect ctx, bounds.left, Math.round(bounds.top), bounds.width, 1, color when 'line-through' # TODO try and find exact position for line-through renderRect ctx, bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, color return getTextBounds = (state, text, textDecoration, isLast, transform) -> bounds = undefined if support.rangeBounds and not transform if textDecoration isnt 'none' or Util.trimText(text).length isnt 0 bounds = textRangeBounds(text, state.node, state.textOffset) state.textOffset += text.length else if state.node and typeof state.node.nodeValue is 'string' newTextNode = if isLast then state.node.splitText(text.length) else null bounds = textWrapperBounds(state.node, transform) state.node = newTextNode bounds textRangeBounds = (text, textNode, textOffset) -> range = doc.createRange() range.setStart textNode, textOffset range.setEnd textNode, textOffset + text.length range.getBoundingClientRect() textWrapperBounds = (oldTextNode, transform) -> parent = oldTextNode.parentNode wrapElement = doc.createElement('wrapper') backupText = oldTextNode.cloneNode(true) wrapElement.appendChild oldTextNode.cloneNode(true) parent.replaceChild wrapElement, oldTextNode bounds = if transform then Util.OffsetBounds(wrapElement) else Util.Bounds(wrapElement) parent.replaceChild backupText, wrapElement bounds renderText = (el, textNode, stack) -> ctx = stack.ctx color = getCSS(el, 'color') textDecoration = getCSS(el, 'textDecoration') textAlign = getCSS(el, 'textAlign') metrics = undefined textList = undefined state = node: textNode textOffset: 0 if Util.trimText(textNode.nodeValue).length > 0 textNode.nodeValue = textTransform(textNode.nodeValue, getCSS(el, 'textTransform')) textAlign = textAlign.replace([ '-webkit-auto' ], [ 'auto' ]) textList = if not options.letterRendering and /^(left|right|justify|auto)$/.test(textAlign) and noLetterSpacing(getCSS(el, 'letterSpacing')) then textNode.nodeValue.split(/(\b| )/) else textNode.nodeValue.split('') metrics = setTextVariables(ctx, el, textDecoration, color) if options.chinese textList.forEach (word, index) -> if /.*[\u4E00-\u9FA5].*$/.test(word) word = word.split('') word.unshift index, 1 textList.splice.apply textList, word return textList.forEach (text, index) -> bounds = getTextBounds(state, text, textDecoration, index < textList.length - 1, stack.transform.matrix) if bounds drawText text, bounds.left, bounds.bottom, ctx renderTextDecoration ctx, textDecoration, bounds, metrics, color return return listPosition = (element, val) -> boundElement = doc.createElement('boundelement') originalType = undefined bounds = undefined boundElement.style.display = 'inline' originalType = element.style.listStyleType element.style.listStyleType = 'none' boundElement.appendChild doc.createTextNode(val) element.insertBefore boundElement, element.firstChild bounds = Util.Bounds(boundElement) element.removeChild boundElement element.style.listStyleType = originalType bounds elementIndex = (el) -> i = -1 count = 1 childs = el.parentNode.childNodes if el.parentNode while childs[++i] isnt el if childs[i].nodeType is 1 count++ count else -1 listItemText = (element, type) -> currentIndex = elementIndex(element) text = undefined switch type when 'decimal' text = currentIndex when 'decimal-leading-zero' text = if currentIndex.toString().length is 1 then (currentIndex = '0' + currentIndex.toString()) else currentIndex.toString() when 'upper-roman' text = _html2canvas.Generate.ListRoman(currentIndex) when 'lower-roman' text = _html2canvas.Generate.ListRoman(currentIndex).toLowerCase() when 'lower-alpha' text = _html2canvas.Generate.ListAlpha(currentIndex).toLowerCase() when 'upper-alpha' text = _html2canvas.Generate.ListAlpha(currentIndex) text + '. ' renderListItem = (element, stack, elBounds) -> x = undefined text = undefined ctx = stack.ctx type = getCSS(element, 'listStyleType') listBounds = undefined if /^(decimal|decimal-leading-zero|upper-alpha|upper-latin|upper-roman|lower-alpha|lower-greek|lower-latin|lower-roman)$/i.test(type) text = listItemText(element, type) listBounds = listPosition(element, text) setTextVariables ctx, element, 'none', getCSS(element, 'color') if getCSS(element, 'listStylePosition') is 'inside' ctx.setVariable 'textAlign', 'left' x = elBounds.left else return drawText text, x, listBounds.bottom, ctx return loadImage = (src) -> img = images[src] if img and img.succeeded is true then img.img else false clipBounds = (src, dst) -> x = Math.max(src.left, dst.left) y = Math.max(src.top, dst.top) x2 = Math.min(src.left + src.width, dst.left + dst.width) y2 = Math.min(src.top + src.height, dst.top + dst.height) { left: x top: y width: x2 - x height: y2 - y } setZ = (element, stack, parentStack) -> newContext = undefined isPositioned = stack.cssPosition isnt 'static' zIndex = if isPositioned then getCSS(element, 'zIndex') else 'auto' opacity = getCSS(element, 'opacity') isFloated = getCSS(element, 'cssFloat') isnt 'none' # https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context # When a new stacking context should be created: # the root element (HTML), # positioned (absolutely or relatively) with a z-index value other than "auto", # elements with an opacity value less than 1. (See the specification for opacity), # on mobile WebKit and Chrome 22+, position: fixed always creates a new stacking context, even when z-index is "auto" (See this post) stack.zIndex = newContext = h2czContext(zIndex) newContext.isPositioned = isPositioned newContext.isFloated = isFloated newContext.opacity = opacity newContext.ownStacking = zIndex isnt 'auto' or opacity < 1 if parentStack parentStack.zIndex.children.push stack return renderImage = (ctx, element, image, bounds, borders) -> paddingLeft = getCSSInt(element, 'paddingLeft') paddingTop = getCSSInt(element, 'paddingTop') paddingRight = getCSSInt(element, 'paddingRight') paddingBottom = getCSSInt(element, 'paddingBottom') bLeft = bounds.left + paddingLeft + borders[3].width bTop = bounds.top + paddingTop + borders[0].width bWidth = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight) drawImage ctx, image, 0, 0, image.width, image.height, bLeft, bTop, bWidth, bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom) return getBorderData = (element) -> [ 'Top' 'Right' 'Bottom' 'Left' ].map (side) -> { width: getCSSInt(element, 'border' + side + 'Width') color: getCSS(element, 'border' + side + 'Color') } getBorderRadiusData = (element) -> [ 'TopLeft' 'TopRight' 'BottomRight' 'BottomLeft' ].map (side) -> getCSS element, 'border' + side + 'Radius' bezierCurve = (start, startControl, endControl, end) -> lerp = (a, b, t) -> { x: a.x + (b.x - (a.x)) * t y: a.y + (b.y - (a.y)) * t } { start: start startControl: startControl endControl: endControl end: end subdivide: (t) -> ab = lerp(start, startControl, t) bc = lerp(startControl, endControl, t) cd = lerp(endControl, end, t) abbc = lerp(ab, bc, t) bccd = lerp(bc, cd, t) dest = lerp(abbc, bccd, t) [ bezierCurve(start, ab, abbc, dest) bezierCurve(dest, bccd, cd, end) ] curveTo: (borderArgs) -> borderArgs.push [ 'bezierCurve' startControl.x startControl.y endControl.x endControl.y end.x end.y ] return curveToReversed: (borderArgs) -> borderArgs.push [ 'bezierCurve' endControl.x endControl.y startControl.x startControl.y start.x start.y ] return } parseCorner = (borderArgs, radius1, radius2, corner1, corner2, x, y) -> if radius1[0] > 0 or radius1[1] > 0 borderArgs.push [ 'line' corner1[0].start.x corner1[0].start.y ] corner1[0].curveTo borderArgs corner1[1].curveTo borderArgs else borderArgs.push [ 'line' x y ] if radius2[0] > 0 or radius2[1] > 0 borderArgs.push [ 'line' corner2[0].start.x corner2[0].start.y ] return drawSide = (borderData, radius1, radius2, outer1, inner1, outer2, inner2) -> borderArgs = [] if radius1[0] > 0 or radius1[1] > 0 borderArgs.push [ 'line' outer1[1].start.x outer1[1].start.y ] outer1[1].curveTo borderArgs else borderArgs.push [ 'line' borderData.c1[0] borderData.c1[1] ] if radius2[0] > 0 or radius2[1] > 0 borderArgs.push [ 'line' outer2[0].start.x outer2[0].start.y ] outer2[0].curveTo borderArgs borderArgs.push [ 'line' inner2[0].end.x inner2[0].end.y ] inner2[0].curveToReversed borderArgs else borderArgs.push [ 'line' borderData.c2[0] borderData.c2[1] ] borderArgs.push [ 'line' borderData.c3[0] borderData.c3[1] ] if radius1[0] > 0 or radius1[1] > 0 borderArgs.push [ 'line' inner1[1].end.x inner1[1].end.y ] inner1[1].curveToReversed borderArgs else borderArgs.push [ 'line' borderData.c4[0] borderData.c4[1] ] borderArgs calculateCurvePoints = (bounds, borderRadius, borders) -> x = bounds.left y = bounds.top width = bounds.width height = bounds.height tlh = borderRadius[0][0] tlv = borderRadius[0][1] trh = borderRadius[1][0] trv = borderRadius[1][1] brh = borderRadius[2][0] brv = borderRadius[2][1] blh = borderRadius[3][0] blv = borderRadius[3][1] topWidth = width - trh rightHeight = height - brv bottomWidth = width - brh leftHeight = height - blv { topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5) topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - (borders[3].width)), Math.max(0, tlv - (borders[0].width))).topLeft.subdivide(0.5) topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5) topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (if topWidth > width + borders[3].width then 0 else trh - (borders[3].width)), trv - (borders[0].width)).topRight.subdivide(0.5) bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5) bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width + borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - (borders[1].width)), Math.max(0, brv - (borders[2].width))).bottomRight.subdivide(0.5) bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5) bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - (borders[3].width)), Math.max(0, blv - (borders[2].width))).bottomLeft.subdivide(0.5) } getBorderClip = (element, borderPoints, borders, radius, bounds) -> backgroundClip = getCSS(element, 'backgroundClip') borderArgs = [] switch backgroundClip when 'content-box', 'padding-box' parseCorner borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width parseCorner borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - (borders[1].width), bounds.top + borders[0].width parseCorner borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - (borders[1].width), bounds.top + bounds.height - (borders[2].width) parseCorner borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - (borders[2].width) else parseCorner borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top parseCorner borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top parseCorner borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height parseCorner borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height break borderArgs parseBorders = (element, bounds, borders) -> x = bounds.left y = bounds.top width = bounds.width height = bounds.height borderSide = undefined bx = undefined borderY = undefined bw = undefined bh = undefined borderArgs = undefined borderRadius = getBorderRadiusData(element) borderPoints = calculateCurvePoints(bounds, borderRadius, borders) borderData = clip: getBorderClip(element, borderPoints, borders, borderRadius, bounds) borders: [] borderSide = 0 while borderSide < 4 if borders[borderSide].width > 0 bx = x borderY = y bw = width bh = height - (borders[2].width) switch borderSide when 0 # top border bh = borders[0].width borderArgs = drawSide({ c1: [ bx borderY ] c2: [ bx + bw borderY ] c3: [ bx + bw - (borders[1].width) borderY + bh ] c4: [ bx + borders[3].width borderY + bh ] }, borderRadius[0], borderRadius[1], borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner) when 1 # right border bx = x + width - (borders[1].width) bw = borders[1].width borderArgs = drawSide({ c1: [ bx + bw borderY ] c2: [ bx + bw borderY + bh + borders[2].width ] c3: [ bx borderY + bh ] c4: [ bx borderY + borders[0].width ] }, borderRadius[1], borderRadius[2], borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner) when 2 # bottom border borderY = borderY + height - (borders[2].width) bh = borders[2].width borderArgs = drawSide({ c1: [ bx + bw borderY + bh ] c2: [ bx borderY + bh ] c3: [ bx + borders[3].width borderY ] c4: [ bx + bw - (borders[3].width) borderY ] }, borderRadius[2], borderRadius[3], borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner) when 3 # left border bw = borders[3].width borderArgs = drawSide({ c1: [ bx borderY + bh + borders[2].width ] c2: [ bx borderY ] c3: [ bx + bw borderY + borders[0].width ] c4: [ bx + bw borderY + bh ] }, borderRadius[3], borderRadius[0], borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner) borderData.borders.push args: borderArgs color: borders[borderSide].color borderSide++ borderData createShape = (ctx, args) -> shape = ctx.drawShape() args.forEach (border, index) -> shape[if index is 0 then 'moveTo' else border[0] + 'To'].apply null, border.slice(1) return shape renderBorders = (ctx, borderArgs, color) -> if color isnt 'transparent' ctx.setVariable 'fillStyle', color createShape ctx, borderArgs ctx.fill() numDraws += 1 return renderFormValue = (el, bounds, stack) -> valueWrap = doc.createElement('valuewrap') cssPropertyArray = [ 'lineHeight' 'textAlign' 'fontFamily' 'color' 'fontSize' 'paddingLeft' 'paddingTop' 'width' 'height' 'border' 'borderLeftWidth' 'borderTopWidth' ] textValue = undefined textNode = undefined cssPropertyArray.forEach (property) -> try valueWrap.style[property] = getCSS(el, property) catch e # Older IE has issues with "border" Util.log 'html2canvas: Parse: Exception caught in renderFormValue: ' + e.message return valueWrap.style.borderColor = 'black' valueWrap.style.borderStyle = 'solid' valueWrap.style.display = 'block' valueWrap.style.position = 'absolute' if /^(submit|reset|button|text|password)$/.test(el.type) or el.nodeName is 'SELECT' valueWrap.style.lineHeight = getCSS(el, 'height') valueWrap.style.top = bounds.top + 'px' valueWrap.style.left = bounds.left + 'px' textValue = if el.nodeName is 'SELECT' then (el.options[el.selectedIndex] or 0).text else el.value if not textValue textValue = el.placeholder textNode = doc.createTextNode(textValue) valueWrap.appendChild textNode body.appendChild valueWrap renderText el, textNode, stack body.removeChild valueWrap return drawImage = (ctx) -> ctx.drawImage.apply ctx, Array::slice.call(arguments, 1) numDraws += 1 return getPseudoElement = (el, which) -> elStyle = window.getComputedStyle(el, which) if not elStyle or not elStyle.content or elStyle.content is 'none' or elStyle.content is '-moz-alt-content' or elStyle.display is 'none' return content = elStyle.content + '' first = content.substr(0, 1) #strips quotes if first is content.substr(content.length - 1) and first.match(/'|"/) content = content.substr(1, content.length - 2) isImage = content.substr(0, 3) is 'url' elps = document.createElement(if isImage then 'img' else 'span') elps.className = pseudoHide + '-before ' + pseudoHide + '-after' Object.keys(elStyle).filter(indexedProperty).forEach (prop) -> # Prevent assigning of read only CSS Rules, ex. length, parentRule try elps.style[prop] = elStyle[prop] catch e Util.log [ 'Tried to assign readonly property ' prop 'Error:' e ] return if isImage elps.src = Util.parseBackgroundImage(content)[0].args[0] else elps.innerHTML = content elps indexedProperty = (property) -> isNaN window.parseInt(property, 10) injectPseudoElements = (el, stack) -> before = getPseudoElement(el, ':before') after = getPseudoElement(el, ':after') if not before and not after return if before el.className += ' ' + pseudoHide + '-before' el.parentNode.insertBefore before, el parseElement before, stack, true el.parentNode.removeChild before el.className = el.className.replace(pseudoHide + '-before', '').trim() if after el.className += ' ' + pseudoHide + '-after' el.appendChild after parseElement after, stack, true el.removeChild after el.className = el.className.replace(pseudoHide + '-after', '').trim() return renderBackgroundRepeat = (ctx, image, backgroundPosition, bounds) -> offsetX = Math.round(bounds.left + backgroundPosition.left) offsetY = Math.round(bounds.top + backgroundPosition.top) ctx.createPattern image ctx.translate offsetX, offsetY ctx.fill() ctx.translate -offsetX, -offsetY return backgroundRepeatShape = (ctx, image, backgroundPosition, bounds, left, top, width, height) -> args = [] args.push [ 'line' Math.round(left) Math.round(top) ] args.push [ 'line' Math.round(left + width) Math.round(top) ] args.push [ 'line' Math.round(left + width) Math.round(height + top) ] args.push [ 'line' Math.round(left) Math.round(height + top) ] createShape ctx, args ctx.save() ctx.clip() renderBackgroundRepeat ctx, image, backgroundPosition, bounds ctx.restore() return renderBackgroundColor = (ctx, backgroundBounds, bgcolor) -> renderRect ctx, backgroundBounds.left, backgroundBounds.top, backgroundBounds.width, backgroundBounds.height, bgcolor return renderBackgroundRepeating = (el, bounds, ctx, image, imageIndex) -> backgroundSize = Util.BackgroundSize(el, bounds, image, imageIndex) backgroundPosition = Util.BackgroundPosition(el, bounds, image, imageIndex, backgroundSize) backgroundRepeat = getCSS(el, 'backgroundRepeat').split(',').map(Util.trimText) image = resizeImage(image, backgroundSize) backgroundRepeat = backgroundRepeat[imageIndex] or backgroundRepeat[0] switch backgroundRepeat when 'repeat-x' backgroundRepeatShape ctx, image, backgroundPosition, bounds, bounds.left, bounds.top + backgroundPosition.top, 99999, image.height when 'repeat-y' backgroundRepeatShape ctx, image, backgroundPosition, bounds, bounds.left + backgroundPosition.left, bounds.top, image.width, 99999 when 'no-repeat' backgroundRepeatShape ctx, image, backgroundPosition, bounds, bounds.left + backgroundPosition.left, bounds.top + backgroundPosition.top, image.width, image.height else renderBackgroundRepeat ctx, image, backgroundPosition, top: bounds.top left: bounds.left width: image.width height: image.height break return renderBackgroundImage = (element, bounds, ctx) -> backgroundImage = getCSS(element, 'backgroundImage') backgroundImages = Util.parseBackgroundImage(backgroundImage) image = undefined imageIndex = backgroundImages.length while imageIndex-- backgroundImage = backgroundImages[imageIndex] if not backgroundImage.args or backgroundImage.args.length is 0 borderSide++ continue key = if backgroundImage.method is 'url' then backgroundImage.args[0] else backgroundImage.value image = loadImage(key) # TODO add support for background-origin if image renderBackgroundRepeating element, bounds, ctx, image, imageIndex else Util.log 'html2canvas: Error loading background:', backgroundImage return resizeImage = (image, bounds) -> if image.width is bounds.width and image.height is bounds.height return image ctx = undefined canvas = doc.createElement('canvas') canvas.width = bounds.width canvas.height = bounds.height ctx = canvas.getContext('2d') drawImage ctx, image, 0, 0, image.width, image.height, 0, 0, bounds.width, bounds.height canvas setOpacity = (ctx, element, parentStack) -> ctx.setVariable 'globalAlpha', getCSS(element, 'opacity') * (if parentStack then parentStack.opacity else 1) removePx = (str) -> str.replace 'px', '' getTransform = (element, parentStack) -> transform = getCSS(element, 'transform') or getCSS(element, '-webkit-transform') or getCSS(element, '-moz-transform') or getCSS(element, '-ms-transform') or getCSS(element, '-o-transform') transformOrigin = getCSS(element, 'transform-origin') or getCSS(element, '-webkit-transform-origin') or getCSS(element, '-moz-transform-origin') or getCSS(element, '-ms-transform-origin') or getCSS(element, '-o-transform-origin') or '0px 0px' transformOrigin = transformOrigin.split(' ').map(removePx).map(Util.asFloat) matrix = undefined if transform and transform isnt 'none' match = transform.match(transformRegExp) if match switch match[1] when 'matrix' matrix = match[2].split(',').map(Util.trimText).map(Util.asFloat) { origin: transformOrigin matrix: matrix } createStack = (element, parentStack, bounds, transform) -> ctx = h2cRenderContext((if not parentStack then documentWidth() else bounds.width), (if not parentStack then documentHeight() else bounds.height)) stack = ctx: ctx opacity: setOpacity(ctx, element, parentStack) cssPosition: getCSS(element, 'position') borders: getBorderData(element) transform: transform clip: if parentStack and parentStack.clip then Util.Extend({}, parentStack.clip) else null setZ element, stack, parentStack # TODO correct overflow for absolute content residing under a static position if options.useOverflow is true and /(hidden|scroll|auto)/.test(getCSS(element, 'overflow')) is true and /(BODY)/i.test(element.nodeName) is false stack.clip = if stack.clip then clipBounds(stack.clip, bounds) else bounds stack getBackgroundBounds = (borders, bounds, clip) -> backgroundBounds = left: bounds.left + borders[3].width top: bounds.top + borders[0].width width: bounds.width - (borders[1].width + borders[3].width) height: bounds.height - (borders[0].width + borders[2].width) if clip backgroundBounds = clipBounds(backgroundBounds, clip) backgroundBounds getBounds = (element, transform) -> bounds = if transform.matrix then Util.OffsetBounds(element) else Util.Bounds(element) transform.origin[0] += bounds.left transform.origin[1] += bounds.top bounds renderElement = (element, parentStack, pseudoElement, ignoreBackground) -> transform = getTransform(element, parentStack) bounds = getBounds(element, transform) image = undefined stack = createStack(element, parentStack, bounds, transform) borders = stack.borders ctx = stack.ctx backgroundBounds = getBackgroundBounds(borders, bounds, stack.clip) borderData = parseBorders(element, bounds, borders) backgroundColor = if ignoreElementsRegExp.test(element.nodeName) then '#efefef' else getCSS(element, 'backgroundColor') createShape ctx, borderData.clip ctx.save() ctx.clip() if backgroundBounds.height > 0 and backgroundBounds.width > 0 and not ignoreBackground renderBackgroundColor ctx, bounds, backgroundColor renderBackgroundImage element, backgroundBounds, ctx else if ignoreBackground stack.backgroundColor = backgroundColor ctx.restore() borderData.borders.forEach (border) -> renderBorders ctx, border.args, border.color return if not pseudoElement injectPseudoElements element, stack switch element.nodeName when 'IMG' if image = loadImage(element.getAttribute('src')) renderImage ctx, element, image, bounds, borders else Util.log 'html2canvas: Error loading <img>:' + element.getAttribute('src') when 'INPUT' # TODO add all relevant type's, i.e. HTML5 new stuff # todo add support for placeholder attribute for browsers which support it if /^(text|url|email|submit|button|reset)$/.test(element.type) and (element.value or element.placeholder or '').length > 0 renderFormValue element, bounds, stack when 'TEXTAREA' if (element.value or element.placeholder or '').length > 0 renderFormValue element, bounds, stack when 'SELECT' if (element.options or element.placeholder or '').length > 0 renderFormValue element, bounds, stack when 'LI' renderListItem element, stack, backgroundBounds when 'CANVAS' renderImage ctx, element, element, bounds, borders stack isElementVisible = (element) -> getCSS(element, 'display') isnt 'none' and getCSS(element, 'visibility') isnt 'hidden' and not element.hasAttribute('data-html2canvas-ignore') parseElement = (element, stack, pseudoElement) -> if isElementVisible(element) stack = renderElement(element, stack, pseudoElement, false) or stack if not ignoreElementsRegExp.test(element.nodeName) parseChildren element, stack, pseudoElement return parseChildren = (element, stack, pseudoElement) -> Util.Children(element).forEach (node) -> if node.nodeType is node.ELEMENT_NODE parseElement node, stack, pseudoElement else if node.nodeType is node.TEXT_NODE renderText element, node, stack return return init = -> background = getCSS(document.documentElement, 'backgroundColor') transparentBackground = Util.isTransparent(background) and element is document.body stack = renderElement(element, null, false, transparentBackground) parseChildren element, stack if transparentBackground background = stack.backgroundColor body.removeChild hidePseudoElements { backgroundColor: background stack: stack } window.scroll 0, 0 element = if options.elements is undefined then document.body else options.elements[0] numDraws = 0 doc = element.ownerDocument Util = _html2canvas.Util support = Util.Support(options, doc) ignoreElementsRegExp = new RegExp('(' + options.ignoreElements + ')') body = doc.body getCSS = Util.getCSS pseudoHide = '___html2canvas___pseudoelement' hidePseudoElements = doc.createElement('style') hidePseudoElements.innerHTML = '.' + pseudoHide + '-before:before { content: "" !important; display: none !important; }' + '.' + pseudoHide + '-after:after { content: "" !important; display: none !important; }' body.appendChild hidePseudoElements images = images or {} getCurvePoints = ((kappa) -> (x, y, r1, r2) -> ox = r1 * kappa oy = r2 * kappa xm = x + r1 ym = y + r2 # y-middle { topLeft: bezierCurve({ x: x y: ym }, { x: x y: ym - oy }, { x: xm - ox y: y }, x: xm y: y) topRight: bezierCurve({ x: x y: y }, { x: x + ox y: y }, { x: xm y: ym - oy }, x: xm y: ym) bottomRight: bezierCurve({ x: xm y: y }, { x: xm y: y + oy }, { x: x + ox y: ym }, x: x y: ym) bottomLeft: bezierCurve({ x: xm y: ym }, { x: xm - ox y: ym }, { x: x y: y + oy }, x: x y: y) } )(4 * (Math.sqrt(2) - 1) / 3) transformRegExp = /(matrix)\((.+)\)/ init() _html2canvas.Preload = (options) -> images = numLoaded: 0 numFailed: 0 numTotal: 0 cleanupDone: false pageOrigin = undefined Util = _html2canvas.Util methods = undefined i = undefined count = 0 element = options.elements[0] or document.body doc = element.ownerDocument domImages = element.getElementsByTagName('img') imgLen = domImages.length link = doc.createElement('a') supportCORS = ((img) -> img.crossOrigin isnt undefined )(new Image) timeoutTimer = undefined isSameOrigin = (url) -> link.href = url link.href = link.href # YES, BELIEVE IT OR NOT, that is required for IE9 - http://jsfiddle.net/niklasvh/2e48b/ origin = link.protocol + link.host origin is pageOrigin start = -> Util.log 'html2canvas: start: images: ' + images.numLoaded + ' / ' + images.numTotal + ' (failed: ' + images.numFailed + ')' if not images.firstRun and images.numLoaded >= images.numTotal Util.log 'Finished loading images: # ' + images.numTotal + ' (failed: ' + images.numFailed + ')' if typeof options.complete is 'function' options.complete images return # TODO modify proxy to serve images with CORS enabled, where available proxyGetImage = (url, img, imageObj) -> callback_name = undefined scriptUrl = options.proxy script = undefined link.href = url url = link.href # work around for pages with base href="" set - WARNING: this may change the url callback_name = 'html2canvas_' + count++ imageObj.callbackname = callback_name if scriptUrl.indexOf('?') > -1 scriptUrl += '&' else scriptUrl += '?' scriptUrl += 'url=' + encodeURIComponent(url) + '&callback=' + callback_name script = doc.createElement('script') window[callback_name] = (a) -> if a.substring(0, 6) is 'error:' imageObj.succeeded = false images.numLoaded++ images.numFailed++ start() else setImageLoadHandlers img, imageObj img.src = a window[callback_name] = undefined # to work with IE<9 // NOTE: that the undefined callback property-name still exists on the window object (for IE<9) try delete window[callback_name] # for all browser that support this catch ex script.parentNode.removeChild script script = null delete imageObj.script delete imageObj.callbackname return script.setAttribute 'type', 'text/javascript' script.setAttribute 'src', scriptUrl imageObj.script = script window.document.body.appendChild script return loadPseudoElement = (element, type) -> style = window.getComputedStyle(element, type) content = style.content if content.substr(0, 3) is 'url' methods.loadImage _html2canvas.Util.parseBackgroundImage(content)[0].args[0] loadBackgroundImages style.backgroundImage, element return loadPseudoElementImages = (element) -> loadPseudoElement element, ':before' loadPseudoElement element, ':after' return loadGradientImage = (backgroundImage, bounds) -> img = _html2canvas.Generate.Gradient(backgroundImage, bounds) if img isnt undefined images[backgroundImage] = img: img succeeded: true images.numTotal++ images.numLoaded++ start() return invalidBackgrounds = (background_image) -> background_image and background_image.method and background_image.args and background_image.args.length > 0 loadBackgroundImages = (background_image, el) -> bounds = undefined _html2canvas.Util.parseBackgroundImage(background_image).filter(invalidBackgrounds).forEach (background_image) -> if background_image.method is 'url' methods.loadImage background_image.args[0] else if background_image.method.match(/\-?gradient$/) if bounds is undefined bounds = _html2canvas.Util.Bounds(el) loadGradientImage background_image.value, bounds return return getImages = (el) -> elNodeType = false # Firefox fails with permission denied on pages with iframes try Util.Children(el).forEach getImages catch e try elNodeType = el.nodeType catch ex elNodeType = false Util.log 'html2canvas: failed to access some element\'s nodeType - Exception: ' + ex.message if elNodeType is 1 or elNodeType is undefined loadPseudoElementImages el try loadBackgroundImages Util.getCSS(el, 'backgroundImage'), el catch e Util.log 'html2canvas: failed to get background-image - Exception: ' + e.message loadBackgroundImages el return setImageLoadHandlers = (img, imageObj) -> img.onload = -> if imageObj.timer isnt undefined # CORS succeeded window.clearTimeout imageObj.timer images.numLoaded++ imageObj.succeeded = true img.onerror = img.onload = null start() return img.onerror = -> if img.crossOrigin is 'anonymous' # CORS failed window.clearTimeout imageObj.timer # let's try with proxy instead if options.proxy src = img.src img = new Image imageObj.img = img img.src = src proxyGetImage img.src, img, imageObj return images.numLoaded++ images.numFailed++ imageObj.succeeded = false img.onerror = img.onload = null start() return return link.href = window.location.href pageOrigin = link.protocol + link.host methods = loadImage: (src) -> img = undefined imageObj = undefined if src and images[src] is undefined img = new Image if src.match(/data:image\/.*;base64,/i) img.src = src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, '') imageObj = images[src] = img: img images.numTotal++ setImageLoadHandlers img, imageObj else if isSameOrigin(src) or options.allowTaint is true imageObj = images[src] = img: img images.numTotal++ setImageLoadHandlers img, imageObj img.src = src else if supportCORS and not options.allowTaint and options.useCORS # attempt to load with CORS img.crossOrigin = 'anonymous' imageObj = images[src] = img: img images.numTotal++ setImageLoadHandlers img, imageObj img.src = src else if options.proxy imageObj = images[src] = img: img images.numTotal++ proxyGetImage src, img, imageObj return cleanupDOM: (cause) -> img = undefined src = undefined if not images.cleanupDone if cause and typeof cause is 'string' Util.log 'html2canvas: Cleanup because: ' + cause else Util.log 'html2canvas: Cleanup after timeout: ' + options.timeout + ' ms.' for src in images # `src = src` if images.hasOwnProperty(src) img = images[src] if typeof img is 'object' and img.callbackname and img.succeeded is undefined # cancel proxy image request window[img.callbackname] = undefined # to work with IE<9 // NOTE: that the undefined callback property-name still exists on the window object (for IE<9) try delete window[img.callbackname] # for all browser that support this catch ex if img.script and img.script.parentNode img.script.setAttribute 'src', 'about:blank' # try to cancel running request img.script.parentNode.removeChild img.script images.numLoaded++ images.numFailed++ Util.log 'html2canvas: Cleaned up failed img: \'' + src + '\' Steps: ' + images.numLoaded + ' / ' + images.numTotal # cancel any pending requests if window.stop isnt undefined window.stop() else if document.execCommand isnt undefined document.execCommand 'Stop', false if document.close isnt undefined document.close() images.cleanupDone = true if not (cause and typeof cause is 'string') start() return renderingDone: -> if timeoutTimer window.clearTimeout timeoutTimer return if options.timeout > 0 timeoutTimer = window.setTimeout(methods.cleanupDOM, options.timeout) Util.log 'html2canvas: Preload starts: finding background-images' images.firstRun = true getImages element Util.log 'html2canvas: Preload: Finding images' # load <img> images i = 0 while i < imgLen methods.loadImage domImages[i].getAttribute('src') i += 1 images.firstRun = false Util.log 'html2canvas: Preload: Done.' if images.numTotal is images.numLoaded start() methods _html2canvas.Renderer = (parseQueue, options) -> # http://www.w3.org/TR/CSS21/zindex.html createRenderQueue = (parseQueue) -> queue = [] rootContext = undefined sortZ = (context) -> Object.keys(context).sort().forEach (zi) -> nonPositioned = [] floated = [] positioned = [] list = [] # positioned after static context[zi].forEach (v) -> if v.node.zIndex.isPositioned or v.node.zIndex.opacity < 1 # http://www.w3.org/TR/css3-color/#transparency # non-positioned element with opactiy < 1 should be stacked as if it were a positioned element with ‘z-index: 0’ and ‘opacity: 1’. positioned.push v else if v.node.zIndex.isFloated floated.push v else nonPositioned.push v return do walk = (arr = nonPositioned.concat(floated, positioned)) -> arr.forEach (v) -> list.push v if v.children walk v.children return return list.forEach (v) -> if v.context sortZ v.context else queue.push v.node return return return rootContext = ((rootNode) -> # `var rootContext` irootContext = {} insert = (context, node, specialParent) -> zi = if node.zIndex.zindex is 'auto' then 0 else Number(node.zIndex.zindex) contextForChildren = context isPositioned = node.zIndex.isPositioned isFloated = node.zIndex.isFloated stub = node: node childrenDest = specialParent # where children without z-index should be pushed into if node.zIndex.ownStacking # '!' comes before numbers in sorted array contextForChildren = stub.context = '!': [ { node: node children: [] } ] childrenDest = undefined else if isPositioned or isFloated childrenDest = stub.children = [] if zi is 0 and specialParent specialParent.push stub else if not context[zi] context[zi] = [] context[zi].push stub node.zIndex.children.forEach (childNode) -> insert contextForChildren, childNode, childrenDest return return insert irootContext, rootNode irootContext )(parseQueue) sortZ rootContext queue getRenderer = (rendererName) -> renderer = undefined if typeof options.renderer is 'string' and _html2canvas.Renderer[rendererName] isnt undefined renderer = _html2canvas.Renderer[rendererName](options) else if typeof rendererName is 'function' renderer = rendererName(options) else throw new Error('Unknown renderer') if typeof renderer isnt 'function' throw new Error('Invalid renderer defined') renderer getRenderer(options.renderer) parseQueue, options, document, createRenderQueue(parseQueue.stack), _html2canvas _html2canvas.Util.Support = (options, doc) -> supportSVGRendering = -> img = new Image canvas = doc.createElement('canvas') ctx = if canvas.getContext is undefined then false else canvas.getContext('2d') if ctx is false return false canvas.width = canvas.height = 10 img.src = [ 'data:image/svg+xml,' '<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'10\' height=\'10\'>' '<foreignObject width=\'10\' height=\'10\'>' '<div xmlns=\'http://www.w3.org/1999/xhtml\' style=\'width:10;height:10;\'>' 'sup' '</div>' '</foreignObject>' '</svg>' ].join('') try ctx.drawImage img, 0, 0 canvas.toDataURL() catch e return false _html2canvas.Util.log 'html2canvas: Parse: SVG powered rendering available' true # Test whether we can use ranges to measure bounding boxes # Opera doesn't provide valid bounds.height/bottom even though it supports the method. supportRangeBounds = -> r = undefined testElement = undefined rangeBounds = undefined rangeHeight = undefined support = false if doc.createRange r = doc.createRange() if r.getBoundingClientRect testElement = doc.createElement('boundtest') testElement.style.height = '123px' testElement.style.display = 'block' doc.body.appendChild testElement r.selectNode testElement rangeBounds = r.getBoundingClientRect() rangeHeight = rangeBounds.height if rangeHeight is 123 support = true doc.body.removeChild testElement support { rangeBounds: supportRangeBounds() svgRendering: options.svgRendering and supportSVGRendering() } window.html2canvas = (elements, opts) -> elements = if elements.length then elements else [ elements ] queue = undefined canvas = undefined options = logging: false elements: elements background: '#fff' proxy: null timeout: 0 useCORS: false allowTaint: false svgRendering: false ignoreElements: 'IFRAME|OBJECT|PARAM' useOverflow: true letterRendering: false chinese: false width: null height: null taintTest: true renderer: 'Canvas' options = _html2canvas.Util.Extend(opts, options) _html2canvas.logging = options.logging options.complete = (images) -> if typeof options.onpreloaded is 'function' if options.onpreloaded(images) is false return queue = _html2canvas.Parse(images, options) if typeof options.onparsed is 'function' if options.onparsed(queue) is false return canvas = _html2canvas.Renderer(queue, options) if typeof options.onrendered is 'function' options.onrendered canvas return # for pages without images, we still want this to be async, i.e. return methods before executing window.setTimeout (-> _html2canvas.Preload options return ), 0 { render: (queue, opts) -> _html2canvas.Renderer queue, _html2canvas.Util.Extend(opts, options) parse: (images, opts) -> _html2canvas.Parse images, _html2canvas.Util.Extend(opts, options) preload: (opts) -> _html2canvas.Preload _html2canvas.Util.Extend(opts, options) log: _html2canvas.Util.log } window.html2canvas.log = _html2canvas.Util.log # for renderers window.html2canvas.Renderer = Canvas: undefined _html2canvas.Renderer.Canvas = (options) -> createShape = (ctx, args) -> ctx.beginPath() args.forEach (arg) -> ctx[arg.name].apply ctx, arg['arguments'] return ctx.closePath() return safeImage = (item) -> if safeImages.indexOf(item['arguments'][0].src) is -1 testctx.drawImage item['arguments'][0], 0, 0 try testctx.getImageData 0, 0, 1, 1 catch e testCanvas = doc.createElement('canvas') testctx = testCanvas.getContext('2d') return false safeImages.push item['arguments'][0].src true renderItem = (ctx, item) -> switch item.type when 'variable' ctx[item.name] = item['arguments'] when 'function' switch item.name when 'createPattern' if item['arguments'][0].width > 0 and item['arguments'][0].height > 0 try ctx.fillStyle = ctx.createPattern(item['arguments'][0], 'repeat') catch e Util.log 'html2canvas: Renderer: Error creating pattern', e.message when 'drawShape' createShape ctx, item['arguments'] when 'drawImage' if item['arguments'][8] > 0 and item['arguments'][7] > 0 if not options.taintTest or options.taintTest and safeImage(item) ctx.drawImage.apply ctx, item['arguments'] else ctx[item.name].apply ctx, item['arguments'] return options = options or {} doc = document safeImages = [] testCanvas = document.createElement('canvas') testctx = testCanvas.getContext('2d') Util = _html2canvas.Util canvas = options.canvas or doc.createElement('canvas') (parsedData, options, document, queue, _html2canvas) -> ctx = canvas.getContext('2d') newCanvas = undefined bounds = undefined fstyle = undefined zStack = parsedData.stack canvas.width = canvas.style.width = options.width or zStack.ctx.width canvas.height = canvas.style.height = options.height or zStack.ctx.height fstyle = ctx.fillStyle ctx.fillStyle = if Util.isTransparent(zStack.backgroundColor) and options.background isnt undefined then options.background else parsedData.backgroundColor ctx.fillRect 0, 0, canvas.width, canvas.height ctx.fillStyle = fstyle queue.forEach (storageContext) -> # set common settings for canvas ctx.textBaseline = 'bottom' ctx.save() if storageContext.transform.matrix ctx.translate storageContext.transform.origin[0], storageContext.transform.origin[1] ctx.transform.apply ctx, storageContext.transform.matrix ctx.translate -storageContext.transform.origin[0], -storageContext.transform.origin[1] if storageContext.clip ctx.beginPath() ctx.rect storageContext.clip.left, storageContext.clip.top, storageContext.clip.width, storageContext.clip.height ctx.clip() if storageContext.ctx.storage storageContext.ctx.storage.forEach (item) -> renderItem ctx, item return ctx.restore() return Util.log 'html2canvas: Renderer: Canvas renderer done - returning canvas obj' if options.elements.length is 1 if typeof options.elements[0] is 'object' and options.elements[0].nodeName isnt 'BODY' # crop image to the bounds of selected (single) element bounds = _html2canvas.Util.Bounds(options.elements[0]) newCanvas = document.createElement('canvas') newCanvas.width = Math.ceil(bounds.width) newCanvas.height = Math.ceil(bounds.height) ctx = newCanvas.getContext('2d') ctx.drawImage canvas, bounds.left, bounds.top, bounds.width, bounds.height, 0, 0, bounds.width, bounds.height canvas = null return newCanvas canvas return ) window, document module.exports = window.html2canvas
45103
### html2canvas 0.4.1 <http://html2canvas.hertzen.com> Copyright (c) 2013 <NAME> Released under MIT License ### ((window, document) -> # global variables borderSide = undefined toPX = (element, attribute, value) -> rsLeft = element.runtimeStyle and element.runtimeStyle[attribute] left = undefined style = element.style # Check if we are not dealing with pixels, (Opera has issues with this) # Ported from jQuery css.js # From the awesome hack by <NAME> # http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 # If we're not dealing with a regular pixel number # but a number that has a weird ending, we need to convert it to pixels if not /^-?[0-9]+\.?[0-9]*(?:px)?$/i.test(value) and /^-?\d/.test(value) # Remember the original values left = style.left # Put in the new values to get a computed value out if rsLeft element.runtimeStyle.left = element.currentStyle.left style.left = if attribute is 'fontSize' then '1em' else value or 0 value = style.pixelLeft + 'px' # Revert the changed values style.left = left if rsLeft element.runtimeStyle.left = rsLeft if not /^(thin|medium|thick)$/i.test(value) return Math.round(parseFloat(value)) + 'px' value asInt = (val) -> parseInt val, 10 parseBackgroundSizePosition = (value, element, attribute, index) -> value = (value or '').split(',') value = value[index or 0] or value[0] or 'auto' value = _html2canvas.Util.trimText(value).split(' ') if attribute is 'backgroundSize' and (not value[0] or value[0].match(/cover|contain|auto/)) #these values will be handled in the parent function else value[0] = if value[0].indexOf('%') is -1 then toPX(element, attribute + 'X', value[0]) else value[0] if value[1] is undefined if attribute is 'backgroundSize' value[1] = 'auto' return value else # IE 9 doesn't return double digit always value[1] = value[0] value[1] = if value[1].indexOf('%') is -1 then toPX(element, attribute + 'Y', value[1]) else value[1] value backgroundBoundsFactory = (prop, el, bounds, image, imageIndex, backgroundSize) -> bgposition = _html2canvas.Util.getCSS(el, prop, imageIndex) topPos = undefined left = undefined percentage = undefined val = undefined if bgposition.length is 1 val = bgposition[0] bgposition = [] bgposition[0] = val bgposition[1] = val if bgposition[0].toString().indexOf('%') isnt -1 percentage = parseFloat(bgposition[0]) / 100 left = bounds.width * percentage if prop isnt 'backgroundSize' left -= (backgroundSize or image).width * percentage else if prop is 'backgroundSize' if bgposition[0] is 'auto' left = image.width else if /contain|cover/.test(bgposition[0]) resized = _html2canvas.Util.resizeBounds(image.width, image.height, bounds.width, bounds.height, bgposition[0]) left = resized.width topPos = resized.height else left = parseInt(bgposition[0], 10) else left = parseInt(bgposition[0], 10) if bgposition[1] is 'auto' topPos = left / image.width * image.height else if bgposition[1].toString().indexOf('%') isnt -1 percentage = parseFloat(bgposition[1]) / 100 topPos = bounds.height * percentage if prop isnt 'backgroundSize' topPos -= (backgroundSize or image).height * percentage else topPos = parseInt(bgposition[1], 10) [ left topPos ] h2cRenderContext = (width, height) -> storage = [] { storage: storage width: width height: height clip: -> storage.push type: 'function' name: 'clip' 'arguments': arguments return translate: -> storage.push type: 'function' name: 'translate' 'arguments': arguments return fill: -> storage.push type: 'function' name: 'fill' 'arguments': arguments return save: -> storage.push type: 'function' name: 'save' 'arguments': arguments return restore: -> storage.push type: 'function' name: 'restore' 'arguments': arguments return fillRect: -> storage.push type: 'function' name: 'fillRect' 'arguments': arguments return createPattern: -> storage.push type: 'function' name: 'createPattern' 'arguments': arguments return drawShape: -> shape = [] storage.push type: 'function' name: 'drawShape' 'arguments': shape { moveTo: -> shape.push name: 'moveTo' 'arguments': arguments return lineTo: -> shape.push name: 'lineTo' 'arguments': arguments return arcTo: -> shape.push name: 'arcTo' 'arguments': arguments return bezierCurveTo: -> shape.push name: 'bezierCurveTo' 'arguments': arguments return quadraticCurveTo: -> shape.push name: 'quadraticCurveTo' 'arguments': arguments return } drawImage: -> storage.push type: 'function' name: 'drawImage' 'arguments': arguments return fillText: -> storage.push type: 'function' name: 'fillText' 'arguments': arguments return setVariable: (variable, value) -> storage.push type: 'variable' name: variable 'arguments': value value } h2czContext = (zindex) -> { zindex: zindex children: [] } 'use strict' _html2canvas = {} previousElement = undefined computedCSS = undefined html2canvas = undefined _html2canvas.Util = {} _html2canvas.Util.log = (a) -> if _html2canvas.logging and window.console and window.console.log window.console.log a return _html2canvas.Util.trimText = ((isNative) -> (input) -> if isNative then isNative.apply(input) else ((input or '') + '').replace(/^\s+|\s+$/g, '') )(String::trim) _html2canvas.Util.asFloat = (v) -> parseFloat v do -> # TODO: support all possible length values TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g _html2canvas.Util.parseTextShadows = (value) -> if not value or value is 'none' return [] # find multiple shadow declarations shadows = value.match(TEXT_SHADOW_PROPERTY) results = [] i = 0 while shadows and i < shadows.length s = shadows[i].match(TEXT_SHADOW_VALUES) results.push color: s[0] offsetX: if s[1] then s[1].replace('px', '') else 0 offsetY: if s[2] then s[2].replace('px', '') else 0 blur: if s[3] then s[3].replace('px', '') else 0 i++ results return _html2canvas.Util.parseBackgroundImage = (value) -> whitespace = ' \u000d\n\u0009' method = undefined definition = undefined prefix = undefined prefix_i = undefined block = undefined results = [] c = undefined mode = 0 numParen = 0 quote = undefined args = undefined appendResult = -> if method if definition.substr(0, 1) is '"' definition = definition.substr(1, definition.length - 2) if definition args.push definition if method.substr(0, 1) is '-' and (prefix_i = method.indexOf('-', 1) + 1) > 0 prefix = method.substr(0, prefix_i) method = method.substr(prefix_i) results.push prefix: prefix method: method.toLowerCase() value: block args: args args = [] #for some odd reason, setting .length = 0 didn't work in safari method = prefix = definition = block = '' return appendResult() i = 0 ii = value.length while i < ii c = value[i] if mode is 0 and whitespace.indexOf(c) > -1 i++ continue switch c when '"' if not quote quote = c else if quote is c quote = null when '(' if quote break else if mode is 0 mode = 1 block += c i++ continue else numParen++ when ')' if quote break else if mode is 1 if numParen is 0 mode = 0 block += c appendResult() i++ continue else numParen-- when ',' if quote break else if mode is 0 appendResult() i++ continue else if mode is 1 if numParen is 0 and not method.match(/^url$/i) args.push definition definition = '' block += c i++ continue block += c if mode is 0 method += c else definition += c i++ appendResult() results _html2canvas.Util.Bounds = (element) -> clientRect = undefined bounds = {} if element.getBoundingClientRect clientRect = element.getBoundingClientRect() # TODO add scroll position to bounds, so no scrolling of window necessary bounds.top = clientRect.top bounds.bottom = clientRect.bottom or clientRect.top + clientRect.height bounds.left = clientRect.left bounds.width = element.offsetWidth bounds.height = element.offsetHeight bounds # TODO ideally, we'd want everything to go through this function instead of Util.Bounds, # but would require further work to calculate the correct positions for elements with offsetParents _html2canvas.Util.OffsetBounds = (element) -> parent = if element.offsetParent then _html2canvas.Util.OffsetBounds(element.offsetParent) else top: 0 left: 0 { top: element.offsetTop + parent.top bottom: element.offsetTop + element.offsetHeight + parent.top left: element.offsetLeft + parent.left width: element.offsetWidth height: element.offsetHeight } _html2canvas.Util.getCSS = (element, attribute, index) -> if previousElement isnt element computedCSS = document.defaultView.getComputedStyle(element, null) value = computedCSS[attribute] if /^background(Size|Position)$/.test(attribute) return parseBackgroundSizePosition(value, element, attribute, index) else if /border(Top|Bottom)(Left|Right)Radius/.test(attribute) arr = value.split(' ') if arr.length <= 1 arr[1] = arr[0] return arr.map(asInt) value _html2canvas.Util.resizeBounds = (current_width, current_height, target_width, target_height, stretch_mode) -> target_ratio = target_width / target_height current_ratio = current_width / current_height output_width = undefined output_height = undefined if not stretch_mode or stretch_mode is 'auto' output_width = target_width output_height = target_height else if target_ratio < current_ratio ^ stretch_mode is 'contain' output_height = target_height output_width = target_height * current_ratio else output_width = target_width output_height = target_width / current_ratio { width: output_width height: output_height } _html2canvas.Util.BackgroundPosition = (el, bounds, image, imageIndex, backgroundSize) -> result = backgroundBoundsFactory('backgroundPosition', el, bounds, image, imageIndex, backgroundSize) { left: result[0] top: result[1] } _html2canvas.Util.BackgroundSize = (el, bounds, image, imageIndex) -> result = backgroundBoundsFactory('backgroundSize', el, bounds, image, imageIndex) { width: result[0] height: result[1] } _html2canvas.Util.Extend = (options, defaults) -> for key of options if options.hasOwnProperty(key) defaults[key] = options[key] defaults ### # Derived from jQuery.contents() # Copyright 2010, <NAME> # Dual licensed under the MIT or GPL Version 2 licenses. # http://jquery.org/license ### _html2canvas.Util.Children = (elem) -> children = undefined try children = if elem.nodeName and elem.nodeName.toUpperCase() is 'IFRAME' then elem.contentDocument or elem.contentWindow.document else ((array) -> ret = [] if array isnt null ((first, second) -> i = first.length j = 0 if typeof second.length is 'number' l = second.length while j < l first[i++] = second[j] j++ else while second[j] isnt undefined first[i++] = second[j++] first.length = i first ) ret, array ret )(elem.childNodes) catch ex _html2canvas.Util.log 'html2canvas.Util.Children failed with exception: ' + ex.message children = [] children _html2canvas.Util.isTransparent = (backgroundColor) -> backgroundColor is 'transparent' or backgroundColor is 'rgba(0, 0, 0, 0)' _html2canvas.Util.Font = do -> fontData = {} (font, fontSize, doc) -> if fontData[font + '-' + fontSize] isnt undefined return fontData[font + '-' + fontSize] container = doc.createElement('div') img = doc.createElement('img') span = doc.createElement('span') sampleText = 'Hidden Text' baseline = undefined middle = undefined metricsObj = undefined container.style.visibility = 'hidden' container.style.fontFamily = font container.style.fontSize = fontSize container.style.margin = 0 container.style.padding = 0 doc.body.appendChild container # http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever (handtinywhite.gif) img.src = 'data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACwAAAAAAQABAAACAkQBADs=' img.width = 1 img.height = 1 img.style.margin = 0 img.style.padding = 0 img.style.verticalAlign = 'baseline' span.style.fontFamily = font span.style.fontSize = fontSize span.style.margin = 0 span.style.padding = 0 span.appendChild doc.createTextNode(sampleText) container.appendChild span container.appendChild img baseline = img.offsetTop - (span.offsetTop) + 1 container.removeChild span container.appendChild doc.createTextNode(sampleText) container.style.lineHeight = 'normal' img.style.verticalAlign = 'super' middle = img.offsetTop - (container.offsetTop) + 1 metricsObj = baseline: baseline lineWidth: 1 middle: middle fontData[font + '-' + fontSize] = metricsObj doc.body.removeChild container metricsObj do -> Util = _html2canvas.Util Generate = {} addScrollStops = (grad) -> (colorStop) -> try grad.addColorStop colorStop.stop, colorStop.color catch e Util.log [ 'failed to add color stop: ' e '; tried to add: ' colorStop ] return _html2canvas.Generate = Generate reGradients = [ /^(-webkit-linear-gradient)\(([a-z\s]+)([\w\d\.\s,%\(\)]+)\)$/ /^(-o-linear-gradient)\(([a-z\s]+)([\w\d\.\s,%\(\)]+)\)$/ /^(-webkit-gradient)\((linear|radial),\s((?:\d{1,3}%?)\s(?:\d{1,3}%?),\s(?:\d{1,3}%?)\s(?:\d{1,3}%?))([\w\d\.\s,%\(\)\-]+)\)$/ /^(-moz-linear-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?))([\w\d\.\s,%\(\)]+)\)$/ /^(-webkit-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s([a-z\-]+)([\w\d\.\s,%\(\)]+)\)$/ /^(-moz-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s?([a-z\-]*)([\w\d\.\s,%\(\)]+)\)$/ /^(-o-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s([a-z\-]+)([\w\d\.\s,%\(\)]+)\)$/ ] ### # TODO: Add IE10 vendor prefix (-ms) support # TODO: Add W3C gradient (linear-gradient) support # TODO: Add old Webkit -webkit-gradient(radial, ...) support # TODO: Maybe some RegExp optimizations are possible ;o) ### Generate.parseGradient = (css, bounds) -> gradient = undefined i = undefined len = reGradients.length m1 = undefined stop = undefined m2 = undefined m2Len = undefined step = undefined m3 = undefined tl = undefined tr = undefined br = undefined bl = undefined i = 0 while i < len m1 = css.match(reGradients[i]) if m1 break i += 1 if m1 switch m1[1] when '-webkit-linear-gradient', '-o-linear-gradient' gradient = type: 'linear' x0: null y0: null x1: null y1: null colorStops: [] # get coordinates m2 = m1[2].match(/\w+/g) if m2 m2Len = m2.length i = 0 while i < m2Len switch m2[i] when 'top' gradient.y0 = 0 gradient.y1 = bounds.height when 'right' gradient.x0 = bounds.width gradient.x1 = 0 when 'bottom' gradient.y0 = bounds.height gradient.y1 = 0 when 'left' gradient.x0 = 0 gradient.x1 = bounds.width i += 1 if gradient.x0 is null and gradient.x1 is null # center gradient.x0 = gradient.x1 = bounds.width / 2 if gradient.y0 is null and gradient.y1 is null # center gradient.y0 = gradient.y1 = bounds.height / 2 # get colors and stops m2 = m1[3].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}(?:%|px))?)+/g) if m2 m2Len = m2.length step = 1 / Math.max(m2Len - 1, 1) i = 0 while i < m2Len m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/) if m3[2] stop = parseFloat(m3[2]) if m3[3] is '%' stop /= 100 else # px - stupid opera stop /= bounds.width else stop = i * step gradient.colorStops.push color: m3[1] stop: stop i += 1 when '-webkit-gradient' gradient = type: if m1[2] is 'radial' then 'circle' else m1[2] x0: 0 y0: 0 x1: 0 y1: 0 colorStops: [] # get coordinates m2 = m1[3].match(/(\d{1,3})%?\s(\d{1,3})%?,\s(\d{1,3})%?\s(\d{1,3})%?/) if m2 gradient.x0 = m2[1] * bounds.width / 100 gradient.y0 = m2[2] * bounds.height / 100 gradient.x1 = m2[3] * bounds.width / 100 gradient.y1 = m2[4] * bounds.height / 100 # get colors and stops m2 = m1[4].match(/((?:from|to|color-stop)\((?:[0-9\.]+,\s)?(?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)\))+/g) if m2 m2Len = m2.length i = 0 while i < m2Len m3 = m2[i].match(/(from|to|color-stop)\(([0-9\.]+)?(?:,\s)?((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\)/) stop = parseFloat(m3[2]) if m3[1] is 'from' stop = 0.0 if m3[1] is 'to' stop = 1.0 gradient.colorStops.push color: m3[3] stop: stop i += 1 when '-moz-linear-gradient' gradient = type: 'linear' x0: 0 y0: 0 x1: 0 y1: 0 colorStops: [] # get coordinates m2 = m1[2].match(/(\d{1,3})%?\s(\d{1,3})%?/) # m2[1] is 0% -> left # m2[1] is 50% -> center # m2[1] is 100% -> right # m2[2] is 0% -> top # m2[2] is 50% -> center # m2[2] is 100% -> bottom if m2 gradient.x0 = m2[1] * bounds.width / 100 gradient.y0 = m2[2] * bounds.height / 100 gradient.x1 = bounds.width - (gradient.x0) gradient.y1 = bounds.height - (gradient.y0) # get colors and stops m2 = m1[3].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}%)?)+/g) if m2 m2Len = m2.length step = 1 / Math.max(m2Len - 1, 1) i = 0 while i < m2Len m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%)?/) if m3[2] stop = parseFloat(m3[2]) if m3[3] # percentage stop /= 100 else stop = i * step gradient.colorStops.push color: m3[1] stop: stop i += 1 when '-webkit-radial-gradient', '-moz-radial-gradient', '-o-radial-gradient' gradient = type: 'circle' x0: 0 y0: 0 x1: bounds.width y1: bounds.height cx: 0 cy: 0 rx: 0 ry: 0 colorStops: [] # center m2 = m1[2].match(/(\d{1,3})%?\s(\d{1,3})%?/) if m2 gradient.cx = m2[1] * bounds.width / 100 gradient.cy = m2[2] * bounds.height / 100 # size m2 = m1[3].match(/\w+/) m3 = m1[4].match(/[a-z\-]*/) if m2 and m3 switch m3[0] # is equivalent to farthest-corner when 'farthest-corner', 'cover', '' # mozilla removes "cover" from definition :( tl = Math.sqrt(gradient.cx ** 2 + gradient.cy ** 2) tr = Math.sqrt(gradient.cx ** 2 + (gradient.y1 - (gradient.cy)) ** 2) br = Math.sqrt((gradient.x1 - (gradient.cx)) ** 2 + (gradient.y1 - (gradient.cy)) ** 2) bl = Math.sqrt((gradient.x1 - (gradient.cx)) ** 2 + gradient.cy ** 2) gradient.rx = gradient.ry = Math.max(tl, tr, br, bl) when 'closest-corner' tl = Math.sqrt(gradient.cx ** 2 + gradient.cy ** 2) tr = Math.sqrt(gradient.cx ** 2 + (gradient.y1 - (gradient.cy)) ** 2) br = Math.sqrt((gradient.x1 - (gradient.cx)) ** 2 + (gradient.y1 - (gradient.cy)) ** 2) bl = Math.sqrt((gradient.x1 - (gradient.cx)) ** 2 + gradient.cy ** 2) gradient.rx = gradient.ry = Math.min(tl, tr, br, bl) when 'farthest-side' if m2[0] is 'circle' gradient.rx = gradient.ry = Math.max(gradient.cx, gradient.cy, gradient.x1 - (gradient.cx), gradient.y1 - (gradient.cy)) else # ellipse gradient.type = m2[0] gradient.rx = Math.max(gradient.cx, gradient.x1 - (gradient.cx)) gradient.ry = Math.max(gradient.cy, gradient.y1 - (gradient.cy)) when 'closest-side', 'contain' # is equivalent to closest-side if m2[0] is 'circle' gradient.rx = gradient.ry = Math.min(gradient.cx, gradient.cy, gradient.x1 - (gradient.cx), gradient.y1 - (gradient.cy)) else # ellipse gradient.type = m2[0] gradient.rx = Math.min(gradient.cx, gradient.x1 - (gradient.cx)) gradient.ry = Math.min(gradient.cy, gradient.y1 - (gradient.cy)) # TODO: add support for "30px 40px" sizes (webkit only) # color stops m2 = m1[5].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}(?:%|px))?)+/g) if m2 m2Len = m2.length step = 1 / Math.max(m2Len - 1, 1) i = 0 while i < m2Len m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/) if m3[2] stop = parseFloat(m3[2]) if m3[3] is '%' stop /= 100 else # px - stupid opera stop /= bounds.width else stop = i * step gradient.colorStops.push color: m3[1] stop: stop i += 1 gradient Generate.Gradient = (src, bounds) -> if bounds.width is 0 or bounds.height is 0 return canvas = document.createElement('canvas') ctx = canvas.getContext('2d') gradient = undefined grad = undefined canvas.width = bounds.width canvas.height = bounds.height # TODO: add support for multi defined background gradients gradient = _html2canvas.Generate.parseGradient(src, bounds) if gradient switch gradient.type when 'linear' grad = ctx.createLinearGradient(gradient.x0, gradient.y0, gradient.x1, gradient.y1) gradient.colorStops.forEach addScrollStops(grad) ctx.fillStyle = grad ctx.fillRect 0, 0, bounds.width, bounds.height when 'circle' grad = ctx.createRadialGradient(gradient.cx, gradient.cy, 0, gradient.cx, gradient.cy, gradient.rx) gradient.colorStops.forEach addScrollStops(grad) ctx.fillStyle = grad ctx.fillRect 0, 0, bounds.width, bounds.height when 'ellipse' canvasRadial = document.createElement('canvas') ctxRadial = canvasRadial.getContext('2d') ri = Math.max(gradient.rx, gradient.ry) di = ri * 2 canvasRadial.width = canvasRadial.height = di grad = ctxRadial.createRadialGradient(gradient.rx, gradient.ry, 0, gradient.rx, gradient.ry, ri) gradient.colorStops.forEach addScrollStops(grad) ctxRadial.fillStyle = grad ctxRadial.fillRect 0, 0, di, di ctx.fillStyle = gradient.colorStops[gradient.colorStops.length - 1].color ctx.fillRect 0, 0, canvas.width, canvas.height ctx.drawImage canvasRadial, gradient.cx - (gradient.rx), gradient.cy - (gradient.ry), 2 * gradient.rx, 2 * gradient.ry canvas Generate.ListAlpha = (number) -> tmp = '' modulus = undefined loop modulus = number % 26 tmp = String.fromCharCode(modulus + 64) + tmp number = number / 26 unless number * 26 > 26 break tmp Generate.ListRoman = (number) -> romanArray = [ 'M' 'CM' 'D' 'CD' 'C' 'XC' 'L' 'XL' 'X' 'IX' 'V' 'IV' 'I' ] decimal = [ 1000 900 500 400 100 90 50 40 10 9 5 4 1 ] roman = '' v = undefined len = romanArray.length if number <= 0 or number >= 4000 return number v = 0 while v < len while number >= decimal[v] number -= decimal[v] roman += romanArray[v] v += 1 roman return _html2canvas.Parse = (images, options) -> documentWidth = -> Math.max Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth), Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth), Math.max(doc.body.clientWidth, doc.documentElement.clientWidth) documentHeight = -> Math.max Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight), Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight), Math.max(doc.body.clientHeight, doc.documentElement.clientHeight) getCSSInt = (element, attribute) -> val = parseInt(getCSS(element, attribute), 10) if isNaN(val) then 0 else val # borders in old IE are throwing 'medium' for demo.html renderRect = (ctx, x, y, w, h, bgcolor) -> if bgcolor isnt 'transparent' ctx.setVariable 'fillStyle', bgcolor ctx.fillRect x, y, w, h numDraws += 1 return capitalize = (m, p1, p2) -> if m.length > 0 return p1 + p2.toUpperCase() return textTransform = (text, transform) -> switch transform when 'lowercase' return text.toLowerCase() when 'capitalize' return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize) when 'uppercase' return text.toUpperCase() else return text return noLetterSpacing = (letter_spacing) -> /^(normal|none|0px)$/.test letter_spacing drawText = (currentText, x, y, ctx) -> if currentText isnt null and Util.trimText(currentText).length > 0 ctx.fillText currentText, x, y numDraws += 1 return setTextVariables = (ctx, el, text_decoration, color) -> align = false bold = getCSS(el, 'fontWeight') family = getCSS(el, 'fontFamily') size = getCSS(el, 'fontSize') shadows = Util.parseTextShadows(getCSS(el, 'textShadow')) switch parseInt(bold, 10) when 401 bold = 'bold' when 400 bold = 'normal' ctx.setVariable 'fillStyle', color ctx.setVariable 'font', [ getCSS(el, 'fontStyle') getCSS(el, 'fontVariant') bold size family ].join(' ') ctx.setVariable 'textAlign', if align then 'right' else 'left' if shadows.length # TODO: support multiple text shadows # apply the first text shadow ctx.setVariable 'shadowColor', shadows[0].color ctx.setVariable 'shadowOffsetX', shadows[0].offsetX ctx.setVariable 'shadowOffsetY', shadows[0].offsetY ctx.setVariable 'shadowBlur', shadows[0].blur if text_decoration isnt 'none' return Util.Font(family, size, doc) return renderTextDecoration = (ctx, text_decoration, bounds, metrics, color) -> switch text_decoration when 'underline' # Draws a line at the baseline of the font # TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size renderRect ctx, bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, color when 'overline' renderRect ctx, bounds.left, Math.round(bounds.top), bounds.width, 1, color when 'line-through' # TODO try and find exact position for line-through renderRect ctx, bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, color return getTextBounds = (state, text, textDecoration, isLast, transform) -> bounds = undefined if support.rangeBounds and not transform if textDecoration isnt 'none' or Util.trimText(text).length isnt 0 bounds = textRangeBounds(text, state.node, state.textOffset) state.textOffset += text.length else if state.node and typeof state.node.nodeValue is 'string' newTextNode = if isLast then state.node.splitText(text.length) else null bounds = textWrapperBounds(state.node, transform) state.node = newTextNode bounds textRangeBounds = (text, textNode, textOffset) -> range = doc.createRange() range.setStart textNode, textOffset range.setEnd textNode, textOffset + text.length range.getBoundingClientRect() textWrapperBounds = (oldTextNode, transform) -> parent = oldTextNode.parentNode wrapElement = doc.createElement('wrapper') backupText = oldTextNode.cloneNode(true) wrapElement.appendChild oldTextNode.cloneNode(true) parent.replaceChild wrapElement, oldTextNode bounds = if transform then Util.OffsetBounds(wrapElement) else Util.Bounds(wrapElement) parent.replaceChild backupText, wrapElement bounds renderText = (el, textNode, stack) -> ctx = stack.ctx color = getCSS(el, 'color') textDecoration = getCSS(el, 'textDecoration') textAlign = getCSS(el, 'textAlign') metrics = undefined textList = undefined state = node: textNode textOffset: 0 if Util.trimText(textNode.nodeValue).length > 0 textNode.nodeValue = textTransform(textNode.nodeValue, getCSS(el, 'textTransform')) textAlign = textAlign.replace([ '-webkit-auto' ], [ 'auto' ]) textList = if not options.letterRendering and /^(left|right|justify|auto)$/.test(textAlign) and noLetterSpacing(getCSS(el, 'letterSpacing')) then textNode.nodeValue.split(/(\b| )/) else textNode.nodeValue.split('') metrics = setTextVariables(ctx, el, textDecoration, color) if options.chinese textList.forEach (word, index) -> if /.*[\u4E00-\u9FA5].*$/.test(word) word = word.split('') word.unshift index, 1 textList.splice.apply textList, word return textList.forEach (text, index) -> bounds = getTextBounds(state, text, textDecoration, index < textList.length - 1, stack.transform.matrix) if bounds drawText text, bounds.left, bounds.bottom, ctx renderTextDecoration ctx, textDecoration, bounds, metrics, color return return listPosition = (element, val) -> boundElement = doc.createElement('boundelement') originalType = undefined bounds = undefined boundElement.style.display = 'inline' originalType = element.style.listStyleType element.style.listStyleType = 'none' boundElement.appendChild doc.createTextNode(val) element.insertBefore boundElement, element.firstChild bounds = Util.Bounds(boundElement) element.removeChild boundElement element.style.listStyleType = originalType bounds elementIndex = (el) -> i = -1 count = 1 childs = el.parentNode.childNodes if el.parentNode while childs[++i] isnt el if childs[i].nodeType is 1 count++ count else -1 listItemText = (element, type) -> currentIndex = elementIndex(element) text = undefined switch type when 'decimal' text = currentIndex when 'decimal-leading-zero' text = if currentIndex.toString().length is 1 then (currentIndex = '0' + currentIndex.toString()) else currentIndex.toString() when 'upper-roman' text = _html2canvas.Generate.ListRoman(currentIndex) when 'lower-roman' text = _html2canvas.Generate.ListRoman(currentIndex).toLowerCase() when 'lower-alpha' text = _html2canvas.Generate.ListAlpha(currentIndex).toLowerCase() when 'upper-alpha' text = _html2canvas.Generate.ListAlpha(currentIndex) text + '. ' renderListItem = (element, stack, elBounds) -> x = undefined text = undefined ctx = stack.ctx type = getCSS(element, 'listStyleType') listBounds = undefined if /^(decimal|decimal-leading-zero|upper-alpha|upper-latin|upper-roman|lower-alpha|lower-greek|lower-latin|lower-roman)$/i.test(type) text = listItemText(element, type) listBounds = listPosition(element, text) setTextVariables ctx, element, 'none', getCSS(element, 'color') if getCSS(element, 'listStylePosition') is 'inside' ctx.setVariable 'textAlign', 'left' x = elBounds.left else return drawText text, x, listBounds.bottom, ctx return loadImage = (src) -> img = images[src] if img and img.succeeded is true then img.img else false clipBounds = (src, dst) -> x = Math.max(src.left, dst.left) y = Math.max(src.top, dst.top) x2 = Math.min(src.left + src.width, dst.left + dst.width) y2 = Math.min(src.top + src.height, dst.top + dst.height) { left: x top: y width: x2 - x height: y2 - y } setZ = (element, stack, parentStack) -> newContext = undefined isPositioned = stack.cssPosition isnt 'static' zIndex = if isPositioned then getCSS(element, 'zIndex') else 'auto' opacity = getCSS(element, 'opacity') isFloated = getCSS(element, 'cssFloat') isnt 'none' # https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context # When a new stacking context should be created: # the root element (HTML), # positioned (absolutely or relatively) with a z-index value other than "auto", # elements with an opacity value less than 1. (See the specification for opacity), # on mobile WebKit and Chrome 22+, position: fixed always creates a new stacking context, even when z-index is "auto" (See this post) stack.zIndex = newContext = h2czContext(zIndex) newContext.isPositioned = isPositioned newContext.isFloated = isFloated newContext.opacity = opacity newContext.ownStacking = zIndex isnt 'auto' or opacity < 1 if parentStack parentStack.zIndex.children.push stack return renderImage = (ctx, element, image, bounds, borders) -> paddingLeft = getCSSInt(element, 'paddingLeft') paddingTop = getCSSInt(element, 'paddingTop') paddingRight = getCSSInt(element, 'paddingRight') paddingBottom = getCSSInt(element, 'paddingBottom') bLeft = bounds.left + paddingLeft + borders[3].width bTop = bounds.top + paddingTop + borders[0].width bWidth = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight) drawImage ctx, image, 0, 0, image.width, image.height, bLeft, bTop, bWidth, bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom) return getBorderData = (element) -> [ 'Top' 'Right' 'Bottom' 'Left' ].map (side) -> { width: getCSSInt(element, 'border' + side + 'Width') color: getCSS(element, 'border' + side + 'Color') } getBorderRadiusData = (element) -> [ 'TopLeft' 'TopRight' 'BottomRight' 'BottomLeft' ].map (side) -> getCSS element, 'border' + side + 'Radius' bezierCurve = (start, startControl, endControl, end) -> lerp = (a, b, t) -> { x: a.x + (b.x - (a.x)) * t y: a.y + (b.y - (a.y)) * t } { start: start startControl: startControl endControl: endControl end: end subdivide: (t) -> ab = lerp(start, startControl, t) bc = lerp(startControl, endControl, t) cd = lerp(endControl, end, t) abbc = lerp(ab, bc, t) bccd = lerp(bc, cd, t) dest = lerp(abbc, bccd, t) [ bezierCurve(start, ab, abbc, dest) bezierCurve(dest, bccd, cd, end) ] curveTo: (borderArgs) -> borderArgs.push [ 'bezierCurve' startControl.x startControl.y endControl.x endControl.y end.x end.y ] return curveToReversed: (borderArgs) -> borderArgs.push [ 'bezierCurve' endControl.x endControl.y startControl.x startControl.y start.x start.y ] return } parseCorner = (borderArgs, radius1, radius2, corner1, corner2, x, y) -> if radius1[0] > 0 or radius1[1] > 0 borderArgs.push [ 'line' corner1[0].start.x corner1[0].start.y ] corner1[0].curveTo borderArgs corner1[1].curveTo borderArgs else borderArgs.push [ 'line' x y ] if radius2[0] > 0 or radius2[1] > 0 borderArgs.push [ 'line' corner2[0].start.x corner2[0].start.y ] return drawSide = (borderData, radius1, radius2, outer1, inner1, outer2, inner2) -> borderArgs = [] if radius1[0] > 0 or radius1[1] > 0 borderArgs.push [ 'line' outer1[1].start.x outer1[1].start.y ] outer1[1].curveTo borderArgs else borderArgs.push [ 'line' borderData.c1[0] borderData.c1[1] ] if radius2[0] > 0 or radius2[1] > 0 borderArgs.push [ 'line' outer2[0].start.x outer2[0].start.y ] outer2[0].curveTo borderArgs borderArgs.push [ 'line' inner2[0].end.x inner2[0].end.y ] inner2[0].curveToReversed borderArgs else borderArgs.push [ 'line' borderData.c2[0] borderData.c2[1] ] borderArgs.push [ 'line' borderData.c3[0] borderData.c3[1] ] if radius1[0] > 0 or radius1[1] > 0 borderArgs.push [ 'line' inner1[1].end.x inner1[1].end.y ] inner1[1].curveToReversed borderArgs else borderArgs.push [ 'line' borderData.c4[0] borderData.c4[1] ] borderArgs calculateCurvePoints = (bounds, borderRadius, borders) -> x = bounds.left y = bounds.top width = bounds.width height = bounds.height tlh = borderRadius[0][0] tlv = borderRadius[0][1] trh = borderRadius[1][0] trv = borderRadius[1][1] brh = borderRadius[2][0] brv = borderRadius[2][1] blh = borderRadius[3][0] blv = borderRadius[3][1] topWidth = width - trh rightHeight = height - brv bottomWidth = width - brh leftHeight = height - blv { topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5) topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - (borders[3].width)), Math.max(0, tlv - (borders[0].width))).topLeft.subdivide(0.5) topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5) topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (if topWidth > width + borders[3].width then 0 else trh - (borders[3].width)), trv - (borders[0].width)).topRight.subdivide(0.5) bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5) bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width + borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - (borders[1].width)), Math.max(0, brv - (borders[2].width))).bottomRight.subdivide(0.5) bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5) bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - (borders[3].width)), Math.max(0, blv - (borders[2].width))).bottomLeft.subdivide(0.5) } getBorderClip = (element, borderPoints, borders, radius, bounds) -> backgroundClip = getCSS(element, 'backgroundClip') borderArgs = [] switch backgroundClip when 'content-box', 'padding-box' parseCorner borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width parseCorner borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - (borders[1].width), bounds.top + borders[0].width parseCorner borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - (borders[1].width), bounds.top + bounds.height - (borders[2].width) parseCorner borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - (borders[2].width) else parseCorner borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top parseCorner borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top parseCorner borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height parseCorner borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height break borderArgs parseBorders = (element, bounds, borders) -> x = bounds.left y = bounds.top width = bounds.width height = bounds.height borderSide = undefined bx = undefined borderY = undefined bw = undefined bh = undefined borderArgs = undefined borderRadius = getBorderRadiusData(element) borderPoints = calculateCurvePoints(bounds, borderRadius, borders) borderData = clip: getBorderClip(element, borderPoints, borders, borderRadius, bounds) borders: [] borderSide = 0 while borderSide < 4 if borders[borderSide].width > 0 bx = x borderY = y bw = width bh = height - (borders[2].width) switch borderSide when 0 # top border bh = borders[0].width borderArgs = drawSide({ c1: [ bx borderY ] c2: [ bx + bw borderY ] c3: [ bx + bw - (borders[1].width) borderY + bh ] c4: [ bx + borders[3].width borderY + bh ] }, borderRadius[0], borderRadius[1], borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner) when 1 # right border bx = x + width - (borders[1].width) bw = borders[1].width borderArgs = drawSide({ c1: [ bx + bw borderY ] c2: [ bx + bw borderY + bh + borders[2].width ] c3: [ bx borderY + bh ] c4: [ bx borderY + borders[0].width ] }, borderRadius[1], borderRadius[2], borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner) when 2 # bottom border borderY = borderY + height - (borders[2].width) bh = borders[2].width borderArgs = drawSide({ c1: [ bx + bw borderY + bh ] c2: [ bx borderY + bh ] c3: [ bx + borders[3].width borderY ] c4: [ bx + bw - (borders[3].width) borderY ] }, borderRadius[2], borderRadius[3], borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner) when 3 # left border bw = borders[3].width borderArgs = drawSide({ c1: [ bx borderY + bh + borders[2].width ] c2: [ bx borderY ] c3: [ bx + bw borderY + borders[0].width ] c4: [ bx + bw borderY + bh ] }, borderRadius[3], borderRadius[0], borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner) borderData.borders.push args: borderArgs color: borders[borderSide].color borderSide++ borderData createShape = (ctx, args) -> shape = ctx.drawShape() args.forEach (border, index) -> shape[if index is 0 then 'moveTo' else border[0] + 'To'].apply null, border.slice(1) return shape renderBorders = (ctx, borderArgs, color) -> if color isnt 'transparent' ctx.setVariable 'fillStyle', color createShape ctx, borderArgs ctx.fill() numDraws += 1 return renderFormValue = (el, bounds, stack) -> valueWrap = doc.createElement('valuewrap') cssPropertyArray = [ 'lineHeight' 'textAlign' 'fontFamily' 'color' 'fontSize' 'paddingLeft' 'paddingTop' 'width' 'height' 'border' 'borderLeftWidth' 'borderTopWidth' ] textValue = undefined textNode = undefined cssPropertyArray.forEach (property) -> try valueWrap.style[property] = getCSS(el, property) catch e # Older IE has issues with "border" Util.log 'html2canvas: Parse: Exception caught in renderFormValue: ' + e.message return valueWrap.style.borderColor = 'black' valueWrap.style.borderStyle = 'solid' valueWrap.style.display = 'block' valueWrap.style.position = 'absolute' if /^(submit|reset|button|text|password)$/.test(el.type) or el.nodeName is 'SELECT' valueWrap.style.lineHeight = getCSS(el, 'height') valueWrap.style.top = bounds.top + 'px' valueWrap.style.left = bounds.left + 'px' textValue = if el.nodeName is 'SELECT' then (el.options[el.selectedIndex] or 0).text else el.value if not textValue textValue = el.placeholder textNode = doc.createTextNode(textValue) valueWrap.appendChild textNode body.appendChild valueWrap renderText el, textNode, stack body.removeChild valueWrap return drawImage = (ctx) -> ctx.drawImage.apply ctx, Array::slice.call(arguments, 1) numDraws += 1 return getPseudoElement = (el, which) -> elStyle = window.getComputedStyle(el, which) if not elStyle or not elStyle.content or elStyle.content is 'none' or elStyle.content is '-moz-alt-content' or elStyle.display is 'none' return content = elStyle.content + '' first = content.substr(0, 1) #strips quotes if first is content.substr(content.length - 1) and first.match(/'|"/) content = content.substr(1, content.length - 2) isImage = content.substr(0, 3) is 'url' elps = document.createElement(if isImage then 'img' else 'span') elps.className = pseudoHide + '-before ' + pseudoHide + '-after' Object.keys(elStyle).filter(indexedProperty).forEach (prop) -> # Prevent assigning of read only CSS Rules, ex. length, parentRule try elps.style[prop] = elStyle[prop] catch e Util.log [ 'Tried to assign readonly property ' prop 'Error:' e ] return if isImage elps.src = Util.parseBackgroundImage(content)[0].args[0] else elps.innerHTML = content elps indexedProperty = (property) -> isNaN window.parseInt(property, 10) injectPseudoElements = (el, stack) -> before = getPseudoElement(el, ':before') after = getPseudoElement(el, ':after') if not before and not after return if before el.className += ' ' + pseudoHide + '-before' el.parentNode.insertBefore before, el parseElement before, stack, true el.parentNode.removeChild before el.className = el.className.replace(pseudoHide + '-before', '').trim() if after el.className += ' ' + pseudoHide + '-after' el.appendChild after parseElement after, stack, true el.removeChild after el.className = el.className.replace(pseudoHide + '-after', '').trim() return renderBackgroundRepeat = (ctx, image, backgroundPosition, bounds) -> offsetX = Math.round(bounds.left + backgroundPosition.left) offsetY = Math.round(bounds.top + backgroundPosition.top) ctx.createPattern image ctx.translate offsetX, offsetY ctx.fill() ctx.translate -offsetX, -offsetY return backgroundRepeatShape = (ctx, image, backgroundPosition, bounds, left, top, width, height) -> args = [] args.push [ 'line' Math.round(left) Math.round(top) ] args.push [ 'line' Math.round(left + width) Math.round(top) ] args.push [ 'line' Math.round(left + width) Math.round(height + top) ] args.push [ 'line' Math.round(left) Math.round(height + top) ] createShape ctx, args ctx.save() ctx.clip() renderBackgroundRepeat ctx, image, backgroundPosition, bounds ctx.restore() return renderBackgroundColor = (ctx, backgroundBounds, bgcolor) -> renderRect ctx, backgroundBounds.left, backgroundBounds.top, backgroundBounds.width, backgroundBounds.height, bgcolor return renderBackgroundRepeating = (el, bounds, ctx, image, imageIndex) -> backgroundSize = Util.BackgroundSize(el, bounds, image, imageIndex) backgroundPosition = Util.BackgroundPosition(el, bounds, image, imageIndex, backgroundSize) backgroundRepeat = getCSS(el, 'backgroundRepeat').split(',').map(Util.trimText) image = resizeImage(image, backgroundSize) backgroundRepeat = backgroundRepeat[imageIndex] or backgroundRepeat[0] switch backgroundRepeat when 'repeat-x' backgroundRepeatShape ctx, image, backgroundPosition, bounds, bounds.left, bounds.top + backgroundPosition.top, 99999, image.height when 'repeat-y' backgroundRepeatShape ctx, image, backgroundPosition, bounds, bounds.left + backgroundPosition.left, bounds.top, image.width, 99999 when 'no-repeat' backgroundRepeatShape ctx, image, backgroundPosition, bounds, bounds.left + backgroundPosition.left, bounds.top + backgroundPosition.top, image.width, image.height else renderBackgroundRepeat ctx, image, backgroundPosition, top: bounds.top left: bounds.left width: image.width height: image.height break return renderBackgroundImage = (element, bounds, ctx) -> backgroundImage = getCSS(element, 'backgroundImage') backgroundImages = Util.parseBackgroundImage(backgroundImage) image = undefined imageIndex = backgroundImages.length while imageIndex-- backgroundImage = backgroundImages[imageIndex] if not backgroundImage.args or backgroundImage.args.length is 0 borderSide++ continue key = if backgroundImage.method is 'url' then backgroundImage.args[0] else backgroundImage.value image = loadImage(key) # TODO add support for background-origin if image renderBackgroundRepeating element, bounds, ctx, image, imageIndex else Util.log 'html2canvas: Error loading background:', backgroundImage return resizeImage = (image, bounds) -> if image.width is bounds.width and image.height is bounds.height return image ctx = undefined canvas = doc.createElement('canvas') canvas.width = bounds.width canvas.height = bounds.height ctx = canvas.getContext('2d') drawImage ctx, image, 0, 0, image.width, image.height, 0, 0, bounds.width, bounds.height canvas setOpacity = (ctx, element, parentStack) -> ctx.setVariable 'globalAlpha', getCSS(element, 'opacity') * (if parentStack then parentStack.opacity else 1) removePx = (str) -> str.replace 'px', '' getTransform = (element, parentStack) -> transform = getCSS(element, 'transform') or getCSS(element, '-webkit-transform') or getCSS(element, '-moz-transform') or getCSS(element, '-ms-transform') or getCSS(element, '-o-transform') transformOrigin = getCSS(element, 'transform-origin') or getCSS(element, '-webkit-transform-origin') or getCSS(element, '-moz-transform-origin') or getCSS(element, '-ms-transform-origin') or getCSS(element, '-o-transform-origin') or '0px 0px' transformOrigin = transformOrigin.split(' ').map(removePx).map(Util.asFloat) matrix = undefined if transform and transform isnt 'none' match = transform.match(transformRegExp) if match switch match[1] when 'matrix' matrix = match[2].split(',').map(Util.trimText).map(Util.asFloat) { origin: transformOrigin matrix: matrix } createStack = (element, parentStack, bounds, transform) -> ctx = h2cRenderContext((if not parentStack then documentWidth() else bounds.width), (if not parentStack then documentHeight() else bounds.height)) stack = ctx: ctx opacity: setOpacity(ctx, element, parentStack) cssPosition: getCSS(element, 'position') borders: getBorderData(element) transform: transform clip: if parentStack and parentStack.clip then Util.Extend({}, parentStack.clip) else null setZ element, stack, parentStack # TODO correct overflow for absolute content residing under a static position if options.useOverflow is true and /(hidden|scroll|auto)/.test(getCSS(element, 'overflow')) is true and /(BODY)/i.test(element.nodeName) is false stack.clip = if stack.clip then clipBounds(stack.clip, bounds) else bounds stack getBackgroundBounds = (borders, bounds, clip) -> backgroundBounds = left: bounds.left + borders[3].width top: bounds.top + borders[0].width width: bounds.width - (borders[1].width + borders[3].width) height: bounds.height - (borders[0].width + borders[2].width) if clip backgroundBounds = clipBounds(backgroundBounds, clip) backgroundBounds getBounds = (element, transform) -> bounds = if transform.matrix then Util.OffsetBounds(element) else Util.Bounds(element) transform.origin[0] += bounds.left transform.origin[1] += bounds.top bounds renderElement = (element, parentStack, pseudoElement, ignoreBackground) -> transform = getTransform(element, parentStack) bounds = getBounds(element, transform) image = undefined stack = createStack(element, parentStack, bounds, transform) borders = stack.borders ctx = stack.ctx backgroundBounds = getBackgroundBounds(borders, bounds, stack.clip) borderData = parseBorders(element, bounds, borders) backgroundColor = if ignoreElementsRegExp.test(element.nodeName) then '#efefef' else getCSS(element, 'backgroundColor') createShape ctx, borderData.clip ctx.save() ctx.clip() if backgroundBounds.height > 0 and backgroundBounds.width > 0 and not ignoreBackground renderBackgroundColor ctx, bounds, backgroundColor renderBackgroundImage element, backgroundBounds, ctx else if ignoreBackground stack.backgroundColor = backgroundColor ctx.restore() borderData.borders.forEach (border) -> renderBorders ctx, border.args, border.color return if not pseudoElement injectPseudoElements element, stack switch element.nodeName when 'IMG' if image = loadImage(element.getAttribute('src')) renderImage ctx, element, image, bounds, borders else Util.log 'html2canvas: Error loading <img>:' + element.getAttribute('src') when 'INPUT' # TODO add all relevant type's, i.e. HTML5 new stuff # todo add support for placeholder attribute for browsers which support it if /^(text|url|email|submit|button|reset)$/.test(element.type) and (element.value or element.placeholder or '').length > 0 renderFormValue element, bounds, stack when 'TEXTAREA' if (element.value or element.placeholder or '').length > 0 renderFormValue element, bounds, stack when 'SELECT' if (element.options or element.placeholder or '').length > 0 renderFormValue element, bounds, stack when 'LI' renderListItem element, stack, backgroundBounds when 'CANVAS' renderImage ctx, element, element, bounds, borders stack isElementVisible = (element) -> getCSS(element, 'display') isnt 'none' and getCSS(element, 'visibility') isnt 'hidden' and not element.hasAttribute('data-html2canvas-ignore') parseElement = (element, stack, pseudoElement) -> if isElementVisible(element) stack = renderElement(element, stack, pseudoElement, false) or stack if not ignoreElementsRegExp.test(element.nodeName) parseChildren element, stack, pseudoElement return parseChildren = (element, stack, pseudoElement) -> Util.Children(element).forEach (node) -> if node.nodeType is node.ELEMENT_NODE parseElement node, stack, pseudoElement else if node.nodeType is node.TEXT_NODE renderText element, node, stack return return init = -> background = getCSS(document.documentElement, 'backgroundColor') transparentBackground = Util.isTransparent(background) and element is document.body stack = renderElement(element, null, false, transparentBackground) parseChildren element, stack if transparentBackground background = stack.backgroundColor body.removeChild hidePseudoElements { backgroundColor: background stack: stack } window.scroll 0, 0 element = if options.elements is undefined then document.body else options.elements[0] numDraws = 0 doc = element.ownerDocument Util = _html2canvas.Util support = Util.Support(options, doc) ignoreElementsRegExp = new RegExp('(' + options.ignoreElements + ')') body = doc.body getCSS = Util.getCSS pseudoHide = '___html2canvas___pseudoelement' hidePseudoElements = doc.createElement('style') hidePseudoElements.innerHTML = '.' + pseudoHide + '-before:before { content: "" !important; display: none !important; }' + '.' + pseudoHide + '-after:after { content: "" !important; display: none !important; }' body.appendChild hidePseudoElements images = images or {} getCurvePoints = ((kappa) -> (x, y, r1, r2) -> ox = r1 * kappa oy = r2 * kappa xm = x + r1 ym = y + r2 # y-middle { topLeft: bezierCurve({ x: x y: ym }, { x: x y: ym - oy }, { x: xm - ox y: y }, x: xm y: y) topRight: bezierCurve({ x: x y: y }, { x: x + ox y: y }, { x: xm y: ym - oy }, x: xm y: ym) bottomRight: bezierCurve({ x: xm y: y }, { x: xm y: y + oy }, { x: x + ox y: ym }, x: x y: ym) bottomLeft: bezierCurve({ x: xm y: ym }, { x: xm - ox y: ym }, { x: x y: y + oy }, x: x y: y) } )(4 * (Math.sqrt(2) - 1) / 3) transformRegExp = /(matrix)\((.+)\)/ init() _html2canvas.Preload = (options) -> images = numLoaded: 0 numFailed: 0 numTotal: 0 cleanupDone: false pageOrigin = undefined Util = _html2canvas.Util methods = undefined i = undefined count = 0 element = options.elements[0] or document.body doc = element.ownerDocument domImages = element.getElementsByTagName('img') imgLen = domImages.length link = doc.createElement('a') supportCORS = ((img) -> img.crossOrigin isnt undefined )(new Image) timeoutTimer = undefined isSameOrigin = (url) -> link.href = url link.href = link.href # YES, BELIEVE IT OR NOT, that is required for IE9 - http://jsfiddle.net/niklasvh/2e48b/ origin = link.protocol + link.host origin is pageOrigin start = -> Util.log 'html2canvas: start: images: ' + images.numLoaded + ' / ' + images.numTotal + ' (failed: ' + images.numFailed + ')' if not images.firstRun and images.numLoaded >= images.numTotal Util.log 'Finished loading images: # ' + images.numTotal + ' (failed: ' + images.numFailed + ')' if typeof options.complete is 'function' options.complete images return # TODO modify proxy to serve images with CORS enabled, where available proxyGetImage = (url, img, imageObj) -> callback_name = undefined scriptUrl = options.proxy script = undefined link.href = url url = link.href # work around for pages with base href="" set - WARNING: this may change the url callback_name = 'html2canvas_' + count++ imageObj.callbackname = callback_name if scriptUrl.indexOf('?') > -1 scriptUrl += '&' else scriptUrl += '?' scriptUrl += 'url=' + encodeURIComponent(url) + '&callback=' + callback_name script = doc.createElement('script') window[callback_name] = (a) -> if a.substring(0, 6) is 'error:' imageObj.succeeded = false images.numLoaded++ images.numFailed++ start() else setImageLoadHandlers img, imageObj img.src = a window[callback_name] = undefined # to work with IE<9 // NOTE: that the undefined callback property-name still exists on the window object (for IE<9) try delete window[callback_name] # for all browser that support this catch ex script.parentNode.removeChild script script = null delete imageObj.script delete imageObj.callbackname return script.setAttribute 'type', 'text/javascript' script.setAttribute 'src', scriptUrl imageObj.script = script window.document.body.appendChild script return loadPseudoElement = (element, type) -> style = window.getComputedStyle(element, type) content = style.content if content.substr(0, 3) is 'url' methods.loadImage _html2canvas.Util.parseBackgroundImage(content)[0].args[0] loadBackgroundImages style.backgroundImage, element return loadPseudoElementImages = (element) -> loadPseudoElement element, ':before' loadPseudoElement element, ':after' return loadGradientImage = (backgroundImage, bounds) -> img = _html2canvas.Generate.Gradient(backgroundImage, bounds) if img isnt undefined images[backgroundImage] = img: img succeeded: true images.numTotal++ images.numLoaded++ start() return invalidBackgrounds = (background_image) -> background_image and background_image.method and background_image.args and background_image.args.length > 0 loadBackgroundImages = (background_image, el) -> bounds = undefined _html2canvas.Util.parseBackgroundImage(background_image).filter(invalidBackgrounds).forEach (background_image) -> if background_image.method is 'url' methods.loadImage background_image.args[0] else if background_image.method.match(/\-?gradient$/) if bounds is undefined bounds = _html2canvas.Util.Bounds(el) loadGradientImage background_image.value, bounds return return getImages = (el) -> elNodeType = false # Firefox fails with permission denied on pages with iframes try Util.Children(el).forEach getImages catch e try elNodeType = el.nodeType catch ex elNodeType = false Util.log 'html2canvas: failed to access some element\'s nodeType - Exception: ' + ex.message if elNodeType is 1 or elNodeType is undefined loadPseudoElementImages el try loadBackgroundImages Util.getCSS(el, 'backgroundImage'), el catch e Util.log 'html2canvas: failed to get background-image - Exception: ' + e.message loadBackgroundImages el return setImageLoadHandlers = (img, imageObj) -> img.onload = -> if imageObj.timer isnt undefined # CORS succeeded window.clearTimeout imageObj.timer images.numLoaded++ imageObj.succeeded = true img.onerror = img.onload = null start() return img.onerror = -> if img.crossOrigin is 'anonymous' # CORS failed window.clearTimeout imageObj.timer # let's try with proxy instead if options.proxy src = img.src img = new Image imageObj.img = img img.src = src proxyGetImage img.src, img, imageObj return images.numLoaded++ images.numFailed++ imageObj.succeeded = false img.onerror = img.onload = null start() return return link.href = window.location.href pageOrigin = link.protocol + link.host methods = loadImage: (src) -> img = undefined imageObj = undefined if src and images[src] is undefined img = new Image if src.match(/data:image\/.*;base64,/i) img.src = src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, '') imageObj = images[src] = img: img images.numTotal++ setImageLoadHandlers img, imageObj else if isSameOrigin(src) or options.allowTaint is true imageObj = images[src] = img: img images.numTotal++ setImageLoadHandlers img, imageObj img.src = src else if supportCORS and not options.allowTaint and options.useCORS # attempt to load with CORS img.crossOrigin = 'anonymous' imageObj = images[src] = img: img images.numTotal++ setImageLoadHandlers img, imageObj img.src = src else if options.proxy imageObj = images[src] = img: img images.numTotal++ proxyGetImage src, img, imageObj return cleanupDOM: (cause) -> img = undefined src = undefined if not images.cleanupDone if cause and typeof cause is 'string' Util.log 'html2canvas: Cleanup because: ' + cause else Util.log 'html2canvas: Cleanup after timeout: ' + options.timeout + ' ms.' for src in images # `src = src` if images.hasOwnProperty(src) img = images[src] if typeof img is 'object' and img.callbackname and img.succeeded is undefined # cancel proxy image request window[img.callbackname] = undefined # to work with IE<9 // NOTE: that the undefined callback property-name still exists on the window object (for IE<9) try delete window[img.callbackname] # for all browser that support this catch ex if img.script and img.script.parentNode img.script.setAttribute 'src', 'about:blank' # try to cancel running request img.script.parentNode.removeChild img.script images.numLoaded++ images.numFailed++ Util.log 'html2canvas: Cleaned up failed img: \'' + src + '\' Steps: ' + images.numLoaded + ' / ' + images.numTotal # cancel any pending requests if window.stop isnt undefined window.stop() else if document.execCommand isnt undefined document.execCommand 'Stop', false if document.close isnt undefined document.close() images.cleanupDone = true if not (cause and typeof cause is 'string') start() return renderingDone: -> if timeoutTimer window.clearTimeout timeoutTimer return if options.timeout > 0 timeoutTimer = window.setTimeout(methods.cleanupDOM, options.timeout) Util.log 'html2canvas: Preload starts: finding background-images' images.firstRun = true getImages element Util.log 'html2canvas: Preload: Finding images' # load <img> images i = 0 while i < imgLen methods.loadImage domImages[i].getAttribute('src') i += 1 images.firstRun = false Util.log 'html2canvas: Preload: Done.' if images.numTotal is images.numLoaded start() methods _html2canvas.Renderer = (parseQueue, options) -> # http://www.w3.org/TR/CSS21/zindex.html createRenderQueue = (parseQueue) -> queue = [] rootContext = undefined sortZ = (context) -> Object.keys(context).sort().forEach (zi) -> nonPositioned = [] floated = [] positioned = [] list = [] # positioned after static context[zi].forEach (v) -> if v.node.zIndex.isPositioned or v.node.zIndex.opacity < 1 # http://www.w3.org/TR/css3-color/#transparency # non-positioned element with opactiy < 1 should be stacked as if it were a positioned element with ‘z-index: 0’ and ‘opacity: 1’. positioned.push v else if v.node.zIndex.isFloated floated.push v else nonPositioned.push v return do walk = (arr = nonPositioned.concat(floated, positioned)) -> arr.forEach (v) -> list.push v if v.children walk v.children return return list.forEach (v) -> if v.context sortZ v.context else queue.push v.node return return return rootContext = ((rootNode) -> # `var rootContext` irootContext = {} insert = (context, node, specialParent) -> zi = if node.zIndex.zindex is 'auto' then 0 else Number(node.zIndex.zindex) contextForChildren = context isPositioned = node.zIndex.isPositioned isFloated = node.zIndex.isFloated stub = node: node childrenDest = specialParent # where children without z-index should be pushed into if node.zIndex.ownStacking # '!' comes before numbers in sorted array contextForChildren = stub.context = '!': [ { node: node children: [] } ] childrenDest = undefined else if isPositioned or isFloated childrenDest = stub.children = [] if zi is 0 and specialParent specialParent.push stub else if not context[zi] context[zi] = [] context[zi].push stub node.zIndex.children.forEach (childNode) -> insert contextForChildren, childNode, childrenDest return return insert irootContext, rootNode irootContext )(parseQueue) sortZ rootContext queue getRenderer = (rendererName) -> renderer = undefined if typeof options.renderer is 'string' and _html2canvas.Renderer[rendererName] isnt undefined renderer = _html2canvas.Renderer[rendererName](options) else if typeof rendererName is 'function' renderer = rendererName(options) else throw new Error('Unknown renderer') if typeof renderer isnt 'function' throw new Error('Invalid renderer defined') renderer getRenderer(options.renderer) parseQueue, options, document, createRenderQueue(parseQueue.stack), _html2canvas _html2canvas.Util.Support = (options, doc) -> supportSVGRendering = -> img = new Image canvas = doc.createElement('canvas') ctx = if canvas.getContext is undefined then false else canvas.getContext('2d') if ctx is false return false canvas.width = canvas.height = 10 img.src = [ 'data:image/svg+xml,' '<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'10\' height=\'10\'>' '<foreignObject width=\'10\' height=\'10\'>' '<div xmlns=\'http://www.w3.org/1999/xhtml\' style=\'width:10;height:10;\'>' 'sup' '</div>' '</foreignObject>' '</svg>' ].join('') try ctx.drawImage img, 0, 0 canvas.toDataURL() catch e return false _html2canvas.Util.log 'html2canvas: Parse: SVG powered rendering available' true # Test whether we can use ranges to measure bounding boxes # Opera doesn't provide valid bounds.height/bottom even though it supports the method. supportRangeBounds = -> r = undefined testElement = undefined rangeBounds = undefined rangeHeight = undefined support = false if doc.createRange r = doc.createRange() if r.getBoundingClientRect testElement = doc.createElement('boundtest') testElement.style.height = '123px' testElement.style.display = 'block' doc.body.appendChild testElement r.selectNode testElement rangeBounds = r.getBoundingClientRect() rangeHeight = rangeBounds.height if rangeHeight is 123 support = true doc.body.removeChild testElement support { rangeBounds: supportRangeBounds() svgRendering: options.svgRendering and supportSVGRendering() } window.html2canvas = (elements, opts) -> elements = if elements.length then elements else [ elements ] queue = undefined canvas = undefined options = logging: false elements: elements background: '#fff' proxy: null timeout: 0 useCORS: false allowTaint: false svgRendering: false ignoreElements: 'IFRAME|OBJECT|PARAM' useOverflow: true letterRendering: false chinese: false width: null height: null taintTest: true renderer: 'Canvas' options = _html2canvas.Util.Extend(opts, options) _html2canvas.logging = options.logging options.complete = (images) -> if typeof options.onpreloaded is 'function' if options.onpreloaded(images) is false return queue = _html2canvas.Parse(images, options) if typeof options.onparsed is 'function' if options.onparsed(queue) is false return canvas = _html2canvas.Renderer(queue, options) if typeof options.onrendered is 'function' options.onrendered canvas return # for pages without images, we still want this to be async, i.e. return methods before executing window.setTimeout (-> _html2canvas.Preload options return ), 0 { render: (queue, opts) -> _html2canvas.Renderer queue, _html2canvas.Util.Extend(opts, options) parse: (images, opts) -> _html2canvas.Parse images, _html2canvas.Util.Extend(opts, options) preload: (opts) -> _html2canvas.Preload _html2canvas.Util.Extend(opts, options) log: _html2canvas.Util.log } window.html2canvas.log = _html2canvas.Util.log # for renderers window.html2canvas.Renderer = Canvas: undefined _html2canvas.Renderer.Canvas = (options) -> createShape = (ctx, args) -> ctx.beginPath() args.forEach (arg) -> ctx[arg.name].apply ctx, arg['arguments'] return ctx.closePath() return safeImage = (item) -> if safeImages.indexOf(item['arguments'][0].src) is -1 testctx.drawImage item['arguments'][0], 0, 0 try testctx.getImageData 0, 0, 1, 1 catch e testCanvas = doc.createElement('canvas') testctx = testCanvas.getContext('2d') return false safeImages.push item['arguments'][0].src true renderItem = (ctx, item) -> switch item.type when 'variable' ctx[item.name] = item['arguments'] when 'function' switch item.name when 'createPattern' if item['arguments'][0].width > 0 and item['arguments'][0].height > 0 try ctx.fillStyle = ctx.createPattern(item['arguments'][0], 'repeat') catch e Util.log 'html2canvas: Renderer: Error creating pattern', e.message when 'drawShape' createShape ctx, item['arguments'] when 'drawImage' if item['arguments'][8] > 0 and item['arguments'][7] > 0 if not options.taintTest or options.taintTest and safeImage(item) ctx.drawImage.apply ctx, item['arguments'] else ctx[item.name].apply ctx, item['arguments'] return options = options or {} doc = document safeImages = [] testCanvas = document.createElement('canvas') testctx = testCanvas.getContext('2d') Util = _html2canvas.Util canvas = options.canvas or doc.createElement('canvas') (parsedData, options, document, queue, _html2canvas) -> ctx = canvas.getContext('2d') newCanvas = undefined bounds = undefined fstyle = undefined zStack = parsedData.stack canvas.width = canvas.style.width = options.width or zStack.ctx.width canvas.height = canvas.style.height = options.height or zStack.ctx.height fstyle = ctx.fillStyle ctx.fillStyle = if Util.isTransparent(zStack.backgroundColor) and options.background isnt undefined then options.background else parsedData.backgroundColor ctx.fillRect 0, 0, canvas.width, canvas.height ctx.fillStyle = fstyle queue.forEach (storageContext) -> # set common settings for canvas ctx.textBaseline = 'bottom' ctx.save() if storageContext.transform.matrix ctx.translate storageContext.transform.origin[0], storageContext.transform.origin[1] ctx.transform.apply ctx, storageContext.transform.matrix ctx.translate -storageContext.transform.origin[0], -storageContext.transform.origin[1] if storageContext.clip ctx.beginPath() ctx.rect storageContext.clip.left, storageContext.clip.top, storageContext.clip.width, storageContext.clip.height ctx.clip() if storageContext.ctx.storage storageContext.ctx.storage.forEach (item) -> renderItem ctx, item return ctx.restore() return Util.log 'html2canvas: Renderer: Canvas renderer done - returning canvas obj' if options.elements.length is 1 if typeof options.elements[0] is 'object' and options.elements[0].nodeName isnt 'BODY' # crop image to the bounds of selected (single) element bounds = _html2canvas.Util.Bounds(options.elements[0]) newCanvas = document.createElement('canvas') newCanvas.width = Math.ceil(bounds.width) newCanvas.height = Math.ceil(bounds.height) ctx = newCanvas.getContext('2d') ctx.drawImage canvas, bounds.left, bounds.top, bounds.width, bounds.height, 0, 0, bounds.width, bounds.height canvas = null return newCanvas canvas return ) window, document module.exports = window.html2canvas
true
### html2canvas 0.4.1 <http://html2canvas.hertzen.com> Copyright (c) 2013 PI:NAME:<NAME>END_PI Released under MIT License ### ((window, document) -> # global variables borderSide = undefined toPX = (element, attribute, value) -> rsLeft = element.runtimeStyle and element.runtimeStyle[attribute] left = undefined style = element.style # Check if we are not dealing with pixels, (Opera has issues with this) # Ported from jQuery css.js # From the awesome hack by PI:NAME:<NAME>END_PI # http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 # If we're not dealing with a regular pixel number # but a number that has a weird ending, we need to convert it to pixels if not /^-?[0-9]+\.?[0-9]*(?:px)?$/i.test(value) and /^-?\d/.test(value) # Remember the original values left = style.left # Put in the new values to get a computed value out if rsLeft element.runtimeStyle.left = element.currentStyle.left style.left = if attribute is 'fontSize' then '1em' else value or 0 value = style.pixelLeft + 'px' # Revert the changed values style.left = left if rsLeft element.runtimeStyle.left = rsLeft if not /^(thin|medium|thick)$/i.test(value) return Math.round(parseFloat(value)) + 'px' value asInt = (val) -> parseInt val, 10 parseBackgroundSizePosition = (value, element, attribute, index) -> value = (value or '').split(',') value = value[index or 0] or value[0] or 'auto' value = _html2canvas.Util.trimText(value).split(' ') if attribute is 'backgroundSize' and (not value[0] or value[0].match(/cover|contain|auto/)) #these values will be handled in the parent function else value[0] = if value[0].indexOf('%') is -1 then toPX(element, attribute + 'X', value[0]) else value[0] if value[1] is undefined if attribute is 'backgroundSize' value[1] = 'auto' return value else # IE 9 doesn't return double digit always value[1] = value[0] value[1] = if value[1].indexOf('%') is -1 then toPX(element, attribute + 'Y', value[1]) else value[1] value backgroundBoundsFactory = (prop, el, bounds, image, imageIndex, backgroundSize) -> bgposition = _html2canvas.Util.getCSS(el, prop, imageIndex) topPos = undefined left = undefined percentage = undefined val = undefined if bgposition.length is 1 val = bgposition[0] bgposition = [] bgposition[0] = val bgposition[1] = val if bgposition[0].toString().indexOf('%') isnt -1 percentage = parseFloat(bgposition[0]) / 100 left = bounds.width * percentage if prop isnt 'backgroundSize' left -= (backgroundSize or image).width * percentage else if prop is 'backgroundSize' if bgposition[0] is 'auto' left = image.width else if /contain|cover/.test(bgposition[0]) resized = _html2canvas.Util.resizeBounds(image.width, image.height, bounds.width, bounds.height, bgposition[0]) left = resized.width topPos = resized.height else left = parseInt(bgposition[0], 10) else left = parseInt(bgposition[0], 10) if bgposition[1] is 'auto' topPos = left / image.width * image.height else if bgposition[1].toString().indexOf('%') isnt -1 percentage = parseFloat(bgposition[1]) / 100 topPos = bounds.height * percentage if prop isnt 'backgroundSize' topPos -= (backgroundSize or image).height * percentage else topPos = parseInt(bgposition[1], 10) [ left topPos ] h2cRenderContext = (width, height) -> storage = [] { storage: storage width: width height: height clip: -> storage.push type: 'function' name: 'clip' 'arguments': arguments return translate: -> storage.push type: 'function' name: 'translate' 'arguments': arguments return fill: -> storage.push type: 'function' name: 'fill' 'arguments': arguments return save: -> storage.push type: 'function' name: 'save' 'arguments': arguments return restore: -> storage.push type: 'function' name: 'restore' 'arguments': arguments return fillRect: -> storage.push type: 'function' name: 'fillRect' 'arguments': arguments return createPattern: -> storage.push type: 'function' name: 'createPattern' 'arguments': arguments return drawShape: -> shape = [] storage.push type: 'function' name: 'drawShape' 'arguments': shape { moveTo: -> shape.push name: 'moveTo' 'arguments': arguments return lineTo: -> shape.push name: 'lineTo' 'arguments': arguments return arcTo: -> shape.push name: 'arcTo' 'arguments': arguments return bezierCurveTo: -> shape.push name: 'bezierCurveTo' 'arguments': arguments return quadraticCurveTo: -> shape.push name: 'quadraticCurveTo' 'arguments': arguments return } drawImage: -> storage.push type: 'function' name: 'drawImage' 'arguments': arguments return fillText: -> storage.push type: 'function' name: 'fillText' 'arguments': arguments return setVariable: (variable, value) -> storage.push type: 'variable' name: variable 'arguments': value value } h2czContext = (zindex) -> { zindex: zindex children: [] } 'use strict' _html2canvas = {} previousElement = undefined computedCSS = undefined html2canvas = undefined _html2canvas.Util = {} _html2canvas.Util.log = (a) -> if _html2canvas.logging and window.console and window.console.log window.console.log a return _html2canvas.Util.trimText = ((isNative) -> (input) -> if isNative then isNative.apply(input) else ((input or '') + '').replace(/^\s+|\s+$/g, '') )(String::trim) _html2canvas.Util.asFloat = (v) -> parseFloat v do -> # TODO: support all possible length values TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g _html2canvas.Util.parseTextShadows = (value) -> if not value or value is 'none' return [] # find multiple shadow declarations shadows = value.match(TEXT_SHADOW_PROPERTY) results = [] i = 0 while shadows and i < shadows.length s = shadows[i].match(TEXT_SHADOW_VALUES) results.push color: s[0] offsetX: if s[1] then s[1].replace('px', '') else 0 offsetY: if s[2] then s[2].replace('px', '') else 0 blur: if s[3] then s[3].replace('px', '') else 0 i++ results return _html2canvas.Util.parseBackgroundImage = (value) -> whitespace = ' \u000d\n\u0009' method = undefined definition = undefined prefix = undefined prefix_i = undefined block = undefined results = [] c = undefined mode = 0 numParen = 0 quote = undefined args = undefined appendResult = -> if method if definition.substr(0, 1) is '"' definition = definition.substr(1, definition.length - 2) if definition args.push definition if method.substr(0, 1) is '-' and (prefix_i = method.indexOf('-', 1) + 1) > 0 prefix = method.substr(0, prefix_i) method = method.substr(prefix_i) results.push prefix: prefix method: method.toLowerCase() value: block args: args args = [] #for some odd reason, setting .length = 0 didn't work in safari method = prefix = definition = block = '' return appendResult() i = 0 ii = value.length while i < ii c = value[i] if mode is 0 and whitespace.indexOf(c) > -1 i++ continue switch c when '"' if not quote quote = c else if quote is c quote = null when '(' if quote break else if mode is 0 mode = 1 block += c i++ continue else numParen++ when ')' if quote break else if mode is 1 if numParen is 0 mode = 0 block += c appendResult() i++ continue else numParen-- when ',' if quote break else if mode is 0 appendResult() i++ continue else if mode is 1 if numParen is 0 and not method.match(/^url$/i) args.push definition definition = '' block += c i++ continue block += c if mode is 0 method += c else definition += c i++ appendResult() results _html2canvas.Util.Bounds = (element) -> clientRect = undefined bounds = {} if element.getBoundingClientRect clientRect = element.getBoundingClientRect() # TODO add scroll position to bounds, so no scrolling of window necessary bounds.top = clientRect.top bounds.bottom = clientRect.bottom or clientRect.top + clientRect.height bounds.left = clientRect.left bounds.width = element.offsetWidth bounds.height = element.offsetHeight bounds # TODO ideally, we'd want everything to go through this function instead of Util.Bounds, # but would require further work to calculate the correct positions for elements with offsetParents _html2canvas.Util.OffsetBounds = (element) -> parent = if element.offsetParent then _html2canvas.Util.OffsetBounds(element.offsetParent) else top: 0 left: 0 { top: element.offsetTop + parent.top bottom: element.offsetTop + element.offsetHeight + parent.top left: element.offsetLeft + parent.left width: element.offsetWidth height: element.offsetHeight } _html2canvas.Util.getCSS = (element, attribute, index) -> if previousElement isnt element computedCSS = document.defaultView.getComputedStyle(element, null) value = computedCSS[attribute] if /^background(Size|Position)$/.test(attribute) return parseBackgroundSizePosition(value, element, attribute, index) else if /border(Top|Bottom)(Left|Right)Radius/.test(attribute) arr = value.split(' ') if arr.length <= 1 arr[1] = arr[0] return arr.map(asInt) value _html2canvas.Util.resizeBounds = (current_width, current_height, target_width, target_height, stretch_mode) -> target_ratio = target_width / target_height current_ratio = current_width / current_height output_width = undefined output_height = undefined if not stretch_mode or stretch_mode is 'auto' output_width = target_width output_height = target_height else if target_ratio < current_ratio ^ stretch_mode is 'contain' output_height = target_height output_width = target_height * current_ratio else output_width = target_width output_height = target_width / current_ratio { width: output_width height: output_height } _html2canvas.Util.BackgroundPosition = (el, bounds, image, imageIndex, backgroundSize) -> result = backgroundBoundsFactory('backgroundPosition', el, bounds, image, imageIndex, backgroundSize) { left: result[0] top: result[1] } _html2canvas.Util.BackgroundSize = (el, bounds, image, imageIndex) -> result = backgroundBoundsFactory('backgroundSize', el, bounds, image, imageIndex) { width: result[0] height: result[1] } _html2canvas.Util.Extend = (options, defaults) -> for key of options if options.hasOwnProperty(key) defaults[key] = options[key] defaults ### # Derived from jQuery.contents() # Copyright 2010, PI:NAME:<NAME>END_PI # Dual licensed under the MIT or GPL Version 2 licenses. # http://jquery.org/license ### _html2canvas.Util.Children = (elem) -> children = undefined try children = if elem.nodeName and elem.nodeName.toUpperCase() is 'IFRAME' then elem.contentDocument or elem.contentWindow.document else ((array) -> ret = [] if array isnt null ((first, second) -> i = first.length j = 0 if typeof second.length is 'number' l = second.length while j < l first[i++] = second[j] j++ else while second[j] isnt undefined first[i++] = second[j++] first.length = i first ) ret, array ret )(elem.childNodes) catch ex _html2canvas.Util.log 'html2canvas.Util.Children failed with exception: ' + ex.message children = [] children _html2canvas.Util.isTransparent = (backgroundColor) -> backgroundColor is 'transparent' or backgroundColor is 'rgba(0, 0, 0, 0)' _html2canvas.Util.Font = do -> fontData = {} (font, fontSize, doc) -> if fontData[font + '-' + fontSize] isnt undefined return fontData[font + '-' + fontSize] container = doc.createElement('div') img = doc.createElement('img') span = doc.createElement('span') sampleText = 'Hidden Text' baseline = undefined middle = undefined metricsObj = undefined container.style.visibility = 'hidden' container.style.fontFamily = font container.style.fontSize = fontSize container.style.margin = 0 container.style.padding = 0 doc.body.appendChild container # http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever (handtinywhite.gif) img.src = 'data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACwAAAAAAQABAAACAkQBADs=' img.width = 1 img.height = 1 img.style.margin = 0 img.style.padding = 0 img.style.verticalAlign = 'baseline' span.style.fontFamily = font span.style.fontSize = fontSize span.style.margin = 0 span.style.padding = 0 span.appendChild doc.createTextNode(sampleText) container.appendChild span container.appendChild img baseline = img.offsetTop - (span.offsetTop) + 1 container.removeChild span container.appendChild doc.createTextNode(sampleText) container.style.lineHeight = 'normal' img.style.verticalAlign = 'super' middle = img.offsetTop - (container.offsetTop) + 1 metricsObj = baseline: baseline lineWidth: 1 middle: middle fontData[font + '-' + fontSize] = metricsObj doc.body.removeChild container metricsObj do -> Util = _html2canvas.Util Generate = {} addScrollStops = (grad) -> (colorStop) -> try grad.addColorStop colorStop.stop, colorStop.color catch e Util.log [ 'failed to add color stop: ' e '; tried to add: ' colorStop ] return _html2canvas.Generate = Generate reGradients = [ /^(-webkit-linear-gradient)\(([a-z\s]+)([\w\d\.\s,%\(\)]+)\)$/ /^(-o-linear-gradient)\(([a-z\s]+)([\w\d\.\s,%\(\)]+)\)$/ /^(-webkit-gradient)\((linear|radial),\s((?:\d{1,3}%?)\s(?:\d{1,3}%?),\s(?:\d{1,3}%?)\s(?:\d{1,3}%?))([\w\d\.\s,%\(\)\-]+)\)$/ /^(-moz-linear-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?))([\w\d\.\s,%\(\)]+)\)$/ /^(-webkit-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s([a-z\-]+)([\w\d\.\s,%\(\)]+)\)$/ /^(-moz-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s?([a-z\-]*)([\w\d\.\s,%\(\)]+)\)$/ /^(-o-radial-gradient)\(((?:\d{1,3}%?)\s(?:\d{1,3}%?)),\s(\w+)\s([a-z\-]+)([\w\d\.\s,%\(\)]+)\)$/ ] ### # TODO: Add IE10 vendor prefix (-ms) support # TODO: Add W3C gradient (linear-gradient) support # TODO: Add old Webkit -webkit-gradient(radial, ...) support # TODO: Maybe some RegExp optimizations are possible ;o) ### Generate.parseGradient = (css, bounds) -> gradient = undefined i = undefined len = reGradients.length m1 = undefined stop = undefined m2 = undefined m2Len = undefined step = undefined m3 = undefined tl = undefined tr = undefined br = undefined bl = undefined i = 0 while i < len m1 = css.match(reGradients[i]) if m1 break i += 1 if m1 switch m1[1] when '-webkit-linear-gradient', '-o-linear-gradient' gradient = type: 'linear' x0: null y0: null x1: null y1: null colorStops: [] # get coordinates m2 = m1[2].match(/\w+/g) if m2 m2Len = m2.length i = 0 while i < m2Len switch m2[i] when 'top' gradient.y0 = 0 gradient.y1 = bounds.height when 'right' gradient.x0 = bounds.width gradient.x1 = 0 when 'bottom' gradient.y0 = bounds.height gradient.y1 = 0 when 'left' gradient.x0 = 0 gradient.x1 = bounds.width i += 1 if gradient.x0 is null and gradient.x1 is null # center gradient.x0 = gradient.x1 = bounds.width / 2 if gradient.y0 is null and gradient.y1 is null # center gradient.y0 = gradient.y1 = bounds.height / 2 # get colors and stops m2 = m1[3].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}(?:%|px))?)+/g) if m2 m2Len = m2.length step = 1 / Math.max(m2Len - 1, 1) i = 0 while i < m2Len m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/) if m3[2] stop = parseFloat(m3[2]) if m3[3] is '%' stop /= 100 else # px - stupid opera stop /= bounds.width else stop = i * step gradient.colorStops.push color: m3[1] stop: stop i += 1 when '-webkit-gradient' gradient = type: if m1[2] is 'radial' then 'circle' else m1[2] x0: 0 y0: 0 x1: 0 y1: 0 colorStops: [] # get coordinates m2 = m1[3].match(/(\d{1,3})%?\s(\d{1,3})%?,\s(\d{1,3})%?\s(\d{1,3})%?/) if m2 gradient.x0 = m2[1] * bounds.width / 100 gradient.y0 = m2[2] * bounds.height / 100 gradient.x1 = m2[3] * bounds.width / 100 gradient.y1 = m2[4] * bounds.height / 100 # get colors and stops m2 = m1[4].match(/((?:from|to|color-stop)\((?:[0-9\.]+,\s)?(?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)\))+/g) if m2 m2Len = m2.length i = 0 while i < m2Len m3 = m2[i].match(/(from|to|color-stop)\(([0-9\.]+)?(?:,\s)?((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\)/) stop = parseFloat(m3[2]) if m3[1] is 'from' stop = 0.0 if m3[1] is 'to' stop = 1.0 gradient.colorStops.push color: m3[3] stop: stop i += 1 when '-moz-linear-gradient' gradient = type: 'linear' x0: 0 y0: 0 x1: 0 y1: 0 colorStops: [] # get coordinates m2 = m1[2].match(/(\d{1,3})%?\s(\d{1,3})%?/) # m2[1] is 0% -> left # m2[1] is 50% -> center # m2[1] is 100% -> right # m2[2] is 0% -> top # m2[2] is 50% -> center # m2[2] is 100% -> bottom if m2 gradient.x0 = m2[1] * bounds.width / 100 gradient.y0 = m2[2] * bounds.height / 100 gradient.x1 = bounds.width - (gradient.x0) gradient.y1 = bounds.height - (gradient.y0) # get colors and stops m2 = m1[3].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}%)?)+/g) if m2 m2Len = m2.length step = 1 / Math.max(m2Len - 1, 1) i = 0 while i < m2Len m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%)?/) if m3[2] stop = parseFloat(m3[2]) if m3[3] # percentage stop /= 100 else stop = i * step gradient.colorStops.push color: m3[1] stop: stop i += 1 when '-webkit-radial-gradient', '-moz-radial-gradient', '-o-radial-gradient' gradient = type: 'circle' x0: 0 y0: 0 x1: bounds.width y1: bounds.height cx: 0 cy: 0 rx: 0 ry: 0 colorStops: [] # center m2 = m1[2].match(/(\d{1,3})%?\s(\d{1,3})%?/) if m2 gradient.cx = m2[1] * bounds.width / 100 gradient.cy = m2[2] * bounds.height / 100 # size m2 = m1[3].match(/\w+/) m3 = m1[4].match(/[a-z\-]*/) if m2 and m3 switch m3[0] # is equivalent to farthest-corner when 'farthest-corner', 'cover', '' # mozilla removes "cover" from definition :( tl = Math.sqrt(gradient.cx ** 2 + gradient.cy ** 2) tr = Math.sqrt(gradient.cx ** 2 + (gradient.y1 - (gradient.cy)) ** 2) br = Math.sqrt((gradient.x1 - (gradient.cx)) ** 2 + (gradient.y1 - (gradient.cy)) ** 2) bl = Math.sqrt((gradient.x1 - (gradient.cx)) ** 2 + gradient.cy ** 2) gradient.rx = gradient.ry = Math.max(tl, tr, br, bl) when 'closest-corner' tl = Math.sqrt(gradient.cx ** 2 + gradient.cy ** 2) tr = Math.sqrt(gradient.cx ** 2 + (gradient.y1 - (gradient.cy)) ** 2) br = Math.sqrt((gradient.x1 - (gradient.cx)) ** 2 + (gradient.y1 - (gradient.cy)) ** 2) bl = Math.sqrt((gradient.x1 - (gradient.cx)) ** 2 + gradient.cy ** 2) gradient.rx = gradient.ry = Math.min(tl, tr, br, bl) when 'farthest-side' if m2[0] is 'circle' gradient.rx = gradient.ry = Math.max(gradient.cx, gradient.cy, gradient.x1 - (gradient.cx), gradient.y1 - (gradient.cy)) else # ellipse gradient.type = m2[0] gradient.rx = Math.max(gradient.cx, gradient.x1 - (gradient.cx)) gradient.ry = Math.max(gradient.cy, gradient.y1 - (gradient.cy)) when 'closest-side', 'contain' # is equivalent to closest-side if m2[0] is 'circle' gradient.rx = gradient.ry = Math.min(gradient.cx, gradient.cy, gradient.x1 - (gradient.cx), gradient.y1 - (gradient.cy)) else # ellipse gradient.type = m2[0] gradient.rx = Math.min(gradient.cx, gradient.x1 - (gradient.cx)) gradient.ry = Math.min(gradient.cy, gradient.y1 - (gradient.cy)) # TODO: add support for "30px 40px" sizes (webkit only) # color stops m2 = m1[5].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)(?:\s\d{1,3}(?:%|px))?)+/g) if m2 m2Len = m2.length step = 1 / Math.max(m2Len - 1, 1) i = 0 while i < m2Len m3 = m2[i].match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/) if m3[2] stop = parseFloat(m3[2]) if m3[3] is '%' stop /= 100 else # px - stupid opera stop /= bounds.width else stop = i * step gradient.colorStops.push color: m3[1] stop: stop i += 1 gradient Generate.Gradient = (src, bounds) -> if bounds.width is 0 or bounds.height is 0 return canvas = document.createElement('canvas') ctx = canvas.getContext('2d') gradient = undefined grad = undefined canvas.width = bounds.width canvas.height = bounds.height # TODO: add support for multi defined background gradients gradient = _html2canvas.Generate.parseGradient(src, bounds) if gradient switch gradient.type when 'linear' grad = ctx.createLinearGradient(gradient.x0, gradient.y0, gradient.x1, gradient.y1) gradient.colorStops.forEach addScrollStops(grad) ctx.fillStyle = grad ctx.fillRect 0, 0, bounds.width, bounds.height when 'circle' grad = ctx.createRadialGradient(gradient.cx, gradient.cy, 0, gradient.cx, gradient.cy, gradient.rx) gradient.colorStops.forEach addScrollStops(grad) ctx.fillStyle = grad ctx.fillRect 0, 0, bounds.width, bounds.height when 'ellipse' canvasRadial = document.createElement('canvas') ctxRadial = canvasRadial.getContext('2d') ri = Math.max(gradient.rx, gradient.ry) di = ri * 2 canvasRadial.width = canvasRadial.height = di grad = ctxRadial.createRadialGradient(gradient.rx, gradient.ry, 0, gradient.rx, gradient.ry, ri) gradient.colorStops.forEach addScrollStops(grad) ctxRadial.fillStyle = grad ctxRadial.fillRect 0, 0, di, di ctx.fillStyle = gradient.colorStops[gradient.colorStops.length - 1].color ctx.fillRect 0, 0, canvas.width, canvas.height ctx.drawImage canvasRadial, gradient.cx - (gradient.rx), gradient.cy - (gradient.ry), 2 * gradient.rx, 2 * gradient.ry canvas Generate.ListAlpha = (number) -> tmp = '' modulus = undefined loop modulus = number % 26 tmp = String.fromCharCode(modulus + 64) + tmp number = number / 26 unless number * 26 > 26 break tmp Generate.ListRoman = (number) -> romanArray = [ 'M' 'CM' 'D' 'CD' 'C' 'XC' 'L' 'XL' 'X' 'IX' 'V' 'IV' 'I' ] decimal = [ 1000 900 500 400 100 90 50 40 10 9 5 4 1 ] roman = '' v = undefined len = romanArray.length if number <= 0 or number >= 4000 return number v = 0 while v < len while number >= decimal[v] number -= decimal[v] roman += romanArray[v] v += 1 roman return _html2canvas.Parse = (images, options) -> documentWidth = -> Math.max Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth), Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth), Math.max(doc.body.clientWidth, doc.documentElement.clientWidth) documentHeight = -> Math.max Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight), Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight), Math.max(doc.body.clientHeight, doc.documentElement.clientHeight) getCSSInt = (element, attribute) -> val = parseInt(getCSS(element, attribute), 10) if isNaN(val) then 0 else val # borders in old IE are throwing 'medium' for demo.html renderRect = (ctx, x, y, w, h, bgcolor) -> if bgcolor isnt 'transparent' ctx.setVariable 'fillStyle', bgcolor ctx.fillRect x, y, w, h numDraws += 1 return capitalize = (m, p1, p2) -> if m.length > 0 return p1 + p2.toUpperCase() return textTransform = (text, transform) -> switch transform when 'lowercase' return text.toLowerCase() when 'capitalize' return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize) when 'uppercase' return text.toUpperCase() else return text return noLetterSpacing = (letter_spacing) -> /^(normal|none|0px)$/.test letter_spacing drawText = (currentText, x, y, ctx) -> if currentText isnt null and Util.trimText(currentText).length > 0 ctx.fillText currentText, x, y numDraws += 1 return setTextVariables = (ctx, el, text_decoration, color) -> align = false bold = getCSS(el, 'fontWeight') family = getCSS(el, 'fontFamily') size = getCSS(el, 'fontSize') shadows = Util.parseTextShadows(getCSS(el, 'textShadow')) switch parseInt(bold, 10) when 401 bold = 'bold' when 400 bold = 'normal' ctx.setVariable 'fillStyle', color ctx.setVariable 'font', [ getCSS(el, 'fontStyle') getCSS(el, 'fontVariant') bold size family ].join(' ') ctx.setVariable 'textAlign', if align then 'right' else 'left' if shadows.length # TODO: support multiple text shadows # apply the first text shadow ctx.setVariable 'shadowColor', shadows[0].color ctx.setVariable 'shadowOffsetX', shadows[0].offsetX ctx.setVariable 'shadowOffsetY', shadows[0].offsetY ctx.setVariable 'shadowBlur', shadows[0].blur if text_decoration isnt 'none' return Util.Font(family, size, doc) return renderTextDecoration = (ctx, text_decoration, bounds, metrics, color) -> switch text_decoration when 'underline' # Draws a line at the baseline of the font # TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size renderRect ctx, bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, color when 'overline' renderRect ctx, bounds.left, Math.round(bounds.top), bounds.width, 1, color when 'line-through' # TODO try and find exact position for line-through renderRect ctx, bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, color return getTextBounds = (state, text, textDecoration, isLast, transform) -> bounds = undefined if support.rangeBounds and not transform if textDecoration isnt 'none' or Util.trimText(text).length isnt 0 bounds = textRangeBounds(text, state.node, state.textOffset) state.textOffset += text.length else if state.node and typeof state.node.nodeValue is 'string' newTextNode = if isLast then state.node.splitText(text.length) else null bounds = textWrapperBounds(state.node, transform) state.node = newTextNode bounds textRangeBounds = (text, textNode, textOffset) -> range = doc.createRange() range.setStart textNode, textOffset range.setEnd textNode, textOffset + text.length range.getBoundingClientRect() textWrapperBounds = (oldTextNode, transform) -> parent = oldTextNode.parentNode wrapElement = doc.createElement('wrapper') backupText = oldTextNode.cloneNode(true) wrapElement.appendChild oldTextNode.cloneNode(true) parent.replaceChild wrapElement, oldTextNode bounds = if transform then Util.OffsetBounds(wrapElement) else Util.Bounds(wrapElement) parent.replaceChild backupText, wrapElement bounds renderText = (el, textNode, stack) -> ctx = stack.ctx color = getCSS(el, 'color') textDecoration = getCSS(el, 'textDecoration') textAlign = getCSS(el, 'textAlign') metrics = undefined textList = undefined state = node: textNode textOffset: 0 if Util.trimText(textNode.nodeValue).length > 0 textNode.nodeValue = textTransform(textNode.nodeValue, getCSS(el, 'textTransform')) textAlign = textAlign.replace([ '-webkit-auto' ], [ 'auto' ]) textList = if not options.letterRendering and /^(left|right|justify|auto)$/.test(textAlign) and noLetterSpacing(getCSS(el, 'letterSpacing')) then textNode.nodeValue.split(/(\b| )/) else textNode.nodeValue.split('') metrics = setTextVariables(ctx, el, textDecoration, color) if options.chinese textList.forEach (word, index) -> if /.*[\u4E00-\u9FA5].*$/.test(word) word = word.split('') word.unshift index, 1 textList.splice.apply textList, word return textList.forEach (text, index) -> bounds = getTextBounds(state, text, textDecoration, index < textList.length - 1, stack.transform.matrix) if bounds drawText text, bounds.left, bounds.bottom, ctx renderTextDecoration ctx, textDecoration, bounds, metrics, color return return listPosition = (element, val) -> boundElement = doc.createElement('boundelement') originalType = undefined bounds = undefined boundElement.style.display = 'inline' originalType = element.style.listStyleType element.style.listStyleType = 'none' boundElement.appendChild doc.createTextNode(val) element.insertBefore boundElement, element.firstChild bounds = Util.Bounds(boundElement) element.removeChild boundElement element.style.listStyleType = originalType bounds elementIndex = (el) -> i = -1 count = 1 childs = el.parentNode.childNodes if el.parentNode while childs[++i] isnt el if childs[i].nodeType is 1 count++ count else -1 listItemText = (element, type) -> currentIndex = elementIndex(element) text = undefined switch type when 'decimal' text = currentIndex when 'decimal-leading-zero' text = if currentIndex.toString().length is 1 then (currentIndex = '0' + currentIndex.toString()) else currentIndex.toString() when 'upper-roman' text = _html2canvas.Generate.ListRoman(currentIndex) when 'lower-roman' text = _html2canvas.Generate.ListRoman(currentIndex).toLowerCase() when 'lower-alpha' text = _html2canvas.Generate.ListAlpha(currentIndex).toLowerCase() when 'upper-alpha' text = _html2canvas.Generate.ListAlpha(currentIndex) text + '. ' renderListItem = (element, stack, elBounds) -> x = undefined text = undefined ctx = stack.ctx type = getCSS(element, 'listStyleType') listBounds = undefined if /^(decimal|decimal-leading-zero|upper-alpha|upper-latin|upper-roman|lower-alpha|lower-greek|lower-latin|lower-roman)$/i.test(type) text = listItemText(element, type) listBounds = listPosition(element, text) setTextVariables ctx, element, 'none', getCSS(element, 'color') if getCSS(element, 'listStylePosition') is 'inside' ctx.setVariable 'textAlign', 'left' x = elBounds.left else return drawText text, x, listBounds.bottom, ctx return loadImage = (src) -> img = images[src] if img and img.succeeded is true then img.img else false clipBounds = (src, dst) -> x = Math.max(src.left, dst.left) y = Math.max(src.top, dst.top) x2 = Math.min(src.left + src.width, dst.left + dst.width) y2 = Math.min(src.top + src.height, dst.top + dst.height) { left: x top: y width: x2 - x height: y2 - y } setZ = (element, stack, parentStack) -> newContext = undefined isPositioned = stack.cssPosition isnt 'static' zIndex = if isPositioned then getCSS(element, 'zIndex') else 'auto' opacity = getCSS(element, 'opacity') isFloated = getCSS(element, 'cssFloat') isnt 'none' # https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context # When a new stacking context should be created: # the root element (HTML), # positioned (absolutely or relatively) with a z-index value other than "auto", # elements with an opacity value less than 1. (See the specification for opacity), # on mobile WebKit and Chrome 22+, position: fixed always creates a new stacking context, even when z-index is "auto" (See this post) stack.zIndex = newContext = h2czContext(zIndex) newContext.isPositioned = isPositioned newContext.isFloated = isFloated newContext.opacity = opacity newContext.ownStacking = zIndex isnt 'auto' or opacity < 1 if parentStack parentStack.zIndex.children.push stack return renderImage = (ctx, element, image, bounds, borders) -> paddingLeft = getCSSInt(element, 'paddingLeft') paddingTop = getCSSInt(element, 'paddingTop') paddingRight = getCSSInt(element, 'paddingRight') paddingBottom = getCSSInt(element, 'paddingBottom') bLeft = bounds.left + paddingLeft + borders[3].width bTop = bounds.top + paddingTop + borders[0].width bWidth = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight) drawImage ctx, image, 0, 0, image.width, image.height, bLeft, bTop, bWidth, bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom) return getBorderData = (element) -> [ 'Top' 'Right' 'Bottom' 'Left' ].map (side) -> { width: getCSSInt(element, 'border' + side + 'Width') color: getCSS(element, 'border' + side + 'Color') } getBorderRadiusData = (element) -> [ 'TopLeft' 'TopRight' 'BottomRight' 'BottomLeft' ].map (side) -> getCSS element, 'border' + side + 'Radius' bezierCurve = (start, startControl, endControl, end) -> lerp = (a, b, t) -> { x: a.x + (b.x - (a.x)) * t y: a.y + (b.y - (a.y)) * t } { start: start startControl: startControl endControl: endControl end: end subdivide: (t) -> ab = lerp(start, startControl, t) bc = lerp(startControl, endControl, t) cd = lerp(endControl, end, t) abbc = lerp(ab, bc, t) bccd = lerp(bc, cd, t) dest = lerp(abbc, bccd, t) [ bezierCurve(start, ab, abbc, dest) bezierCurve(dest, bccd, cd, end) ] curveTo: (borderArgs) -> borderArgs.push [ 'bezierCurve' startControl.x startControl.y endControl.x endControl.y end.x end.y ] return curveToReversed: (borderArgs) -> borderArgs.push [ 'bezierCurve' endControl.x endControl.y startControl.x startControl.y start.x start.y ] return } parseCorner = (borderArgs, radius1, radius2, corner1, corner2, x, y) -> if radius1[0] > 0 or radius1[1] > 0 borderArgs.push [ 'line' corner1[0].start.x corner1[0].start.y ] corner1[0].curveTo borderArgs corner1[1].curveTo borderArgs else borderArgs.push [ 'line' x y ] if radius2[0] > 0 or radius2[1] > 0 borderArgs.push [ 'line' corner2[0].start.x corner2[0].start.y ] return drawSide = (borderData, radius1, radius2, outer1, inner1, outer2, inner2) -> borderArgs = [] if radius1[0] > 0 or radius1[1] > 0 borderArgs.push [ 'line' outer1[1].start.x outer1[1].start.y ] outer1[1].curveTo borderArgs else borderArgs.push [ 'line' borderData.c1[0] borderData.c1[1] ] if radius2[0] > 0 or radius2[1] > 0 borderArgs.push [ 'line' outer2[0].start.x outer2[0].start.y ] outer2[0].curveTo borderArgs borderArgs.push [ 'line' inner2[0].end.x inner2[0].end.y ] inner2[0].curveToReversed borderArgs else borderArgs.push [ 'line' borderData.c2[0] borderData.c2[1] ] borderArgs.push [ 'line' borderData.c3[0] borderData.c3[1] ] if radius1[0] > 0 or radius1[1] > 0 borderArgs.push [ 'line' inner1[1].end.x inner1[1].end.y ] inner1[1].curveToReversed borderArgs else borderArgs.push [ 'line' borderData.c4[0] borderData.c4[1] ] borderArgs calculateCurvePoints = (bounds, borderRadius, borders) -> x = bounds.left y = bounds.top width = bounds.width height = bounds.height tlh = borderRadius[0][0] tlv = borderRadius[0][1] trh = borderRadius[1][0] trv = borderRadius[1][1] brh = borderRadius[2][0] brv = borderRadius[2][1] blh = borderRadius[3][0] blv = borderRadius[3][1] topWidth = width - trh rightHeight = height - brv bottomWidth = width - brh leftHeight = height - blv { topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5) topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - (borders[3].width)), Math.max(0, tlv - (borders[0].width))).topLeft.subdivide(0.5) topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5) topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (if topWidth > width + borders[3].width then 0 else trh - (borders[3].width)), trv - (borders[0].width)).topRight.subdivide(0.5) bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5) bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width + borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - (borders[1].width)), Math.max(0, brv - (borders[2].width))).bottomRight.subdivide(0.5) bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5) bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - (borders[3].width)), Math.max(0, blv - (borders[2].width))).bottomLeft.subdivide(0.5) } getBorderClip = (element, borderPoints, borders, radius, bounds) -> backgroundClip = getCSS(element, 'backgroundClip') borderArgs = [] switch backgroundClip when 'content-box', 'padding-box' parseCorner borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width parseCorner borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - (borders[1].width), bounds.top + borders[0].width parseCorner borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - (borders[1].width), bounds.top + bounds.height - (borders[2].width) parseCorner borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - (borders[2].width) else parseCorner borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top parseCorner borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top parseCorner borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height parseCorner borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height break borderArgs parseBorders = (element, bounds, borders) -> x = bounds.left y = bounds.top width = bounds.width height = bounds.height borderSide = undefined bx = undefined borderY = undefined bw = undefined bh = undefined borderArgs = undefined borderRadius = getBorderRadiusData(element) borderPoints = calculateCurvePoints(bounds, borderRadius, borders) borderData = clip: getBorderClip(element, borderPoints, borders, borderRadius, bounds) borders: [] borderSide = 0 while borderSide < 4 if borders[borderSide].width > 0 bx = x borderY = y bw = width bh = height - (borders[2].width) switch borderSide when 0 # top border bh = borders[0].width borderArgs = drawSide({ c1: [ bx borderY ] c2: [ bx + bw borderY ] c3: [ bx + bw - (borders[1].width) borderY + bh ] c4: [ bx + borders[3].width borderY + bh ] }, borderRadius[0], borderRadius[1], borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner) when 1 # right border bx = x + width - (borders[1].width) bw = borders[1].width borderArgs = drawSide({ c1: [ bx + bw borderY ] c2: [ bx + bw borderY + bh + borders[2].width ] c3: [ bx borderY + bh ] c4: [ bx borderY + borders[0].width ] }, borderRadius[1], borderRadius[2], borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner) when 2 # bottom border borderY = borderY + height - (borders[2].width) bh = borders[2].width borderArgs = drawSide({ c1: [ bx + bw borderY + bh ] c2: [ bx borderY + bh ] c3: [ bx + borders[3].width borderY ] c4: [ bx + bw - (borders[3].width) borderY ] }, borderRadius[2], borderRadius[3], borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner) when 3 # left border bw = borders[3].width borderArgs = drawSide({ c1: [ bx borderY + bh + borders[2].width ] c2: [ bx borderY ] c3: [ bx + bw borderY + borders[0].width ] c4: [ bx + bw borderY + bh ] }, borderRadius[3], borderRadius[0], borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner) borderData.borders.push args: borderArgs color: borders[borderSide].color borderSide++ borderData createShape = (ctx, args) -> shape = ctx.drawShape() args.forEach (border, index) -> shape[if index is 0 then 'moveTo' else border[0] + 'To'].apply null, border.slice(1) return shape renderBorders = (ctx, borderArgs, color) -> if color isnt 'transparent' ctx.setVariable 'fillStyle', color createShape ctx, borderArgs ctx.fill() numDraws += 1 return renderFormValue = (el, bounds, stack) -> valueWrap = doc.createElement('valuewrap') cssPropertyArray = [ 'lineHeight' 'textAlign' 'fontFamily' 'color' 'fontSize' 'paddingLeft' 'paddingTop' 'width' 'height' 'border' 'borderLeftWidth' 'borderTopWidth' ] textValue = undefined textNode = undefined cssPropertyArray.forEach (property) -> try valueWrap.style[property] = getCSS(el, property) catch e # Older IE has issues with "border" Util.log 'html2canvas: Parse: Exception caught in renderFormValue: ' + e.message return valueWrap.style.borderColor = 'black' valueWrap.style.borderStyle = 'solid' valueWrap.style.display = 'block' valueWrap.style.position = 'absolute' if /^(submit|reset|button|text|password)$/.test(el.type) or el.nodeName is 'SELECT' valueWrap.style.lineHeight = getCSS(el, 'height') valueWrap.style.top = bounds.top + 'px' valueWrap.style.left = bounds.left + 'px' textValue = if el.nodeName is 'SELECT' then (el.options[el.selectedIndex] or 0).text else el.value if not textValue textValue = el.placeholder textNode = doc.createTextNode(textValue) valueWrap.appendChild textNode body.appendChild valueWrap renderText el, textNode, stack body.removeChild valueWrap return drawImage = (ctx) -> ctx.drawImage.apply ctx, Array::slice.call(arguments, 1) numDraws += 1 return getPseudoElement = (el, which) -> elStyle = window.getComputedStyle(el, which) if not elStyle or not elStyle.content or elStyle.content is 'none' or elStyle.content is '-moz-alt-content' or elStyle.display is 'none' return content = elStyle.content + '' first = content.substr(0, 1) #strips quotes if first is content.substr(content.length - 1) and first.match(/'|"/) content = content.substr(1, content.length - 2) isImage = content.substr(0, 3) is 'url' elps = document.createElement(if isImage then 'img' else 'span') elps.className = pseudoHide + '-before ' + pseudoHide + '-after' Object.keys(elStyle).filter(indexedProperty).forEach (prop) -> # Prevent assigning of read only CSS Rules, ex. length, parentRule try elps.style[prop] = elStyle[prop] catch e Util.log [ 'Tried to assign readonly property ' prop 'Error:' e ] return if isImage elps.src = Util.parseBackgroundImage(content)[0].args[0] else elps.innerHTML = content elps indexedProperty = (property) -> isNaN window.parseInt(property, 10) injectPseudoElements = (el, stack) -> before = getPseudoElement(el, ':before') after = getPseudoElement(el, ':after') if not before and not after return if before el.className += ' ' + pseudoHide + '-before' el.parentNode.insertBefore before, el parseElement before, stack, true el.parentNode.removeChild before el.className = el.className.replace(pseudoHide + '-before', '').trim() if after el.className += ' ' + pseudoHide + '-after' el.appendChild after parseElement after, stack, true el.removeChild after el.className = el.className.replace(pseudoHide + '-after', '').trim() return renderBackgroundRepeat = (ctx, image, backgroundPosition, bounds) -> offsetX = Math.round(bounds.left + backgroundPosition.left) offsetY = Math.round(bounds.top + backgroundPosition.top) ctx.createPattern image ctx.translate offsetX, offsetY ctx.fill() ctx.translate -offsetX, -offsetY return backgroundRepeatShape = (ctx, image, backgroundPosition, bounds, left, top, width, height) -> args = [] args.push [ 'line' Math.round(left) Math.round(top) ] args.push [ 'line' Math.round(left + width) Math.round(top) ] args.push [ 'line' Math.round(left + width) Math.round(height + top) ] args.push [ 'line' Math.round(left) Math.round(height + top) ] createShape ctx, args ctx.save() ctx.clip() renderBackgroundRepeat ctx, image, backgroundPosition, bounds ctx.restore() return renderBackgroundColor = (ctx, backgroundBounds, bgcolor) -> renderRect ctx, backgroundBounds.left, backgroundBounds.top, backgroundBounds.width, backgroundBounds.height, bgcolor return renderBackgroundRepeating = (el, bounds, ctx, image, imageIndex) -> backgroundSize = Util.BackgroundSize(el, bounds, image, imageIndex) backgroundPosition = Util.BackgroundPosition(el, bounds, image, imageIndex, backgroundSize) backgroundRepeat = getCSS(el, 'backgroundRepeat').split(',').map(Util.trimText) image = resizeImage(image, backgroundSize) backgroundRepeat = backgroundRepeat[imageIndex] or backgroundRepeat[0] switch backgroundRepeat when 'repeat-x' backgroundRepeatShape ctx, image, backgroundPosition, bounds, bounds.left, bounds.top + backgroundPosition.top, 99999, image.height when 'repeat-y' backgroundRepeatShape ctx, image, backgroundPosition, bounds, bounds.left + backgroundPosition.left, bounds.top, image.width, 99999 when 'no-repeat' backgroundRepeatShape ctx, image, backgroundPosition, bounds, bounds.left + backgroundPosition.left, bounds.top + backgroundPosition.top, image.width, image.height else renderBackgroundRepeat ctx, image, backgroundPosition, top: bounds.top left: bounds.left width: image.width height: image.height break return renderBackgroundImage = (element, bounds, ctx) -> backgroundImage = getCSS(element, 'backgroundImage') backgroundImages = Util.parseBackgroundImage(backgroundImage) image = undefined imageIndex = backgroundImages.length while imageIndex-- backgroundImage = backgroundImages[imageIndex] if not backgroundImage.args or backgroundImage.args.length is 0 borderSide++ continue key = if backgroundImage.method is 'url' then backgroundImage.args[0] else backgroundImage.value image = loadImage(key) # TODO add support for background-origin if image renderBackgroundRepeating element, bounds, ctx, image, imageIndex else Util.log 'html2canvas: Error loading background:', backgroundImage return resizeImage = (image, bounds) -> if image.width is bounds.width and image.height is bounds.height return image ctx = undefined canvas = doc.createElement('canvas') canvas.width = bounds.width canvas.height = bounds.height ctx = canvas.getContext('2d') drawImage ctx, image, 0, 0, image.width, image.height, 0, 0, bounds.width, bounds.height canvas setOpacity = (ctx, element, parentStack) -> ctx.setVariable 'globalAlpha', getCSS(element, 'opacity') * (if parentStack then parentStack.opacity else 1) removePx = (str) -> str.replace 'px', '' getTransform = (element, parentStack) -> transform = getCSS(element, 'transform') or getCSS(element, '-webkit-transform') or getCSS(element, '-moz-transform') or getCSS(element, '-ms-transform') or getCSS(element, '-o-transform') transformOrigin = getCSS(element, 'transform-origin') or getCSS(element, '-webkit-transform-origin') or getCSS(element, '-moz-transform-origin') or getCSS(element, '-ms-transform-origin') or getCSS(element, '-o-transform-origin') or '0px 0px' transformOrigin = transformOrigin.split(' ').map(removePx).map(Util.asFloat) matrix = undefined if transform and transform isnt 'none' match = transform.match(transformRegExp) if match switch match[1] when 'matrix' matrix = match[2].split(',').map(Util.trimText).map(Util.asFloat) { origin: transformOrigin matrix: matrix } createStack = (element, parentStack, bounds, transform) -> ctx = h2cRenderContext((if not parentStack then documentWidth() else bounds.width), (if not parentStack then documentHeight() else bounds.height)) stack = ctx: ctx opacity: setOpacity(ctx, element, parentStack) cssPosition: getCSS(element, 'position') borders: getBorderData(element) transform: transform clip: if parentStack and parentStack.clip then Util.Extend({}, parentStack.clip) else null setZ element, stack, parentStack # TODO correct overflow for absolute content residing under a static position if options.useOverflow is true and /(hidden|scroll|auto)/.test(getCSS(element, 'overflow')) is true and /(BODY)/i.test(element.nodeName) is false stack.clip = if stack.clip then clipBounds(stack.clip, bounds) else bounds stack getBackgroundBounds = (borders, bounds, clip) -> backgroundBounds = left: bounds.left + borders[3].width top: bounds.top + borders[0].width width: bounds.width - (borders[1].width + borders[3].width) height: bounds.height - (borders[0].width + borders[2].width) if clip backgroundBounds = clipBounds(backgroundBounds, clip) backgroundBounds getBounds = (element, transform) -> bounds = if transform.matrix then Util.OffsetBounds(element) else Util.Bounds(element) transform.origin[0] += bounds.left transform.origin[1] += bounds.top bounds renderElement = (element, parentStack, pseudoElement, ignoreBackground) -> transform = getTransform(element, parentStack) bounds = getBounds(element, transform) image = undefined stack = createStack(element, parentStack, bounds, transform) borders = stack.borders ctx = stack.ctx backgroundBounds = getBackgroundBounds(borders, bounds, stack.clip) borderData = parseBorders(element, bounds, borders) backgroundColor = if ignoreElementsRegExp.test(element.nodeName) then '#efefef' else getCSS(element, 'backgroundColor') createShape ctx, borderData.clip ctx.save() ctx.clip() if backgroundBounds.height > 0 and backgroundBounds.width > 0 and not ignoreBackground renderBackgroundColor ctx, bounds, backgroundColor renderBackgroundImage element, backgroundBounds, ctx else if ignoreBackground stack.backgroundColor = backgroundColor ctx.restore() borderData.borders.forEach (border) -> renderBorders ctx, border.args, border.color return if not pseudoElement injectPseudoElements element, stack switch element.nodeName when 'IMG' if image = loadImage(element.getAttribute('src')) renderImage ctx, element, image, bounds, borders else Util.log 'html2canvas: Error loading <img>:' + element.getAttribute('src') when 'INPUT' # TODO add all relevant type's, i.e. HTML5 new stuff # todo add support for placeholder attribute for browsers which support it if /^(text|url|email|submit|button|reset)$/.test(element.type) and (element.value or element.placeholder or '').length > 0 renderFormValue element, bounds, stack when 'TEXTAREA' if (element.value or element.placeholder or '').length > 0 renderFormValue element, bounds, stack when 'SELECT' if (element.options or element.placeholder or '').length > 0 renderFormValue element, bounds, stack when 'LI' renderListItem element, stack, backgroundBounds when 'CANVAS' renderImage ctx, element, element, bounds, borders stack isElementVisible = (element) -> getCSS(element, 'display') isnt 'none' and getCSS(element, 'visibility') isnt 'hidden' and not element.hasAttribute('data-html2canvas-ignore') parseElement = (element, stack, pseudoElement) -> if isElementVisible(element) stack = renderElement(element, stack, pseudoElement, false) or stack if not ignoreElementsRegExp.test(element.nodeName) parseChildren element, stack, pseudoElement return parseChildren = (element, stack, pseudoElement) -> Util.Children(element).forEach (node) -> if node.nodeType is node.ELEMENT_NODE parseElement node, stack, pseudoElement else if node.nodeType is node.TEXT_NODE renderText element, node, stack return return init = -> background = getCSS(document.documentElement, 'backgroundColor') transparentBackground = Util.isTransparent(background) and element is document.body stack = renderElement(element, null, false, transparentBackground) parseChildren element, stack if transparentBackground background = stack.backgroundColor body.removeChild hidePseudoElements { backgroundColor: background stack: stack } window.scroll 0, 0 element = if options.elements is undefined then document.body else options.elements[0] numDraws = 0 doc = element.ownerDocument Util = _html2canvas.Util support = Util.Support(options, doc) ignoreElementsRegExp = new RegExp('(' + options.ignoreElements + ')') body = doc.body getCSS = Util.getCSS pseudoHide = '___html2canvas___pseudoelement' hidePseudoElements = doc.createElement('style') hidePseudoElements.innerHTML = '.' + pseudoHide + '-before:before { content: "" !important; display: none !important; }' + '.' + pseudoHide + '-after:after { content: "" !important; display: none !important; }' body.appendChild hidePseudoElements images = images or {} getCurvePoints = ((kappa) -> (x, y, r1, r2) -> ox = r1 * kappa oy = r2 * kappa xm = x + r1 ym = y + r2 # y-middle { topLeft: bezierCurve({ x: x y: ym }, { x: x y: ym - oy }, { x: xm - ox y: y }, x: xm y: y) topRight: bezierCurve({ x: x y: y }, { x: x + ox y: y }, { x: xm y: ym - oy }, x: xm y: ym) bottomRight: bezierCurve({ x: xm y: y }, { x: xm y: y + oy }, { x: x + ox y: ym }, x: x y: ym) bottomLeft: bezierCurve({ x: xm y: ym }, { x: xm - ox y: ym }, { x: x y: y + oy }, x: x y: y) } )(4 * (Math.sqrt(2) - 1) / 3) transformRegExp = /(matrix)\((.+)\)/ init() _html2canvas.Preload = (options) -> images = numLoaded: 0 numFailed: 0 numTotal: 0 cleanupDone: false pageOrigin = undefined Util = _html2canvas.Util methods = undefined i = undefined count = 0 element = options.elements[0] or document.body doc = element.ownerDocument domImages = element.getElementsByTagName('img') imgLen = domImages.length link = doc.createElement('a') supportCORS = ((img) -> img.crossOrigin isnt undefined )(new Image) timeoutTimer = undefined isSameOrigin = (url) -> link.href = url link.href = link.href # YES, BELIEVE IT OR NOT, that is required for IE9 - http://jsfiddle.net/niklasvh/2e48b/ origin = link.protocol + link.host origin is pageOrigin start = -> Util.log 'html2canvas: start: images: ' + images.numLoaded + ' / ' + images.numTotal + ' (failed: ' + images.numFailed + ')' if not images.firstRun and images.numLoaded >= images.numTotal Util.log 'Finished loading images: # ' + images.numTotal + ' (failed: ' + images.numFailed + ')' if typeof options.complete is 'function' options.complete images return # TODO modify proxy to serve images with CORS enabled, where available proxyGetImage = (url, img, imageObj) -> callback_name = undefined scriptUrl = options.proxy script = undefined link.href = url url = link.href # work around for pages with base href="" set - WARNING: this may change the url callback_name = 'html2canvas_' + count++ imageObj.callbackname = callback_name if scriptUrl.indexOf('?') > -1 scriptUrl += '&' else scriptUrl += '?' scriptUrl += 'url=' + encodeURIComponent(url) + '&callback=' + callback_name script = doc.createElement('script') window[callback_name] = (a) -> if a.substring(0, 6) is 'error:' imageObj.succeeded = false images.numLoaded++ images.numFailed++ start() else setImageLoadHandlers img, imageObj img.src = a window[callback_name] = undefined # to work with IE<9 // NOTE: that the undefined callback property-name still exists on the window object (for IE<9) try delete window[callback_name] # for all browser that support this catch ex script.parentNode.removeChild script script = null delete imageObj.script delete imageObj.callbackname return script.setAttribute 'type', 'text/javascript' script.setAttribute 'src', scriptUrl imageObj.script = script window.document.body.appendChild script return loadPseudoElement = (element, type) -> style = window.getComputedStyle(element, type) content = style.content if content.substr(0, 3) is 'url' methods.loadImage _html2canvas.Util.parseBackgroundImage(content)[0].args[0] loadBackgroundImages style.backgroundImage, element return loadPseudoElementImages = (element) -> loadPseudoElement element, ':before' loadPseudoElement element, ':after' return loadGradientImage = (backgroundImage, bounds) -> img = _html2canvas.Generate.Gradient(backgroundImage, bounds) if img isnt undefined images[backgroundImage] = img: img succeeded: true images.numTotal++ images.numLoaded++ start() return invalidBackgrounds = (background_image) -> background_image and background_image.method and background_image.args and background_image.args.length > 0 loadBackgroundImages = (background_image, el) -> bounds = undefined _html2canvas.Util.parseBackgroundImage(background_image).filter(invalidBackgrounds).forEach (background_image) -> if background_image.method is 'url' methods.loadImage background_image.args[0] else if background_image.method.match(/\-?gradient$/) if bounds is undefined bounds = _html2canvas.Util.Bounds(el) loadGradientImage background_image.value, bounds return return getImages = (el) -> elNodeType = false # Firefox fails with permission denied on pages with iframes try Util.Children(el).forEach getImages catch e try elNodeType = el.nodeType catch ex elNodeType = false Util.log 'html2canvas: failed to access some element\'s nodeType - Exception: ' + ex.message if elNodeType is 1 or elNodeType is undefined loadPseudoElementImages el try loadBackgroundImages Util.getCSS(el, 'backgroundImage'), el catch e Util.log 'html2canvas: failed to get background-image - Exception: ' + e.message loadBackgroundImages el return setImageLoadHandlers = (img, imageObj) -> img.onload = -> if imageObj.timer isnt undefined # CORS succeeded window.clearTimeout imageObj.timer images.numLoaded++ imageObj.succeeded = true img.onerror = img.onload = null start() return img.onerror = -> if img.crossOrigin is 'anonymous' # CORS failed window.clearTimeout imageObj.timer # let's try with proxy instead if options.proxy src = img.src img = new Image imageObj.img = img img.src = src proxyGetImage img.src, img, imageObj return images.numLoaded++ images.numFailed++ imageObj.succeeded = false img.onerror = img.onload = null start() return return link.href = window.location.href pageOrigin = link.protocol + link.host methods = loadImage: (src) -> img = undefined imageObj = undefined if src and images[src] is undefined img = new Image if src.match(/data:image\/.*;base64,/i) img.src = src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, '') imageObj = images[src] = img: img images.numTotal++ setImageLoadHandlers img, imageObj else if isSameOrigin(src) or options.allowTaint is true imageObj = images[src] = img: img images.numTotal++ setImageLoadHandlers img, imageObj img.src = src else if supportCORS and not options.allowTaint and options.useCORS # attempt to load with CORS img.crossOrigin = 'anonymous' imageObj = images[src] = img: img images.numTotal++ setImageLoadHandlers img, imageObj img.src = src else if options.proxy imageObj = images[src] = img: img images.numTotal++ proxyGetImage src, img, imageObj return cleanupDOM: (cause) -> img = undefined src = undefined if not images.cleanupDone if cause and typeof cause is 'string' Util.log 'html2canvas: Cleanup because: ' + cause else Util.log 'html2canvas: Cleanup after timeout: ' + options.timeout + ' ms.' for src in images # `src = src` if images.hasOwnProperty(src) img = images[src] if typeof img is 'object' and img.callbackname and img.succeeded is undefined # cancel proxy image request window[img.callbackname] = undefined # to work with IE<9 // NOTE: that the undefined callback property-name still exists on the window object (for IE<9) try delete window[img.callbackname] # for all browser that support this catch ex if img.script and img.script.parentNode img.script.setAttribute 'src', 'about:blank' # try to cancel running request img.script.parentNode.removeChild img.script images.numLoaded++ images.numFailed++ Util.log 'html2canvas: Cleaned up failed img: \'' + src + '\' Steps: ' + images.numLoaded + ' / ' + images.numTotal # cancel any pending requests if window.stop isnt undefined window.stop() else if document.execCommand isnt undefined document.execCommand 'Stop', false if document.close isnt undefined document.close() images.cleanupDone = true if not (cause and typeof cause is 'string') start() return renderingDone: -> if timeoutTimer window.clearTimeout timeoutTimer return if options.timeout > 0 timeoutTimer = window.setTimeout(methods.cleanupDOM, options.timeout) Util.log 'html2canvas: Preload starts: finding background-images' images.firstRun = true getImages element Util.log 'html2canvas: Preload: Finding images' # load <img> images i = 0 while i < imgLen methods.loadImage domImages[i].getAttribute('src') i += 1 images.firstRun = false Util.log 'html2canvas: Preload: Done.' if images.numTotal is images.numLoaded start() methods _html2canvas.Renderer = (parseQueue, options) -> # http://www.w3.org/TR/CSS21/zindex.html createRenderQueue = (parseQueue) -> queue = [] rootContext = undefined sortZ = (context) -> Object.keys(context).sort().forEach (zi) -> nonPositioned = [] floated = [] positioned = [] list = [] # positioned after static context[zi].forEach (v) -> if v.node.zIndex.isPositioned or v.node.zIndex.opacity < 1 # http://www.w3.org/TR/css3-color/#transparency # non-positioned element with opactiy < 1 should be stacked as if it were a positioned element with ‘z-index: 0’ and ‘opacity: 1’. positioned.push v else if v.node.zIndex.isFloated floated.push v else nonPositioned.push v return do walk = (arr = nonPositioned.concat(floated, positioned)) -> arr.forEach (v) -> list.push v if v.children walk v.children return return list.forEach (v) -> if v.context sortZ v.context else queue.push v.node return return return rootContext = ((rootNode) -> # `var rootContext` irootContext = {} insert = (context, node, specialParent) -> zi = if node.zIndex.zindex is 'auto' then 0 else Number(node.zIndex.zindex) contextForChildren = context isPositioned = node.zIndex.isPositioned isFloated = node.zIndex.isFloated stub = node: node childrenDest = specialParent # where children without z-index should be pushed into if node.zIndex.ownStacking # '!' comes before numbers in sorted array contextForChildren = stub.context = '!': [ { node: node children: [] } ] childrenDest = undefined else if isPositioned or isFloated childrenDest = stub.children = [] if zi is 0 and specialParent specialParent.push stub else if not context[zi] context[zi] = [] context[zi].push stub node.zIndex.children.forEach (childNode) -> insert contextForChildren, childNode, childrenDest return return insert irootContext, rootNode irootContext )(parseQueue) sortZ rootContext queue getRenderer = (rendererName) -> renderer = undefined if typeof options.renderer is 'string' and _html2canvas.Renderer[rendererName] isnt undefined renderer = _html2canvas.Renderer[rendererName](options) else if typeof rendererName is 'function' renderer = rendererName(options) else throw new Error('Unknown renderer') if typeof renderer isnt 'function' throw new Error('Invalid renderer defined') renderer getRenderer(options.renderer) parseQueue, options, document, createRenderQueue(parseQueue.stack), _html2canvas _html2canvas.Util.Support = (options, doc) -> supportSVGRendering = -> img = new Image canvas = doc.createElement('canvas') ctx = if canvas.getContext is undefined then false else canvas.getContext('2d') if ctx is false return false canvas.width = canvas.height = 10 img.src = [ 'data:image/svg+xml,' '<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'10\' height=\'10\'>' '<foreignObject width=\'10\' height=\'10\'>' '<div xmlns=\'http://www.w3.org/1999/xhtml\' style=\'width:10;height:10;\'>' 'sup' '</div>' '</foreignObject>' '</svg>' ].join('') try ctx.drawImage img, 0, 0 canvas.toDataURL() catch e return false _html2canvas.Util.log 'html2canvas: Parse: SVG powered rendering available' true # Test whether we can use ranges to measure bounding boxes # Opera doesn't provide valid bounds.height/bottom even though it supports the method. supportRangeBounds = -> r = undefined testElement = undefined rangeBounds = undefined rangeHeight = undefined support = false if doc.createRange r = doc.createRange() if r.getBoundingClientRect testElement = doc.createElement('boundtest') testElement.style.height = '123px' testElement.style.display = 'block' doc.body.appendChild testElement r.selectNode testElement rangeBounds = r.getBoundingClientRect() rangeHeight = rangeBounds.height if rangeHeight is 123 support = true doc.body.removeChild testElement support { rangeBounds: supportRangeBounds() svgRendering: options.svgRendering and supportSVGRendering() } window.html2canvas = (elements, opts) -> elements = if elements.length then elements else [ elements ] queue = undefined canvas = undefined options = logging: false elements: elements background: '#fff' proxy: null timeout: 0 useCORS: false allowTaint: false svgRendering: false ignoreElements: 'IFRAME|OBJECT|PARAM' useOverflow: true letterRendering: false chinese: false width: null height: null taintTest: true renderer: 'Canvas' options = _html2canvas.Util.Extend(opts, options) _html2canvas.logging = options.logging options.complete = (images) -> if typeof options.onpreloaded is 'function' if options.onpreloaded(images) is false return queue = _html2canvas.Parse(images, options) if typeof options.onparsed is 'function' if options.onparsed(queue) is false return canvas = _html2canvas.Renderer(queue, options) if typeof options.onrendered is 'function' options.onrendered canvas return # for pages without images, we still want this to be async, i.e. return methods before executing window.setTimeout (-> _html2canvas.Preload options return ), 0 { render: (queue, opts) -> _html2canvas.Renderer queue, _html2canvas.Util.Extend(opts, options) parse: (images, opts) -> _html2canvas.Parse images, _html2canvas.Util.Extend(opts, options) preload: (opts) -> _html2canvas.Preload _html2canvas.Util.Extend(opts, options) log: _html2canvas.Util.log } window.html2canvas.log = _html2canvas.Util.log # for renderers window.html2canvas.Renderer = Canvas: undefined _html2canvas.Renderer.Canvas = (options) -> createShape = (ctx, args) -> ctx.beginPath() args.forEach (arg) -> ctx[arg.name].apply ctx, arg['arguments'] return ctx.closePath() return safeImage = (item) -> if safeImages.indexOf(item['arguments'][0].src) is -1 testctx.drawImage item['arguments'][0], 0, 0 try testctx.getImageData 0, 0, 1, 1 catch e testCanvas = doc.createElement('canvas') testctx = testCanvas.getContext('2d') return false safeImages.push item['arguments'][0].src true renderItem = (ctx, item) -> switch item.type when 'variable' ctx[item.name] = item['arguments'] when 'function' switch item.name when 'createPattern' if item['arguments'][0].width > 0 and item['arguments'][0].height > 0 try ctx.fillStyle = ctx.createPattern(item['arguments'][0], 'repeat') catch e Util.log 'html2canvas: Renderer: Error creating pattern', e.message when 'drawShape' createShape ctx, item['arguments'] when 'drawImage' if item['arguments'][8] > 0 and item['arguments'][7] > 0 if not options.taintTest or options.taintTest and safeImage(item) ctx.drawImage.apply ctx, item['arguments'] else ctx[item.name].apply ctx, item['arguments'] return options = options or {} doc = document safeImages = [] testCanvas = document.createElement('canvas') testctx = testCanvas.getContext('2d') Util = _html2canvas.Util canvas = options.canvas or doc.createElement('canvas') (parsedData, options, document, queue, _html2canvas) -> ctx = canvas.getContext('2d') newCanvas = undefined bounds = undefined fstyle = undefined zStack = parsedData.stack canvas.width = canvas.style.width = options.width or zStack.ctx.width canvas.height = canvas.style.height = options.height or zStack.ctx.height fstyle = ctx.fillStyle ctx.fillStyle = if Util.isTransparent(zStack.backgroundColor) and options.background isnt undefined then options.background else parsedData.backgroundColor ctx.fillRect 0, 0, canvas.width, canvas.height ctx.fillStyle = fstyle queue.forEach (storageContext) -> # set common settings for canvas ctx.textBaseline = 'bottom' ctx.save() if storageContext.transform.matrix ctx.translate storageContext.transform.origin[0], storageContext.transform.origin[1] ctx.transform.apply ctx, storageContext.transform.matrix ctx.translate -storageContext.transform.origin[0], -storageContext.transform.origin[1] if storageContext.clip ctx.beginPath() ctx.rect storageContext.clip.left, storageContext.clip.top, storageContext.clip.width, storageContext.clip.height ctx.clip() if storageContext.ctx.storage storageContext.ctx.storage.forEach (item) -> renderItem ctx, item return ctx.restore() return Util.log 'html2canvas: Renderer: Canvas renderer done - returning canvas obj' if options.elements.length is 1 if typeof options.elements[0] is 'object' and options.elements[0].nodeName isnt 'BODY' # crop image to the bounds of selected (single) element bounds = _html2canvas.Util.Bounds(options.elements[0]) newCanvas = document.createElement('canvas') newCanvas.width = Math.ceil(bounds.width) newCanvas.height = Math.ceil(bounds.height) ctx = newCanvas.getContext('2d') ctx.drawImage canvas, bounds.left, bounds.top, bounds.width, bounds.height, 0, 0, bounds.width, bounds.height canvas = null return newCanvas canvas return ) window, document module.exports = window.html2canvas
[ { "context": "s that require alternative text have it.\n# @author Ethan Cohen\n###\n\n# ------------------------------------------", "end": 126, "score": 0.9998653531074524, "start": 115, "tag": "NAME", "value": "Ethan Cohen" }, { "context": "can uncomment these tests once https://gi...
src/tests/rules/alt-text.coffee
danielbayley/eslint-plugin-coffee
21
### eslint-env jest ### ###* # @fileoverview Enforce all elements that require alternative text have it. # @author Ethan Cohen ### # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- path = require 'path' {RuleTester} = require 'eslint' { default: parserOptionsMapper } = require '../eslint-plugin-jsx-a11y-parser-options-mapper' rule = require 'eslint-plugin-jsx-a11y/lib/rules/alt-text' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' missingPropError = (type) -> message: "#{type} elements must have an alt prop, either with meaningful text, or an empty string for decorative images." type: 'JSXOpeningElement' altValueError = (type) -> message: """Invalid alt value for #{type}. \ Use alt="" for presentational images.""" type: 'JSXOpeningElement' # ariaLabelValueError = # 'The aria-label attribute must have a value. The alt attribute is preferred over aria-label for images.' # ariaLabelledbyValueError = # 'The aria-labelledby attribute must have a value. The alt attribute is preferred over aria-labelledby for images.' preferAltError = -> message: 'Prefer alt="" over a presentational role. First rule of aria is to not use aria if it can be achieved via native HTML.' type: 'JSXOpeningElement' objectError = 'Embedded <object> elements must have alternative text by providing inner text, aria-label or aria-labelledby props.' areaError = 'Each area of an image map must have a text alternative through the `alt`, `aria-label`, or `aria-labelledby` prop.' inputImageError = '<input> elements with type="image" must have a text alternative through the `alt`, `aria-label`, or `aria-labelledby` prop.' array = [ img: ['Thumbnail', 'Image'] object: ['Object'] area: ['Area'] 'input[type="image"]': ['InputImage'] ] ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'alt-text', rule, valid: [ # DEFAULT ELEMENT 'img' TESTS code: '<img alt="foo" />' , code: '<img alt={"foo"} />' , code: '<img alt={alt} />' , code: '<img ALT="foo" />' , code: '<img ALT={"This is the #{alt} text"} />' , code: '<img ALt="foo" />' , code: '<img alt="foo" salt={undefined} />' , code: '<img {...this.props} alt="foo" />' , code: '<img {...@props} alt="foo" />' , code: '<a />' , code: '<div />' , code: '<img alt={(e) ->} />' , code: '<div alt={(e) ->} />' , code: '<img alt={() => undefined} />' , code: '<IMG />' , code: '<UX.Layout>test</UX.Layout>' , code: '<img alt={alt || "Alt text" } />' , code: '<img alt={alt or "Alt text" } />' , code: '<img alt={photo.caption} />' , code: '<img alt={bar()} />' , code: '<img alt={foo.bar || ""} />' , code: '<img alt={bar() || ""} />' , code: '<img alt={foo.bar() || ""} />' , code: '<img alt="" />' , code: '<img alt={"#{undefined}"} />' , code: '<img alt=" " />' , code: '<img alt="" role="presentation" />' , code: '<img alt="" role="none" />' , code: '<img alt="" role={`presentation`} />' , code: '<img alt="" role={"presentation"} />' , code: '<img alt="this is lit..." role="presentation" />' , code: '<img alt={if error then "not working" else "working"} />' , code: '<img alt={if undefined then "working" else "not working"} />' , code: '<img alt={plugin.name + " Logo"} />' , # code: '<img aria-label="foo" />' # , # code: '<img aria-labelledby="id1" />' # DEFAULT <object> TESTS code: '<object aria-label="foo" />' , code: '<object aria-labelledby="id1" />' , code: '<object>Foo</object>' , code: '<object><p>This is descriptive!</p></object>' , code: '<Object />' , code: '<object title="An object" />' , # DEFAULT <area> TESTS code: '<area aria-label="foo" />' , code: '<area aria-labelledby="id1" />' , code: '<area alt="" />' , code: '<area alt="This is descriptive!" />' , code: '<area alt={altText} />' , code: '<Area />' , # DEFAULT <input type="image"> TESTS code: '<input />' , code: '<input type="foo" />' , code: '<input type="image" aria-label="foo" />' , code: '<input type="image" aria-labelledby="id1" />' , code: '<input type="image" alt="" />' , code: '<input type="image" alt="This is descriptive!" />' , code: '<input type="image" alt={altText} />' , code: '<InputImage />' , # CUSTOM ELEMENT TESTS FOR ARRAY OPTION TESTS code: '<Thumbnail alt="foo" />', options: array , code: '<Thumbnail alt={"foo"} />', options: array , code: '<Thumbnail alt={alt} />', options: array , code: '<Thumbnail ALT="foo" />', options: array , code: '<Thumbnail ALT={"This is the #{alt} text"} />', options: array , code: '<Thumbnail ALt="foo" />', options: array , code: '<Thumbnail alt="foo" salt={undefined} />', options: array , code: '<Thumbnail {...this.props} alt="foo" />', options: array , code: '<thumbnail />', options: array , code: '<Thumbnail alt={(e) ->} />', options: array , code: '<div alt={(e) ->} />', options: array , code: '<Thumbnail alt={() => undefined} />', options: array , code: '<THUMBNAIL />', options: array , code: '<Thumbnail alt={alt || "foo" } />', options: array , code: '<Image alt="foo" />', options: array , code: '<Image alt={"foo"} />', options: array , code: '<Image alt={alt} />', options: array , code: '<Image ALT="foo" />', options: array , code: '<Image ALT={"This is the #{alt} text"} />', options: array , code: '<Image ALt="foo" />', options: array , code: '<Image alt="foo" salt={undefined} />', options: array , code: '<Image {...this.props} alt="foo" />', options: array , code: '<image />', options: array , code: '<Image alt={(e) ->} />', options: array , code: '<div alt={(e) ->} />', options: array , code: '<Image alt={() => undefined} />', options: array , code: '<IMAGE />', options: array , code: '<Image alt={alt || "foo" } />', options: array , code: '<Object aria-label="foo" />', options: array , code: '<Object aria-labelledby="id1" />', options: array , code: '<Object>Foo</Object>', options: array , code: '<Object><p>This is descriptive!</p></Object>', options: array , code: '<Object title="An object" />', options: array , code: '<Area aria-label="foo" />', options: array , code: '<Area aria-labelledby="id1" />', options: array , code: '<Area alt="" />', options: array , code: '<Area alt="This is descriptive!" />', options: array , code: '<Area alt={altText} />', options: array , code: '<InputImage aria-label="foo" />', options: array , code: '<InputImage aria-labelledby="id1" />', options: array , code: '<InputImage alt="" />', options: array , code: '<InputImage alt="This is descriptive!" />', options: array , code: '<InputImage alt={altText} />', options: array ].map parserOptionsMapper invalid: [ # DEFAULT ELEMENT 'img' TESTS code: '<img />', errors: [missingPropError 'img'] , code: '<img alt />', errors: [altValueError 'img'] , code: '<img alt={undefined} />', errors: [altValueError 'img'] , code: '<img src="xyz" />', errors: [missingPropError 'img'] , code: '<img role />', errors: [missingPropError 'img'] , code: '<img {...this.props} />', errors: [missingPropError 'img'] , code: '<img alt={false || false} />', errors: [altValueError 'img'] , code: '<img alt={false or false} />', errors: [altValueError 'img'] , code: '<img alt={undefined} role="presentation" />' errors: [altValueError 'img'] , code: '<img alt role="presentation" />', errors: [altValueError 'img'] , code: '<img role="presentation" />', errors: [preferAltError()] , code: '<img role="none" />', errors: [preferAltError()] , # # TODO: can uncomment these tests once https://github.com/evcohen/eslint-plugin-jsx-a11y/commit/dd49060b9ad69b16e03dbf99b989ed1e3bf264da gets released # code: '<img aria-label={undefined} />', errors: [ariaLabelValueError] # , # code: '<img aria-labelledby={undefined} />' # errors: [ariaLabelledbyValueError] # , # code: '<img aria-label="" />', errors: [ariaLabelValueError] # , # code: '<img aria-labelledby="" />', errors: [ariaLabelledbyValueError] # , # DEFAULT ELEMENT 'object' TESTS code: '<object />', errors: [objectError] , code: '<object><div aria-hidden /></object>', errors: [objectError] , code: '<object title={undefined} />', errors: [objectError] , # code: '<object aria-label="" />', errors: [objectError] # , # code: '<object aria-labelledby="" />', errors: [objectError] # , # code: '<object aria-label={undefined} />', errors: [objectError] # , # code: '<object aria-labelledby={undefined} />', errors: [objectError] # , # DEFAULT ELEMENT 'area' TESTS code: '<area />', errors: [areaError] , code: '<area alt />', errors: [areaError] , code: '<area alt={undefined} />', errors: [areaError] , code: '<area src="xyz" />', errors: [areaError] , code: '<area {...this.props} />', errors: [areaError] , # code: '<area aria-label="" />', errors: [areaError] # , # code: '<area aria-label={undefined} />', errors: [areaError] # , # code: '<area aria-labelledby="" />', errors: [areaError] # , # code: '<area aria-labelledby={undefined} />', errors: [areaError] # , # DEFAULT ELEMENT 'input type="image"' TESTS code: '<input type="image" />', errors: [inputImageError] , code: '<input type="image" alt />', errors: [inputImageError] , code: '<input type="image" alt={undefined} />', errors: [inputImageError] , code: '<input type="image">Foo</input>', errors: [inputImageError] , code: '<input type="image" {...this.props} />', errors: [inputImageError] , code: '<input type="image" {...@props} />', errors: [inputImageError] , # code: '<input type="image" aria-label="" />', errors: [inputImageError] # , # code: '<input type="image" aria-label={undefined} />' # errors: [inputImageError] # , # code: '<input type="image" aria-labelledby="" />', errors: [inputImageError] # , # code: '<input type="image" aria-labelledby={undefined} />' # errors: [inputImageError] # , # CUSTOM ELEMENT TESTS FOR ARRAY OPTION TESTS code: '<Thumbnail />' errors: [missingPropError 'Thumbnail'] options: array , code: '<Thumbnail alt />' errors: [altValueError 'Thumbnail'] options: array , code: '<Thumbnail alt={undefined} />' errors: [altValueError 'Thumbnail'] options: array , code: '<Thumbnail src="xyz" />' errors: [missingPropError 'Thumbnail'] options: array , code: '<Thumbnail {...this.props} />' errors: [missingPropError 'Thumbnail'] options: array , code: '<Image />', errors: [missingPropError 'Image'], options: array , code: '<Image alt />', errors: [altValueError 'Image'], options: array , code: '<Image alt={undefined} />' errors: [altValueError 'Image'] options: array , code: '<Image src="xyz" />' errors: [missingPropError 'Image'] options: array , code: '<Image {...this.props} />' errors: [missingPropError 'Image'] options: array , code: '<Object />', errors: [objectError], options: array , code: '<Object><div aria-hidden /></Object>' errors: [objectError] options: array , code: '<Object title={undefined} />', errors: [objectError], options: array , code: '<Area />', errors: [areaError], options: array , code: '<Area alt />', errors: [areaError], options: array , code: '<Area alt={undefined} />', errors: [areaError], options: array , code: '<Area src="xyz" />', errors: [areaError], options: array , code: '<Area {...this.props} />', errors: [areaError], options: array , code: '<InputImage />', errors: [inputImageError], options: array , code: '<InputImage alt />', errors: [inputImageError], options: array , code: '<InputImage alt={undefined} />' errors: [inputImageError] options: array , code: '<InputImage>Foo</InputImage>' errors: [inputImageError] options: array , code: '<InputImage {...this.props} />' errors: [inputImageError] options: array ].map parserOptionsMapper
117494
### eslint-env jest ### ###* # @fileoverview Enforce all elements that require alternative text have it. # @author <NAME> ### # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- path = require 'path' {RuleTester} = require 'eslint' { default: parserOptionsMapper } = require '../eslint-plugin-jsx-a11y-parser-options-mapper' rule = require 'eslint-plugin-jsx-a11y/lib/rules/alt-text' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' missingPropError = (type) -> message: "#{type} elements must have an alt prop, either with meaningful text, or an empty string for decorative images." type: 'JSXOpeningElement' altValueError = (type) -> message: """Invalid alt value for #{type}. \ Use alt="" for presentational images.""" type: 'JSXOpeningElement' # ariaLabelValueError = # 'The aria-label attribute must have a value. The alt attribute is preferred over aria-label for images.' # ariaLabelledbyValueError = # 'The aria-labelledby attribute must have a value. The alt attribute is preferred over aria-labelledby for images.' preferAltError = -> message: 'Prefer alt="" over a presentational role. First rule of aria is to not use aria if it can be achieved via native HTML.' type: 'JSXOpeningElement' objectError = 'Embedded <object> elements must have alternative text by providing inner text, aria-label or aria-labelledby props.' areaError = 'Each area of an image map must have a text alternative through the `alt`, `aria-label`, or `aria-labelledby` prop.' inputImageError = '<input> elements with type="image" must have a text alternative through the `alt`, `aria-label`, or `aria-labelledby` prop.' array = [ img: ['Thumbnail', 'Image'] object: ['Object'] area: ['Area'] 'input[type="image"]': ['InputImage'] ] ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'alt-text', rule, valid: [ # DEFAULT ELEMENT 'img' TESTS code: '<img alt="foo" />' , code: '<img alt={"foo"} />' , code: '<img alt={alt} />' , code: '<img ALT="foo" />' , code: '<img ALT={"This is the #{alt} text"} />' , code: '<img ALt="foo" />' , code: '<img alt="foo" salt={undefined} />' , code: '<img {...this.props} alt="foo" />' , code: '<img {...@props} alt="foo" />' , code: '<a />' , code: '<div />' , code: '<img alt={(e) ->} />' , code: '<div alt={(e) ->} />' , code: '<img alt={() => undefined} />' , code: '<IMG />' , code: '<UX.Layout>test</UX.Layout>' , code: '<img alt={alt || "Alt text" } />' , code: '<img alt={alt or "Alt text" } />' , code: '<img alt={photo.caption} />' , code: '<img alt={bar()} />' , code: '<img alt={foo.bar || ""} />' , code: '<img alt={bar() || ""} />' , code: '<img alt={foo.bar() || ""} />' , code: '<img alt="" />' , code: '<img alt={"#{undefined}"} />' , code: '<img alt=" " />' , code: '<img alt="" role="presentation" />' , code: '<img alt="" role="none" />' , code: '<img alt="" role={`presentation`} />' , code: '<img alt="" role={"presentation"} />' , code: '<img alt="this is lit..." role="presentation" />' , code: '<img alt={if error then "not working" else "working"} />' , code: '<img alt={if undefined then "working" else "not working"} />' , code: '<img alt={plugin.name + " Logo"} />' , # code: '<img aria-label="foo" />' # , # code: '<img aria-labelledby="id1" />' # DEFAULT <object> TESTS code: '<object aria-label="foo" />' , code: '<object aria-labelledby="id1" />' , code: '<object>Foo</object>' , code: '<object><p>This is descriptive!</p></object>' , code: '<Object />' , code: '<object title="An object" />' , # DEFAULT <area> TESTS code: '<area aria-label="foo" />' , code: '<area aria-labelledby="id1" />' , code: '<area alt="" />' , code: '<area alt="This is descriptive!" />' , code: '<area alt={altText} />' , code: '<Area />' , # DEFAULT <input type="image"> TESTS code: '<input />' , code: '<input type="foo" />' , code: '<input type="image" aria-label="foo" />' , code: '<input type="image" aria-labelledby="id1" />' , code: '<input type="image" alt="" />' , code: '<input type="image" alt="This is descriptive!" />' , code: '<input type="image" alt={altText} />' , code: '<InputImage />' , # CUSTOM ELEMENT TESTS FOR ARRAY OPTION TESTS code: '<Thumbnail alt="foo" />', options: array , code: '<Thumbnail alt={"foo"} />', options: array , code: '<Thumbnail alt={alt} />', options: array , code: '<Thumbnail ALT="foo" />', options: array , code: '<Thumbnail ALT={"This is the #{alt} text"} />', options: array , code: '<Thumbnail ALt="foo" />', options: array , code: '<Thumbnail alt="foo" salt={undefined} />', options: array , code: '<Thumbnail {...this.props} alt="foo" />', options: array , code: '<thumbnail />', options: array , code: '<Thumbnail alt={(e) ->} />', options: array , code: '<div alt={(e) ->} />', options: array , code: '<Thumbnail alt={() => undefined} />', options: array , code: '<THUMBNAIL />', options: array , code: '<Thumbnail alt={alt || "foo" } />', options: array , code: '<Image alt="foo" />', options: array , code: '<Image alt={"foo"} />', options: array , code: '<Image alt={alt} />', options: array , code: '<Image ALT="foo" />', options: array , code: '<Image ALT={"This is the #{alt} text"} />', options: array , code: '<Image ALt="foo" />', options: array , code: '<Image alt="foo" salt={undefined} />', options: array , code: '<Image {...this.props} alt="foo" />', options: array , code: '<image />', options: array , code: '<Image alt={(e) ->} />', options: array , code: '<div alt={(e) ->} />', options: array , code: '<Image alt={() => undefined} />', options: array , code: '<IMAGE />', options: array , code: '<Image alt={alt || "foo" } />', options: array , code: '<Object aria-label="foo" />', options: array , code: '<Object aria-labelledby="id1" />', options: array , code: '<Object>Foo</Object>', options: array , code: '<Object><p>This is descriptive!</p></Object>', options: array , code: '<Object title="An object" />', options: array , code: '<Area aria-label="foo" />', options: array , code: '<Area aria-labelledby="id1" />', options: array , code: '<Area alt="" />', options: array , code: '<Area alt="This is descriptive!" />', options: array , code: '<Area alt={altText} />', options: array , code: '<InputImage aria-label="foo" />', options: array , code: '<InputImage aria-labelledby="id1" />', options: array , code: '<InputImage alt="" />', options: array , code: '<InputImage alt="This is descriptive!" />', options: array , code: '<InputImage alt={altText} />', options: array ].map parserOptionsMapper invalid: [ # DEFAULT ELEMENT 'img' TESTS code: '<img />', errors: [missingPropError 'img'] , code: '<img alt />', errors: [altValueError 'img'] , code: '<img alt={undefined} />', errors: [altValueError 'img'] , code: '<img src="xyz" />', errors: [missingPropError 'img'] , code: '<img role />', errors: [missingPropError 'img'] , code: '<img {...this.props} />', errors: [missingPropError 'img'] , code: '<img alt={false || false} />', errors: [altValueError 'img'] , code: '<img alt={false or false} />', errors: [altValueError 'img'] , code: '<img alt={undefined} role="presentation" />' errors: [altValueError 'img'] , code: '<img alt role="presentation" />', errors: [altValueError 'img'] , code: '<img role="presentation" />', errors: [preferAltError()] , code: '<img role="none" />', errors: [preferAltError()] , # # TODO: can uncomment these tests once https://github.com/evcohen/eslint-plugin-jsx-a11y/commit/dd49060b9ad69b16e03dbf99b989ed1e3bf264da gets released # code: '<img aria-label={undefined} />', errors: [ariaLabelValueError] # , # code: '<img aria-labelledby={undefined} />' # errors: [ariaLabelledbyValueError] # , # code: '<img aria-label="" />', errors: [ariaLabelValueError] # , # code: '<img aria-labelledby="" />', errors: [ariaLabelledbyValueError] # , # DEFAULT ELEMENT 'object' TESTS code: '<object />', errors: [objectError] , code: '<object><div aria-hidden /></object>', errors: [objectError] , code: '<object title={undefined} />', errors: [objectError] , # code: '<object aria-label="" />', errors: [objectError] # , # code: '<object aria-labelledby="" />', errors: [objectError] # , # code: '<object aria-label={undefined} />', errors: [objectError] # , # code: '<object aria-labelledby={undefined} />', errors: [objectError] # , # DEFAULT ELEMENT 'area' TESTS code: '<area />', errors: [areaError] , code: '<area alt />', errors: [areaError] , code: '<area alt={undefined} />', errors: [areaError] , code: '<area src="xyz" />', errors: [areaError] , code: '<area {...this.props} />', errors: [areaError] , # code: '<area aria-label="" />', errors: [areaError] # , # code: '<area aria-label={undefined} />', errors: [areaError] # , # code: '<area aria-labelledby="" />', errors: [areaError] # , # code: '<area aria-labelledby={undefined} />', errors: [areaError] # , # DEFAULT ELEMENT 'input type="image"' TESTS code: '<input type="image" />', errors: [inputImageError] , code: '<input type="image" alt />', errors: [inputImageError] , code: '<input type="image" alt={undefined} />', errors: [inputImageError] , code: '<input type="image">Foo</input>', errors: [inputImageError] , code: '<input type="image" {...this.props} />', errors: [inputImageError] , code: '<input type="image" {...@props} />', errors: [inputImageError] , # code: '<input type="image" aria-label="" />', errors: [inputImageError] # , # code: '<input type="image" aria-label={undefined} />' # errors: [inputImageError] # , # code: '<input type="image" aria-labelledby="" />', errors: [inputImageError] # , # code: '<input type="image" aria-labelledby={undefined} />' # errors: [inputImageError] # , # CUSTOM ELEMENT TESTS FOR ARRAY OPTION TESTS code: '<Thumbnail />' errors: [missingPropError 'Thumbnail'] options: array , code: '<Thumbnail alt />' errors: [altValueError 'Thumbnail'] options: array , code: '<Thumbnail alt={undefined} />' errors: [altValueError 'Thumbnail'] options: array , code: '<Thumbnail src="xyz" />' errors: [missingPropError 'Thumbnail'] options: array , code: '<Thumbnail {...this.props} />' errors: [missingPropError 'Thumbnail'] options: array , code: '<Image />', errors: [missingPropError 'Image'], options: array , code: '<Image alt />', errors: [altValueError 'Image'], options: array , code: '<Image alt={undefined} />' errors: [altValueError 'Image'] options: array , code: '<Image src="xyz" />' errors: [missingPropError 'Image'] options: array , code: '<Image {...this.props} />' errors: [missingPropError 'Image'] options: array , code: '<Object />', errors: [objectError], options: array , code: '<Object><div aria-hidden /></Object>' errors: [objectError] options: array , code: '<Object title={undefined} />', errors: [objectError], options: array , code: '<Area />', errors: [areaError], options: array , code: '<Area alt />', errors: [areaError], options: array , code: '<Area alt={undefined} />', errors: [areaError], options: array , code: '<Area src="xyz" />', errors: [areaError], options: array , code: '<Area {...this.props} />', errors: [areaError], options: array , code: '<InputImage />', errors: [inputImageError], options: array , code: '<InputImage alt />', errors: [inputImageError], options: array , code: '<InputImage alt={undefined} />' errors: [inputImageError] options: array , code: '<InputImage>Foo</InputImage>' errors: [inputImageError] options: array , code: '<InputImage {...this.props} />' errors: [inputImageError] options: array ].map parserOptionsMapper
true
### eslint-env jest ### ###* # @fileoverview Enforce all elements that require alternative text have it. # @author PI:NAME:<NAME>END_PI ### # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- path = require 'path' {RuleTester} = require 'eslint' { default: parserOptionsMapper } = require '../eslint-plugin-jsx-a11y-parser-options-mapper' rule = require 'eslint-plugin-jsx-a11y/lib/rules/alt-text' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' missingPropError = (type) -> message: "#{type} elements must have an alt prop, either with meaningful text, or an empty string for decorative images." type: 'JSXOpeningElement' altValueError = (type) -> message: """Invalid alt value for #{type}. \ Use alt="" for presentational images.""" type: 'JSXOpeningElement' # ariaLabelValueError = # 'The aria-label attribute must have a value. The alt attribute is preferred over aria-label for images.' # ariaLabelledbyValueError = # 'The aria-labelledby attribute must have a value. The alt attribute is preferred over aria-labelledby for images.' preferAltError = -> message: 'Prefer alt="" over a presentational role. First rule of aria is to not use aria if it can be achieved via native HTML.' type: 'JSXOpeningElement' objectError = 'Embedded <object> elements must have alternative text by providing inner text, aria-label or aria-labelledby props.' areaError = 'Each area of an image map must have a text alternative through the `alt`, `aria-label`, or `aria-labelledby` prop.' inputImageError = '<input> elements with type="image" must have a text alternative through the `alt`, `aria-label`, or `aria-labelledby` prop.' array = [ img: ['Thumbnail', 'Image'] object: ['Object'] area: ['Area'] 'input[type="image"]': ['InputImage'] ] ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'alt-text', rule, valid: [ # DEFAULT ELEMENT 'img' TESTS code: '<img alt="foo" />' , code: '<img alt={"foo"} />' , code: '<img alt={alt} />' , code: '<img ALT="foo" />' , code: '<img ALT={"This is the #{alt} text"} />' , code: '<img ALt="foo" />' , code: '<img alt="foo" salt={undefined} />' , code: '<img {...this.props} alt="foo" />' , code: '<img {...@props} alt="foo" />' , code: '<a />' , code: '<div />' , code: '<img alt={(e) ->} />' , code: '<div alt={(e) ->} />' , code: '<img alt={() => undefined} />' , code: '<IMG />' , code: '<UX.Layout>test</UX.Layout>' , code: '<img alt={alt || "Alt text" } />' , code: '<img alt={alt or "Alt text" } />' , code: '<img alt={photo.caption} />' , code: '<img alt={bar()} />' , code: '<img alt={foo.bar || ""} />' , code: '<img alt={bar() || ""} />' , code: '<img alt={foo.bar() || ""} />' , code: '<img alt="" />' , code: '<img alt={"#{undefined}"} />' , code: '<img alt=" " />' , code: '<img alt="" role="presentation" />' , code: '<img alt="" role="none" />' , code: '<img alt="" role={`presentation`} />' , code: '<img alt="" role={"presentation"} />' , code: '<img alt="this is lit..." role="presentation" />' , code: '<img alt={if error then "not working" else "working"} />' , code: '<img alt={if undefined then "working" else "not working"} />' , code: '<img alt={plugin.name + " Logo"} />' , # code: '<img aria-label="foo" />' # , # code: '<img aria-labelledby="id1" />' # DEFAULT <object> TESTS code: '<object aria-label="foo" />' , code: '<object aria-labelledby="id1" />' , code: '<object>Foo</object>' , code: '<object><p>This is descriptive!</p></object>' , code: '<Object />' , code: '<object title="An object" />' , # DEFAULT <area> TESTS code: '<area aria-label="foo" />' , code: '<area aria-labelledby="id1" />' , code: '<area alt="" />' , code: '<area alt="This is descriptive!" />' , code: '<area alt={altText} />' , code: '<Area />' , # DEFAULT <input type="image"> TESTS code: '<input />' , code: '<input type="foo" />' , code: '<input type="image" aria-label="foo" />' , code: '<input type="image" aria-labelledby="id1" />' , code: '<input type="image" alt="" />' , code: '<input type="image" alt="This is descriptive!" />' , code: '<input type="image" alt={altText} />' , code: '<InputImage />' , # CUSTOM ELEMENT TESTS FOR ARRAY OPTION TESTS code: '<Thumbnail alt="foo" />', options: array , code: '<Thumbnail alt={"foo"} />', options: array , code: '<Thumbnail alt={alt} />', options: array , code: '<Thumbnail ALT="foo" />', options: array , code: '<Thumbnail ALT={"This is the #{alt} text"} />', options: array , code: '<Thumbnail ALt="foo" />', options: array , code: '<Thumbnail alt="foo" salt={undefined} />', options: array , code: '<Thumbnail {...this.props} alt="foo" />', options: array , code: '<thumbnail />', options: array , code: '<Thumbnail alt={(e) ->} />', options: array , code: '<div alt={(e) ->} />', options: array , code: '<Thumbnail alt={() => undefined} />', options: array , code: '<THUMBNAIL />', options: array , code: '<Thumbnail alt={alt || "foo" } />', options: array , code: '<Image alt="foo" />', options: array , code: '<Image alt={"foo"} />', options: array , code: '<Image alt={alt} />', options: array , code: '<Image ALT="foo" />', options: array , code: '<Image ALT={"This is the #{alt} text"} />', options: array , code: '<Image ALt="foo" />', options: array , code: '<Image alt="foo" salt={undefined} />', options: array , code: '<Image {...this.props} alt="foo" />', options: array , code: '<image />', options: array , code: '<Image alt={(e) ->} />', options: array , code: '<div alt={(e) ->} />', options: array , code: '<Image alt={() => undefined} />', options: array , code: '<IMAGE />', options: array , code: '<Image alt={alt || "foo" } />', options: array , code: '<Object aria-label="foo" />', options: array , code: '<Object aria-labelledby="id1" />', options: array , code: '<Object>Foo</Object>', options: array , code: '<Object><p>This is descriptive!</p></Object>', options: array , code: '<Object title="An object" />', options: array , code: '<Area aria-label="foo" />', options: array , code: '<Area aria-labelledby="id1" />', options: array , code: '<Area alt="" />', options: array , code: '<Area alt="This is descriptive!" />', options: array , code: '<Area alt={altText} />', options: array , code: '<InputImage aria-label="foo" />', options: array , code: '<InputImage aria-labelledby="id1" />', options: array , code: '<InputImage alt="" />', options: array , code: '<InputImage alt="This is descriptive!" />', options: array , code: '<InputImage alt={altText} />', options: array ].map parserOptionsMapper invalid: [ # DEFAULT ELEMENT 'img' TESTS code: '<img />', errors: [missingPropError 'img'] , code: '<img alt />', errors: [altValueError 'img'] , code: '<img alt={undefined} />', errors: [altValueError 'img'] , code: '<img src="xyz" />', errors: [missingPropError 'img'] , code: '<img role />', errors: [missingPropError 'img'] , code: '<img {...this.props} />', errors: [missingPropError 'img'] , code: '<img alt={false || false} />', errors: [altValueError 'img'] , code: '<img alt={false or false} />', errors: [altValueError 'img'] , code: '<img alt={undefined} role="presentation" />' errors: [altValueError 'img'] , code: '<img alt role="presentation" />', errors: [altValueError 'img'] , code: '<img role="presentation" />', errors: [preferAltError()] , code: '<img role="none" />', errors: [preferAltError()] , # # TODO: can uncomment these tests once https://github.com/evcohen/eslint-plugin-jsx-a11y/commit/dd49060b9ad69b16e03dbf99b989ed1e3bf264da gets released # code: '<img aria-label={undefined} />', errors: [ariaLabelValueError] # , # code: '<img aria-labelledby={undefined} />' # errors: [ariaLabelledbyValueError] # , # code: '<img aria-label="" />', errors: [ariaLabelValueError] # , # code: '<img aria-labelledby="" />', errors: [ariaLabelledbyValueError] # , # DEFAULT ELEMENT 'object' TESTS code: '<object />', errors: [objectError] , code: '<object><div aria-hidden /></object>', errors: [objectError] , code: '<object title={undefined} />', errors: [objectError] , # code: '<object aria-label="" />', errors: [objectError] # , # code: '<object aria-labelledby="" />', errors: [objectError] # , # code: '<object aria-label={undefined} />', errors: [objectError] # , # code: '<object aria-labelledby={undefined} />', errors: [objectError] # , # DEFAULT ELEMENT 'area' TESTS code: '<area />', errors: [areaError] , code: '<area alt />', errors: [areaError] , code: '<area alt={undefined} />', errors: [areaError] , code: '<area src="xyz" />', errors: [areaError] , code: '<area {...this.props} />', errors: [areaError] , # code: '<area aria-label="" />', errors: [areaError] # , # code: '<area aria-label={undefined} />', errors: [areaError] # , # code: '<area aria-labelledby="" />', errors: [areaError] # , # code: '<area aria-labelledby={undefined} />', errors: [areaError] # , # DEFAULT ELEMENT 'input type="image"' TESTS code: '<input type="image" />', errors: [inputImageError] , code: '<input type="image" alt />', errors: [inputImageError] , code: '<input type="image" alt={undefined} />', errors: [inputImageError] , code: '<input type="image">Foo</input>', errors: [inputImageError] , code: '<input type="image" {...this.props} />', errors: [inputImageError] , code: '<input type="image" {...@props} />', errors: [inputImageError] , # code: '<input type="image" aria-label="" />', errors: [inputImageError] # , # code: '<input type="image" aria-label={undefined} />' # errors: [inputImageError] # , # code: '<input type="image" aria-labelledby="" />', errors: [inputImageError] # , # code: '<input type="image" aria-labelledby={undefined} />' # errors: [inputImageError] # , # CUSTOM ELEMENT TESTS FOR ARRAY OPTION TESTS code: '<Thumbnail />' errors: [missingPropError 'Thumbnail'] options: array , code: '<Thumbnail alt />' errors: [altValueError 'Thumbnail'] options: array , code: '<Thumbnail alt={undefined} />' errors: [altValueError 'Thumbnail'] options: array , code: '<Thumbnail src="xyz" />' errors: [missingPropError 'Thumbnail'] options: array , code: '<Thumbnail {...this.props} />' errors: [missingPropError 'Thumbnail'] options: array , code: '<Image />', errors: [missingPropError 'Image'], options: array , code: '<Image alt />', errors: [altValueError 'Image'], options: array , code: '<Image alt={undefined} />' errors: [altValueError 'Image'] options: array , code: '<Image src="xyz" />' errors: [missingPropError 'Image'] options: array , code: '<Image {...this.props} />' errors: [missingPropError 'Image'] options: array , code: '<Object />', errors: [objectError], options: array , code: '<Object><div aria-hidden /></Object>' errors: [objectError] options: array , code: '<Object title={undefined} />', errors: [objectError], options: array , code: '<Area />', errors: [areaError], options: array , code: '<Area alt />', errors: [areaError], options: array , code: '<Area alt={undefined} />', errors: [areaError], options: array , code: '<Area src="xyz" />', errors: [areaError], options: array , code: '<Area {...this.props} />', errors: [areaError], options: array , code: '<InputImage />', errors: [inputImageError], options: array , code: '<InputImage alt />', errors: [inputImageError], options: array , code: '<InputImage alt={undefined} />' errors: [inputImageError] options: array , code: '<InputImage>Foo</InputImage>' errors: [inputImageError] options: array , code: '<InputImage {...this.props} />' errors: [inputImageError] options: array ].map parserOptionsMapper
[ { "context": "articular search term in the group\n#\n# Author:\n# stephenyeargin\n\n_ = require 'lodash'\nFlickr = require 'flickr-sd", "end": 282, "score": 0.9995126724243164, "start": 268, "tag": "USERNAME", "value": "stephenyeargin" }, { "context": " image_url: photo_src,\n ...
src/flickr-group-search.coffee
stephenyeargin/hubot-flickr-group-search
1
# Description # Search a specified Flickr group for photos. # # Configuration: # HUBOT_FLICKR_API_KEY - API key # HUBOT_FLICKR_GROUP_ID - Group ID to search # # Commands: # hubot photos <term> - Search for a particular search term in the group # # Author: # stephenyeargin _ = require 'lodash' Flickr = require 'flickr-sdk' # Configure the library flickr = new Flickr(process.env.HUBOT_FLICKR_API_KEY) module.exports = (robot) -> flickrGroupId = process.env.HUBOT_FLICKR_GROUP_ID robot.respond /(?:photo|photos) (.*)/i, (msg) -> if missingEnvironmentForApi(msg) return msg.reply "Retrieving photos matching: \"#{msg.match[1]}\"" # Making the request from Flickr flickr.photos.search( text: msg.match[1] page: 1, per_page: 5, group_id: flickrGroupId, media: 'photos' sort: 'date-taken-desc' ) .then ((response) -> attachments = [] irc_list = [] results = JSON.parse(response.text) # Malformed response unless results.photos? return msg.send "Empty response from API." # Put together the count summary count = results.photos.photo.length if count == 0 return msg.send "No photos found. :cry:" summary = "There are #{results.photos.total} photos in the group that match your search. Here are the #{count} most recent:" # Loop through the response _(results.photos.photo).each (photo, i) -> # Piece together from the photos photo_src = "https://c1.staticflickr.com/#{photo.farm}/#{photo.server}/#{photo.id}_#{photo.secret}_b.jpg" photo_url = "https://flickr.com/photos/#{photo.owner}/#{photo.id}" # Slack attachments attachments.push { title: photo.title, title_link: photo_url, image_url: photo_src, author_name: "Flickr", author_link: "https://flickr.com/groups/#{flickrGroupId}", author_icon: "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png" } # Non-slack content irc_list.push "- #{photo_url} - #{photo.title}" # Send the message switch robot.adapterName when 'slack' payload = { text: summary, fallback: summary + "\n" + irc_list.join("\n"), attachments: attachments, unfurl_links: false } msg.send payload # Non-slack response else msg.reply summary msg.send irc_list.join("\n") ) .catch (err) -> msg.reply "Sorry, unable to retrieve photos. :cry:" robot.logger.error err # Check for required config missingEnvironmentForApi = (msg) -> missingAnything = false unless process.env.HUBOT_FLICKR_API_KEY? msg.send "Flickr API Key is missing: Ensure that HUBOT_FLICKR_API_KEY is set." missingAnything |= true unless process.env.HUBOT_FLICKR_GROUP_ID? msg.send "Flickr Group ID is missing: Ensure that HUBOT_FLICKR_GROUP_ID is set." missingAnything |= true missingAnything
192869
# Description # Search a specified Flickr group for photos. # # Configuration: # HUBOT_FLICKR_API_KEY - API key # HUBOT_FLICKR_GROUP_ID - Group ID to search # # Commands: # hubot photos <term> - Search for a particular search term in the group # # Author: # stephenyeargin _ = require 'lodash' Flickr = require 'flickr-sdk' # Configure the library flickr = new Flickr(process.env.HUBOT_FLICKR_API_KEY) module.exports = (robot) -> flickrGroupId = process.env.HUBOT_FLICKR_GROUP_ID robot.respond /(?:photo|photos) (.*)/i, (msg) -> if missingEnvironmentForApi(msg) return msg.reply "Retrieving photos matching: \"#{msg.match[1]}\"" # Making the request from Flickr flickr.photos.search( text: msg.match[1] page: 1, per_page: 5, group_id: flickrGroupId, media: 'photos' sort: 'date-taken-desc' ) .then ((response) -> attachments = [] irc_list = [] results = JSON.parse(response.text) # Malformed response unless results.photos? return msg.send "Empty response from API." # Put together the count summary count = results.photos.photo.length if count == 0 return msg.send "No photos found. :cry:" summary = "There are #{results.photos.total} photos in the group that match your search. Here are the #{count} most recent:" # Loop through the response _(results.photos.photo).each (photo, i) -> # Piece together from the photos photo_src = "https://c1.staticflickr.com/#{photo.farm}/#{photo.server}/#{photo.id}_#{photo.secret}_b.jpg" photo_url = "https://flickr.com/photos/#{photo.owner}/#{photo.id}" # Slack attachments attachments.push { title: photo.title, title_link: photo_url, image_url: photo_src, author_name: "<NAME>", author_link: "https://flickr.com/groups/#{flickrGroupId}", author_icon: "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png" } # Non-slack content irc_list.push "- #{photo_url} - #{photo.title}" # Send the message switch robot.adapterName when 'slack' payload = { text: summary, fallback: summary + "\n" + irc_list.join("\n"), attachments: attachments, unfurl_links: false } msg.send payload # Non-slack response else msg.reply summary msg.send irc_list.join("\n") ) .catch (err) -> msg.reply "Sorry, unable to retrieve photos. :cry:" robot.logger.error err # Check for required config missingEnvironmentForApi = (msg) -> missingAnything = false unless process.env.HUBOT_FLICKR_API_KEY? msg.send "Flickr API Key is missing: Ensure that HUBOT_FLICKR_API_KEY is set." missingAnything |= true unless process.env.HUBOT_FLICKR_GROUP_ID? msg.send "Flickr Group ID is missing: Ensure that HUBOT_FLICKR_GROUP_ID is set." missingAnything |= true missingAnything
true
# Description # Search a specified Flickr group for photos. # # Configuration: # HUBOT_FLICKR_API_KEY - API key # HUBOT_FLICKR_GROUP_ID - Group ID to search # # Commands: # hubot photos <term> - Search for a particular search term in the group # # Author: # stephenyeargin _ = require 'lodash' Flickr = require 'flickr-sdk' # Configure the library flickr = new Flickr(process.env.HUBOT_FLICKR_API_KEY) module.exports = (robot) -> flickrGroupId = process.env.HUBOT_FLICKR_GROUP_ID robot.respond /(?:photo|photos) (.*)/i, (msg) -> if missingEnvironmentForApi(msg) return msg.reply "Retrieving photos matching: \"#{msg.match[1]}\"" # Making the request from Flickr flickr.photos.search( text: msg.match[1] page: 1, per_page: 5, group_id: flickrGroupId, media: 'photos' sort: 'date-taken-desc' ) .then ((response) -> attachments = [] irc_list = [] results = JSON.parse(response.text) # Malformed response unless results.photos? return msg.send "Empty response from API." # Put together the count summary count = results.photos.photo.length if count == 0 return msg.send "No photos found. :cry:" summary = "There are #{results.photos.total} photos in the group that match your search. Here are the #{count} most recent:" # Loop through the response _(results.photos.photo).each (photo, i) -> # Piece together from the photos photo_src = "https://c1.staticflickr.com/#{photo.farm}/#{photo.server}/#{photo.id}_#{photo.secret}_b.jpg" photo_url = "https://flickr.com/photos/#{photo.owner}/#{photo.id}" # Slack attachments attachments.push { title: photo.title, title_link: photo_url, image_url: photo_src, author_name: "PI:NAME:<NAME>END_PI", author_link: "https://flickr.com/groups/#{flickrGroupId}", author_icon: "https://s.yimg.com/pw/images/goodies/white-large-chiclet.png" } # Non-slack content irc_list.push "- #{photo_url} - #{photo.title}" # Send the message switch robot.adapterName when 'slack' payload = { text: summary, fallback: summary + "\n" + irc_list.join("\n"), attachments: attachments, unfurl_links: false } msg.send payload # Non-slack response else msg.reply summary msg.send irc_list.join("\n") ) .catch (err) -> msg.reply "Sorry, unable to retrieve photos. :cry:" robot.logger.error err # Check for required config missingEnvironmentForApi = (msg) -> missingAnything = false unless process.env.HUBOT_FLICKR_API_KEY? msg.send "Flickr API Key is missing: Ensure that HUBOT_FLICKR_API_KEY is set." missingAnything |= true unless process.env.HUBOT_FLICKR_GROUP_ID? msg.send "Flickr Group ID is missing: Ensure that HUBOT_FLICKR_GROUP_ID is set." missingAnything |= true missingAnything
[ { "context": "amer.Info =\n\ttitle: \"Speech Recog Demo\"\n\tauthor: \"Tony\"\n\ttwitter: \"TonyJing\"\n\tdescription: \"A rebound of", "end": 163, "score": 0.9781091213226318, "start": 159, "tag": "NAME", "value": "Tony" }, { "context": "e: \"Speech Recog Demo\"\n\tauthor: \"Tony\"\...
54speech.framer/app.coffee
gremjua-forks/100daysofframer
26
# Project Info # This info is presented in a widget when you share. # http://framerjs.com/docs/#info.info Framer.Info = title: "Speech Recog Demo" author: "Tony" twitter: "TonyJing" description: "A rebound of Brian Bailey's Speech Recog demo." # Variables promptWidth = Screen.width / 1.5 numAudioBumps = Math.floor(Utils.randomChoice([12,17])) # Layers and Animations prompt = new Layer size: promptWidth x: Align.center, y: Align.center(-150) backgroundColor: "", html: "What can I help you with?" style: textAlign: "center", fontSize: "4.1rem", lineHeight: "5rem" fontFamily: "Helvetica Neue", fontWeight: 300 prompt.states.add hide: opacity: 0 text = new Layer width: Screen.width-60, x: 30, y: 50, backgroundColor: "" style: fontSize: "2.6rem", lineHeight: "3rem", fontWeight: 300, textAlign: "right" bumpContainer = new Layer size: Screen.size, backgroundColor: "", opacity: 0 bumpContainer.states.add show: opacity: 1 lineContainer = bumpContainer.copy() lineContainer.states.add show: opacity: 1 mic = new Layer width: 555/12, height: 1024/12 x: Align.center, y: Align.center(560), image: "images/MikeThePhone.png" mic.states.add hide: opacity: 0 mic.states.animationOptions = time: 0.3 createAudioBumps = -> for i in [0..numAudioBumps] audioBump = new Layer width: Utils.randomNumber(120, 320), height: Utils.randomNumber(20, 120) borderRadius: "100%", backgroundColor: Utils.randomColor().lighten(10) opacity: 0.26, scaleY: 0.1, parent: bumpContainer y: Align.center(560), x: Align.center(Utils.randomNumber(-150,150)) current = audioBump audioBumpLine = audioBump.copy() audioBumpLine.props = blur: 0, parent: bumpContainer height: Utils.randomNumber(5, 20), backgroundColor: "#fff" opacity: 1, scaleY: 0.1, y: Align.center(560) jumpUpA = new Animation layer: audioBump properties: scaleY: Utils.randomNumber(1, 1.3) scaleX: Utils.randomNumber(1, 1.15) time: Utils.randomNumber(0.2, 0.5), curve: "ease-out" delay: Utils.randomNumber(0, 0.2) jumpUpB = new Animation layer: audioBump properties: scaleY: Utils.randomNumber(0.5, 0.7) scaleX: Utils.randomNumber(0.8, 0.9) time: Utils.randomNumber(0.15, 0.25), curve: "ease-out" delay: Utils.randomNumber(0, 0.3) jumpUpLineA = new Animation layer: audioBumpLine properties: scaleY: Utils.randomNumber(1.2, 2.3) scaleX: Utils.randomNumber(1, 1.15) time: Utils.randomNumber(0.2, 0.5), curve: "ease-out" delay: Utils.randomNumber(0, 0.3) jumpUpLineB = new Animation layer: audioBumpLine properties: scaleY: Utils.randomNumber(0.55, 0.8) scaleX: Utils.randomNumber(0.8, 0.9) time: Utils.randomNumber(0.2, 0.5), curve: "ease-out" delay: Utils.randomNumber(0, 0.3) jumpUpA.on(Events.AnimationEnd, jumpUpB.start) jumpUpB.on(Events.AnimationEnd, jumpUpA.start) jumpUpLineA.on(Events.AnimationEnd, jumpUpLineB.start) jumpUpLineB.on(Events.AnimationEnd, jumpUpLineA.start) jumpUpA.start() jumpUpLineA.start() line = new Layer width: Screen.width/1.1, height: 3, backgroundColor: "#fff" y: Align.center(560), x: Align.center parent: lineContainer lineCenter = line.copy() lineCenter.props = width: promptWidth, height: 9, x: Align.center, y: Align.center(560) borderRadius: "50%", backgroundColor: "#fff", parent: lineContainer shadowColor: "#fff", shadowBlur: 5, shadowSpread: 2 lineCenterA = new Animation layer: lineCenter properties: scaleY: Utils.randomNumber(1.2, 1.9) scaleX: Utils.randomNumber(1, 1.15) time: Utils.randomNumber(0.3, 0.55), curve: "ease-out" delay: Utils.randomNumber(0, 0.2) lineCenterB = new Animation layer: lineCenter properties: scaleY: Utils.randomNumber(0.9, 1.1) scaleX: Utils.randomNumber(0.9, 1.1) time: Utils.randomNumber(0.45, 0.55), curve: "ease-out" delay: Utils.randomNumber(0, 0.2) lineCenterA.on(Events.AnimationEnd, lineCenterB.start) lineCenterB.on(Events.AnimationEnd, lineCenterA.start) # Speech Recognition API # This API is currently prefixed in Chrome SpeechRecognition = window.SpeechRecognition or window.webkitSpeechRecognition recognizer = new SpeechRecognition recognizer.interimResults = true recognizer.lang = 'en-US' # Events mic.onClick -> bumpContainer.states.switch("show") lineContainer.states.switch("show") lineCenterA.start() mic.states.switch("hide") recognizer.start() recognizer.onspeechstart = (event) -> createAudioBumps() prompt.states.switch("hide") recognizer.onspeechend = (event) -> lineContainer.states.switch("default") bumpContainer.states.switch("default") Utils.delay 0.8, -> mic.states.switch("default") for layer in bumpContainer.subLayers layer.destroy() recognizer.onresult = (event) -> result = event.results[event.resultIndex] if result.isFinal # print 'You said: ' + result[0].transcript text.html = result[0].transcript else # print 'Interim result', result[0].transcript text.html = result[0].transcript return
102055
# Project Info # This info is presented in a widget when you share. # http://framerjs.com/docs/#info.info Framer.Info = title: "Speech Recog Demo" author: "<NAME>" twitter: "TonyJing" description: "A rebound of Brian Bailey's Speech Recog demo." # Variables promptWidth = Screen.width / 1.5 numAudioBumps = Math.floor(Utils.randomChoice([12,17])) # Layers and Animations prompt = new Layer size: promptWidth x: Align.center, y: Align.center(-150) backgroundColor: "", html: "What can I help you with?" style: textAlign: "center", fontSize: "4.1rem", lineHeight: "5rem" fontFamily: "Helvetica Neue", fontWeight: 300 prompt.states.add hide: opacity: 0 text = new Layer width: Screen.width-60, x: 30, y: 50, backgroundColor: "" style: fontSize: "2.6rem", lineHeight: "3rem", fontWeight: 300, textAlign: "right" bumpContainer = new Layer size: Screen.size, backgroundColor: "", opacity: 0 bumpContainer.states.add show: opacity: 1 lineContainer = bumpContainer.copy() lineContainer.states.add show: opacity: 1 mic = new Layer width: 555/12, height: 1024/12 x: Align.center, y: Align.center(560), image: "images/MikeThePhone.png" mic.states.add hide: opacity: 0 mic.states.animationOptions = time: 0.3 createAudioBumps = -> for i in [0..numAudioBumps] audioBump = new Layer width: Utils.randomNumber(120, 320), height: Utils.randomNumber(20, 120) borderRadius: "100%", backgroundColor: Utils.randomColor().lighten(10) opacity: 0.26, scaleY: 0.1, parent: bumpContainer y: Align.center(560), x: Align.center(Utils.randomNumber(-150,150)) current = audioBump audioBumpLine = audioBump.copy() audioBumpLine.props = blur: 0, parent: bumpContainer height: Utils.randomNumber(5, 20), backgroundColor: "#fff" opacity: 1, scaleY: 0.1, y: Align.center(560) jumpUpA = new Animation layer: audioBump properties: scaleY: Utils.randomNumber(1, 1.3) scaleX: Utils.randomNumber(1, 1.15) time: Utils.randomNumber(0.2, 0.5), curve: "ease-out" delay: Utils.randomNumber(0, 0.2) jumpUpB = new Animation layer: audioBump properties: scaleY: Utils.randomNumber(0.5, 0.7) scaleX: Utils.randomNumber(0.8, 0.9) time: Utils.randomNumber(0.15, 0.25), curve: "ease-out" delay: Utils.randomNumber(0, 0.3) jumpUpLineA = new Animation layer: audioBumpLine properties: scaleY: Utils.randomNumber(1.2, 2.3) scaleX: Utils.randomNumber(1, 1.15) time: Utils.randomNumber(0.2, 0.5), curve: "ease-out" delay: Utils.randomNumber(0, 0.3) jumpUpLineB = new Animation layer: audioBumpLine properties: scaleY: Utils.randomNumber(0.55, 0.8) scaleX: Utils.randomNumber(0.8, 0.9) time: Utils.randomNumber(0.2, 0.5), curve: "ease-out" delay: Utils.randomNumber(0, 0.3) jumpUpA.on(Events.AnimationEnd, jumpUpB.start) jumpUpB.on(Events.AnimationEnd, jumpUpA.start) jumpUpLineA.on(Events.AnimationEnd, jumpUpLineB.start) jumpUpLineB.on(Events.AnimationEnd, jumpUpLineA.start) jumpUpA.start() jumpUpLineA.start() line = new Layer width: Screen.width/1.1, height: 3, backgroundColor: "#fff" y: Align.center(560), x: Align.center parent: lineContainer lineCenter = line.copy() lineCenter.props = width: promptWidth, height: 9, x: Align.center, y: Align.center(560) borderRadius: "50%", backgroundColor: "#fff", parent: lineContainer shadowColor: "#fff", shadowBlur: 5, shadowSpread: 2 lineCenterA = new Animation layer: lineCenter properties: scaleY: Utils.randomNumber(1.2, 1.9) scaleX: Utils.randomNumber(1, 1.15) time: Utils.randomNumber(0.3, 0.55), curve: "ease-out" delay: Utils.randomNumber(0, 0.2) lineCenterB = new Animation layer: lineCenter properties: scaleY: Utils.randomNumber(0.9, 1.1) scaleX: Utils.randomNumber(0.9, 1.1) time: Utils.randomNumber(0.45, 0.55), curve: "ease-out" delay: Utils.randomNumber(0, 0.2) lineCenterA.on(Events.AnimationEnd, lineCenterB.start) lineCenterB.on(Events.AnimationEnd, lineCenterA.start) # Speech Recognition API # This API is currently prefixed in Chrome SpeechRecognition = window.SpeechRecognition or window.webkitSpeechRecognition recognizer = new SpeechRecognition recognizer.interimResults = true recognizer.lang = 'en-US' # Events mic.onClick -> bumpContainer.states.switch("show") lineContainer.states.switch("show") lineCenterA.start() mic.states.switch("hide") recognizer.start() recognizer.onspeechstart = (event) -> createAudioBumps() prompt.states.switch("hide") recognizer.onspeechend = (event) -> lineContainer.states.switch("default") bumpContainer.states.switch("default") Utils.delay 0.8, -> mic.states.switch("default") for layer in bumpContainer.subLayers layer.destroy() recognizer.onresult = (event) -> result = event.results[event.resultIndex] if result.isFinal # print 'You said: ' + result[0].transcript text.html = result[0].transcript else # print 'Interim result', result[0].transcript text.html = result[0].transcript return
true
# Project Info # This info is presented in a widget when you share. # http://framerjs.com/docs/#info.info Framer.Info = title: "Speech Recog Demo" author: "PI:NAME:<NAME>END_PI" twitter: "TonyJing" description: "A rebound of Brian Bailey's Speech Recog demo." # Variables promptWidth = Screen.width / 1.5 numAudioBumps = Math.floor(Utils.randomChoice([12,17])) # Layers and Animations prompt = new Layer size: promptWidth x: Align.center, y: Align.center(-150) backgroundColor: "", html: "What can I help you with?" style: textAlign: "center", fontSize: "4.1rem", lineHeight: "5rem" fontFamily: "Helvetica Neue", fontWeight: 300 prompt.states.add hide: opacity: 0 text = new Layer width: Screen.width-60, x: 30, y: 50, backgroundColor: "" style: fontSize: "2.6rem", lineHeight: "3rem", fontWeight: 300, textAlign: "right" bumpContainer = new Layer size: Screen.size, backgroundColor: "", opacity: 0 bumpContainer.states.add show: opacity: 1 lineContainer = bumpContainer.copy() lineContainer.states.add show: opacity: 1 mic = new Layer width: 555/12, height: 1024/12 x: Align.center, y: Align.center(560), image: "images/MikeThePhone.png" mic.states.add hide: opacity: 0 mic.states.animationOptions = time: 0.3 createAudioBumps = -> for i in [0..numAudioBumps] audioBump = new Layer width: Utils.randomNumber(120, 320), height: Utils.randomNumber(20, 120) borderRadius: "100%", backgroundColor: Utils.randomColor().lighten(10) opacity: 0.26, scaleY: 0.1, parent: bumpContainer y: Align.center(560), x: Align.center(Utils.randomNumber(-150,150)) current = audioBump audioBumpLine = audioBump.copy() audioBumpLine.props = blur: 0, parent: bumpContainer height: Utils.randomNumber(5, 20), backgroundColor: "#fff" opacity: 1, scaleY: 0.1, y: Align.center(560) jumpUpA = new Animation layer: audioBump properties: scaleY: Utils.randomNumber(1, 1.3) scaleX: Utils.randomNumber(1, 1.15) time: Utils.randomNumber(0.2, 0.5), curve: "ease-out" delay: Utils.randomNumber(0, 0.2) jumpUpB = new Animation layer: audioBump properties: scaleY: Utils.randomNumber(0.5, 0.7) scaleX: Utils.randomNumber(0.8, 0.9) time: Utils.randomNumber(0.15, 0.25), curve: "ease-out" delay: Utils.randomNumber(0, 0.3) jumpUpLineA = new Animation layer: audioBumpLine properties: scaleY: Utils.randomNumber(1.2, 2.3) scaleX: Utils.randomNumber(1, 1.15) time: Utils.randomNumber(0.2, 0.5), curve: "ease-out" delay: Utils.randomNumber(0, 0.3) jumpUpLineB = new Animation layer: audioBumpLine properties: scaleY: Utils.randomNumber(0.55, 0.8) scaleX: Utils.randomNumber(0.8, 0.9) time: Utils.randomNumber(0.2, 0.5), curve: "ease-out" delay: Utils.randomNumber(0, 0.3) jumpUpA.on(Events.AnimationEnd, jumpUpB.start) jumpUpB.on(Events.AnimationEnd, jumpUpA.start) jumpUpLineA.on(Events.AnimationEnd, jumpUpLineB.start) jumpUpLineB.on(Events.AnimationEnd, jumpUpLineA.start) jumpUpA.start() jumpUpLineA.start() line = new Layer width: Screen.width/1.1, height: 3, backgroundColor: "#fff" y: Align.center(560), x: Align.center parent: lineContainer lineCenter = line.copy() lineCenter.props = width: promptWidth, height: 9, x: Align.center, y: Align.center(560) borderRadius: "50%", backgroundColor: "#fff", parent: lineContainer shadowColor: "#fff", shadowBlur: 5, shadowSpread: 2 lineCenterA = new Animation layer: lineCenter properties: scaleY: Utils.randomNumber(1.2, 1.9) scaleX: Utils.randomNumber(1, 1.15) time: Utils.randomNumber(0.3, 0.55), curve: "ease-out" delay: Utils.randomNumber(0, 0.2) lineCenterB = new Animation layer: lineCenter properties: scaleY: Utils.randomNumber(0.9, 1.1) scaleX: Utils.randomNumber(0.9, 1.1) time: Utils.randomNumber(0.45, 0.55), curve: "ease-out" delay: Utils.randomNumber(0, 0.2) lineCenterA.on(Events.AnimationEnd, lineCenterB.start) lineCenterB.on(Events.AnimationEnd, lineCenterA.start) # Speech Recognition API # This API is currently prefixed in Chrome SpeechRecognition = window.SpeechRecognition or window.webkitSpeechRecognition recognizer = new SpeechRecognition recognizer.interimResults = true recognizer.lang = 'en-US' # Events mic.onClick -> bumpContainer.states.switch("show") lineContainer.states.switch("show") lineCenterA.start() mic.states.switch("hide") recognizer.start() recognizer.onspeechstart = (event) -> createAudioBumps() prompt.states.switch("hide") recognizer.onspeechend = (event) -> lineContainer.states.switch("default") bumpContainer.states.switch("default") Utils.delay 0.8, -> mic.states.switch("default") for layer in bumpContainer.subLayers layer.destroy() recognizer.onresult = (event) -> result = event.results[event.resultIndex] if result.isFinal # print 'You said: ' + result[0].transcript text.html = result[0].transcript else # print 'Interim result', result[0].transcript text.html = result[0].transcript return
[ { "context": "turn hash\n\nstart = new Date().getTime();\nprkey = \"8e8f61c213e6ad81888bca3972a3adac6df6f1f40303b910dd3a6b04a2137175\"\nkey = ec.keyFromPrivate(prkey,'hex');;\n\nusername", "end": 320, "score": 0.9996070861816406, "start": 256, "tag": "KEY", "value": "8e8f61c213e6ad81888bca39...
perfomance_simulations/idbp/client_argon.coffee
lucy7li/compromised-credential-checking
6
crypto = require 'crypto'; ecc = require 'elliptic'; fs = require 'fs'; argon2 = require 'argon2'; EC = ecc.ec; ec = new EC('secp256k1'); get_hash = (str) => hash = await argon2.hash(str); return hash start = new Date().getTime(); prkey = "8e8f61c213e6ad81888bca3972a3adac6df6f1f40303b910dd3a6b04a2137175" key = ec.keyFromPrivate(prkey,'hex');; username = "V11@email.cz" password = "slovensko1" str = username.concat(password) start = new Date().getTime(); msg = crypto.createHash("sha256").update(str).digest('hex'); msg = crypto.createHash("sha256").update(str).digest('hex'); msg = crypto.createHash("sha256").update(str).digest('hex'); elapsed = new Date().getTime() - start; console.log elapsed key_user = ec.keyFromPrivate(msg,'hex'); public_key = key_user.getPublic().mul(key.getPrivate()).encode('hex') console.log public_key console.log msg prkey = "8e8f61c213e6ad81888bca3972a3adac6df6f1f40303b910dd3a6b04a2137175" key = ec.keyFromPrivate(prkey,'hex');; username = "V11@email.cz" password = "slovensko1" str = username.concat(password) start = new Date().getTime(); hash = get_hash(str) hash = get_hash(str) hash = get_hash(str) elapsed = new Date().getTime() - start; #msg = crypto.createHash("sha256").update(str).digest('hex'); key_user = ec.keyFromPrivate(msg,'hex'); public_key = key_user.getPublic().mul(key.getPrivate()).encode('hex') console.log public_key console.log hash console.log elapsed
1973
crypto = require 'crypto'; ecc = require 'elliptic'; fs = require 'fs'; argon2 = require 'argon2'; EC = ecc.ec; ec = new EC('secp256k1'); get_hash = (str) => hash = await argon2.hash(str); return hash start = new Date().getTime(); prkey = "<KEY>" key = ec.keyFromPrivate(prkey,'hex');; username = "<EMAIL>" password = "<PASSWORD>" str = username.concat(password) start = new Date().getTime(); msg = crypto.createHash("sha256").update(str).digest('hex'); msg = crypto.createHash("sha256").update(str).digest('hex'); msg = crypto.createHash("sha256").update(str).digest('hex'); elapsed = new Date().getTime() - start; console.log elapsed key_user = ec.keyFromPrivate(msg,'hex'); public_key = key_user.getPublic().mul(key.getPrivate()).encode('hex') console.log public_key console.log msg prkey = "<KEY>" key = ec.keyFromPrivate(prkey,'hex');; username = "<EMAIL>" password = "<PASSWORD>" str = username.concat(password) start = new Date().getTime(); hash = get_hash(str) hash = get_hash(str) hash = get_hash(str) elapsed = new Date().getTime() - start; #msg = crypto.createHash("sha256").update(str).digest('hex'); key_user = ec.keyFromPrivate(msg,'hex'); public_key = key_user.getPublic().mul(key.getPrivate()).encode('hex') console.log public_key console.log hash console.log elapsed
true
crypto = require 'crypto'; ecc = require 'elliptic'; fs = require 'fs'; argon2 = require 'argon2'; EC = ecc.ec; ec = new EC('secp256k1'); get_hash = (str) => hash = await argon2.hash(str); return hash start = new Date().getTime(); prkey = "PI:KEY:<KEY>END_PI" key = ec.keyFromPrivate(prkey,'hex');; username = "PI:EMAIL:<EMAIL>END_PI" password = "PI:PASSWORD:<PASSWORD>END_PI" str = username.concat(password) start = new Date().getTime(); msg = crypto.createHash("sha256").update(str).digest('hex'); msg = crypto.createHash("sha256").update(str).digest('hex'); msg = crypto.createHash("sha256").update(str).digest('hex'); elapsed = new Date().getTime() - start; console.log elapsed key_user = ec.keyFromPrivate(msg,'hex'); public_key = key_user.getPublic().mul(key.getPrivate()).encode('hex') console.log public_key console.log msg prkey = "PI:KEY:<KEY>END_PI" key = ec.keyFromPrivate(prkey,'hex');; username = "PI:EMAIL:<EMAIL>END_PI" password = "PI:PASSWORD:<PASSWORD>END_PI" str = username.concat(password) start = new Date().getTime(); hash = get_hash(str) hash = get_hash(str) hash = get_hash(str) elapsed = new Date().getTime() - start; #msg = crypto.createHash("sha256").update(str).digest('hex'); key_user = ec.keyFromPrivate(msg,'hex'); public_key = key_user.getPublic().mul(key.getPrivate()).encode('hex') console.log public_key console.log hash console.log elapsed
[ { "context": " _createGetter:(property)->\n key = \"get\"+property.capitalize()\n @[key]?= ->\n @[\"_\"+pro", "end": 500, "score": 0.9765232801437378, "start": 479, "tag": "KEY", "value": "property.capitalize()" }, { "context": "al,listenerFunctio...
src/coffee/coordinates/utils/BaseClass.coffee
Mparaiso/Coordinates.js
1
define (require)-> class BaseClass ### @TODO implement mixins ### initConfig:(config=null,listenerFunction=null)-> ### set default properties from which getters and setters will be generated ### if config for own key,value of config @_createGetter(key) @_createSetter(key,value,listenerFunction) return _createGetter:(property)-> key = "get"+property.capitalize() @[key]?= -> @["_"+property] return _createSetter:(property,val,listenerFunction=null)-> key = "set"+property.capitalize() @[key]?= (value)-> @["_"+property] = value if listenerFunction && listenerFunction instanceof Function listenerFunction.call(this) @[key](val) return
142506
define (require)-> class BaseClass ### @TODO implement mixins ### initConfig:(config=null,listenerFunction=null)-> ### set default properties from which getters and setters will be generated ### if config for own key,value of config @_createGetter(key) @_createSetter(key,value,listenerFunction) return _createGetter:(property)-> key = "get"+<KEY> @[key]?= -> @["_"+property] return _createSetter:(property,val,listenerFunction=null)-> key = "set"+<KEY> @[key]?= (value)-> @["_"+property] = value if listenerFunction && listenerFunction instanceof Function listenerFunction.call(this) @[key](val) return
true
define (require)-> class BaseClass ### @TODO implement mixins ### initConfig:(config=null,listenerFunction=null)-> ### set default properties from which getters and setters will be generated ### if config for own key,value of config @_createGetter(key) @_createSetter(key,value,listenerFunction) return _createGetter:(property)-> key = "get"+PI:KEY:<KEY>END_PI @[key]?= -> @["_"+property] return _createSetter:(property,val,listenerFunction=null)-> key = "set"+PI:KEY:<KEY>END_PI @[key]?= (value)-> @["_"+property] = value if listenerFunction && listenerFunction instanceof Function listenerFunction.call(this) @[key](val) return
[ { "context": " beforeEach (done) ->\n auth =\n username: 'ai-turns-hostile'\n password: 'team-token'\n\n options =\n ", "end": 889, "score": 0.9996179938316345, "start": 873, "tag": "USERNAME", "value": "ai-turns-hostile" }, { "context": " username: 'ai-turns-ho...
test/integration/all-triggers-spec.coffee
octoblu/triggers-service
5
_ = require 'lodash' http = require 'http' request = require 'request' shmock = require 'shmock' Server = require '../../src/server' fakeFlow = require './fake-flow.json' enableDestroy = require 'server-destroy' describe 'GET /all-triggers', -> beforeEach (done) -> @meshblu = shmock done enableDestroy @meshblu afterEach (done) -> @meshblu.destroy done beforeEach (done) -> meshbluConfig = hostname: 'localhost' port: @meshblu.address().port protocol: 'http' serverOptions = port: undefined, disableLogging: true meshbluConfig: meshbluConfig @server = new Server serverOptions @server.run => @serverPort = @server.address().port done() afterEach (done) -> @server.stop => done() beforeEach (done) -> auth = username: 'ai-turns-hostile' password: 'team-token' options = auth: auth json: true @meshblu.post('/authenticate') .reply 200, uuid: 'ai-turns-hostile', token: 'team-token' @getHandler = @meshblu.get('/v2/devices') .query(type:'octoblu:flow', online: 'true') .reply 200, [fakeFlow] request.get "http://localhost:#{@serverPort}/all-triggers", options, (error, @response, @body) => done error it 'should return the triggers', -> expect(@response.statusCode).to.equal 200 expect(@getHandler.isDone).to.be.true expect(_.size(@body)).to.equal 1 expect(@body[0]).to.contain id: '562f4090-9ed8-11e5-bf39-09fc31cb0cf0'
87146
_ = require 'lodash' http = require 'http' request = require 'request' shmock = require 'shmock' Server = require '../../src/server' fakeFlow = require './fake-flow.json' enableDestroy = require 'server-destroy' describe 'GET /all-triggers', -> beforeEach (done) -> @meshblu = shmock done enableDestroy @meshblu afterEach (done) -> @meshblu.destroy done beforeEach (done) -> meshbluConfig = hostname: 'localhost' port: @meshblu.address().port protocol: 'http' serverOptions = port: undefined, disableLogging: true meshbluConfig: meshbluConfig @server = new Server serverOptions @server.run => @serverPort = @server.address().port done() afterEach (done) -> @server.stop => done() beforeEach (done) -> auth = username: 'ai-turns-hostile' password: '<PASSWORD>' options = auth: auth json: true @meshblu.post('/authenticate') .reply 200, uuid: 'ai-turns-hostile', token: 'team-token' @getHandler = @meshblu.get('/v2/devices') .query(type:'octoblu:flow', online: 'true') .reply 200, [fakeFlow] request.get "http://localhost:#{@serverPort}/all-triggers", options, (error, @response, @body) => done error it 'should return the triggers', -> expect(@response.statusCode).to.equal 200 expect(@getHandler.isDone).to.be.true expect(_.size(@body)).to.equal 1 expect(@body[0]).to.contain id: '562f4090-9ed8-11e5-bf39-09fc31cb0cf0'
true
_ = require 'lodash' http = require 'http' request = require 'request' shmock = require 'shmock' Server = require '../../src/server' fakeFlow = require './fake-flow.json' enableDestroy = require 'server-destroy' describe 'GET /all-triggers', -> beforeEach (done) -> @meshblu = shmock done enableDestroy @meshblu afterEach (done) -> @meshblu.destroy done beforeEach (done) -> meshbluConfig = hostname: 'localhost' port: @meshblu.address().port protocol: 'http' serverOptions = port: undefined, disableLogging: true meshbluConfig: meshbluConfig @server = new Server serverOptions @server.run => @serverPort = @server.address().port done() afterEach (done) -> @server.stop => done() beforeEach (done) -> auth = username: 'ai-turns-hostile' password: 'PI:PASSWORD:<PASSWORD>END_PI' options = auth: auth json: true @meshblu.post('/authenticate') .reply 200, uuid: 'ai-turns-hostile', token: 'team-token' @getHandler = @meshblu.get('/v2/devices') .query(type:'octoblu:flow', online: 'true') .reply 200, [fakeFlow] request.get "http://localhost:#{@serverPort}/all-triggers", options, (error, @response, @body) => done error it 'should return the triggers', -> expect(@response.statusCode).to.equal 200 expect(@getHandler.isDone).to.be.true expect(_.size(@body)).to.equal 1 expect(@body[0]).to.contain id: '562f4090-9ed8-11e5-bf39-09fc31cb0cf0'
[ { "context": "###\n# Copyright (C) 2014-2015 Taiga Agile LLC <taiga@taiga.io>\n#\n# This program is free software: you can redis", "end": 61, "score": 0.9999275803565979, "start": 47, "tag": "EMAIL", "value": "taiga@taiga.io" } ]
app/modules/components/tags/tag-line-common/tag-line-common.controller.spec.coffee
threefoldtech/Threefold-Circles-front
0
### # Copyright (C) 2014-2015 Taiga Agile LLC <taiga@taiga.io> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File:tag-line-common.controller.spec.coffee ### describe "TagLineCommon", -> provide = null controller = null TagLineCommonCtrl = null mocks = {} _mockTgTagLineService = () -> mocks.tgTagLineService = { checkPermissions: sinon.stub() createColorsArray: sinon.stub() renderTags: sinon.stub() } provide.value "tgTagLineService", mocks.tgTagLineService _mocks = () -> module ($provide) -> provide = $provide _mockTgTagLineService() return null beforeEach -> module "taigaCommon" _mocks() inject ($controller) -> controller = $controller TagLineCommonCtrl = controller "TagLineCommonCtrl" TagLineCommonCtrl.tags = [] TagLineCommonCtrl.colorArray = [] TagLineCommonCtrl.addTag = false it "check permissions", () -> TagLineCommonCtrl.project = { } TagLineCommonCtrl.project.my_permissions = [ 'permission1', 'permission2' ] TagLineCommonCtrl.permissions = 'permissions1' TagLineCommonCtrl.checkPermissions() expect(mocks.tgTagLineService.checkPermissions).have.been.calledWith(TagLineCommonCtrl.project.my_permissions, TagLineCommonCtrl.permissions) it "create Colors Array", () -> projectTagColors = 'string' mocks.tgTagLineService.createColorsArray.withArgs(projectTagColors).returns(true) TagLineCommonCtrl._createColorsArray(projectTagColors) expect(TagLineCommonCtrl.colorArray).to.be.equal(true) it "display tag input", () -> TagLineCommonCtrl.addTag = false TagLineCommonCtrl.displayTagInput() expect(TagLineCommonCtrl.addTag).to.be.true it "on add tag", () -> TagLineCommonCtrl.loadingAddTag = true tag = 'tag1' tags = ['tag1', 'tag2'] color = "CC0000" TagLineCommonCtrl.project = { tags: ['tag1', 'tag2'], tags_colors: ["#CC0000", "CCBB00"] } TagLineCommonCtrl.onAddTag = sinon.spy() TagLineCommonCtrl.newTag = {name: "11", color: "22"} TagLineCommonCtrl.addNewTag(tag, color) expect(TagLineCommonCtrl.onAddTag).have.been.calledWith({name: tag, color: color}) expect(TagLineCommonCtrl.newTag.name).to.be.eql("") expect(TagLineCommonCtrl.newTag.color).to.be.null
90494
### # Copyright (C) 2014-2015 Taiga Agile LLC <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File:tag-line-common.controller.spec.coffee ### describe "TagLineCommon", -> provide = null controller = null TagLineCommonCtrl = null mocks = {} _mockTgTagLineService = () -> mocks.tgTagLineService = { checkPermissions: sinon.stub() createColorsArray: sinon.stub() renderTags: sinon.stub() } provide.value "tgTagLineService", mocks.tgTagLineService _mocks = () -> module ($provide) -> provide = $provide _mockTgTagLineService() return null beforeEach -> module "taigaCommon" _mocks() inject ($controller) -> controller = $controller TagLineCommonCtrl = controller "TagLineCommonCtrl" TagLineCommonCtrl.tags = [] TagLineCommonCtrl.colorArray = [] TagLineCommonCtrl.addTag = false it "check permissions", () -> TagLineCommonCtrl.project = { } TagLineCommonCtrl.project.my_permissions = [ 'permission1', 'permission2' ] TagLineCommonCtrl.permissions = 'permissions1' TagLineCommonCtrl.checkPermissions() expect(mocks.tgTagLineService.checkPermissions).have.been.calledWith(TagLineCommonCtrl.project.my_permissions, TagLineCommonCtrl.permissions) it "create Colors Array", () -> projectTagColors = 'string' mocks.tgTagLineService.createColorsArray.withArgs(projectTagColors).returns(true) TagLineCommonCtrl._createColorsArray(projectTagColors) expect(TagLineCommonCtrl.colorArray).to.be.equal(true) it "display tag input", () -> TagLineCommonCtrl.addTag = false TagLineCommonCtrl.displayTagInput() expect(TagLineCommonCtrl.addTag).to.be.true it "on add tag", () -> TagLineCommonCtrl.loadingAddTag = true tag = 'tag1' tags = ['tag1', 'tag2'] color = "CC0000" TagLineCommonCtrl.project = { tags: ['tag1', 'tag2'], tags_colors: ["#CC0000", "CCBB00"] } TagLineCommonCtrl.onAddTag = sinon.spy() TagLineCommonCtrl.newTag = {name: "11", color: "22"} TagLineCommonCtrl.addNewTag(tag, color) expect(TagLineCommonCtrl.onAddTag).have.been.calledWith({name: tag, color: color}) expect(TagLineCommonCtrl.newTag.name).to.be.eql("") expect(TagLineCommonCtrl.newTag.color).to.be.null
true
### # Copyright (C) 2014-2015 Taiga Agile LLC <PI:EMAIL:<EMAIL>END_PI> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File:tag-line-common.controller.spec.coffee ### describe "TagLineCommon", -> provide = null controller = null TagLineCommonCtrl = null mocks = {} _mockTgTagLineService = () -> mocks.tgTagLineService = { checkPermissions: sinon.stub() createColorsArray: sinon.stub() renderTags: sinon.stub() } provide.value "tgTagLineService", mocks.tgTagLineService _mocks = () -> module ($provide) -> provide = $provide _mockTgTagLineService() return null beforeEach -> module "taigaCommon" _mocks() inject ($controller) -> controller = $controller TagLineCommonCtrl = controller "TagLineCommonCtrl" TagLineCommonCtrl.tags = [] TagLineCommonCtrl.colorArray = [] TagLineCommonCtrl.addTag = false it "check permissions", () -> TagLineCommonCtrl.project = { } TagLineCommonCtrl.project.my_permissions = [ 'permission1', 'permission2' ] TagLineCommonCtrl.permissions = 'permissions1' TagLineCommonCtrl.checkPermissions() expect(mocks.tgTagLineService.checkPermissions).have.been.calledWith(TagLineCommonCtrl.project.my_permissions, TagLineCommonCtrl.permissions) it "create Colors Array", () -> projectTagColors = 'string' mocks.tgTagLineService.createColorsArray.withArgs(projectTagColors).returns(true) TagLineCommonCtrl._createColorsArray(projectTagColors) expect(TagLineCommonCtrl.colorArray).to.be.equal(true) it "display tag input", () -> TagLineCommonCtrl.addTag = false TagLineCommonCtrl.displayTagInput() expect(TagLineCommonCtrl.addTag).to.be.true it "on add tag", () -> TagLineCommonCtrl.loadingAddTag = true tag = 'tag1' tags = ['tag1', 'tag2'] color = "CC0000" TagLineCommonCtrl.project = { tags: ['tag1', 'tag2'], tags_colors: ["#CC0000", "CCBB00"] } TagLineCommonCtrl.onAddTag = sinon.spy() TagLineCommonCtrl.newTag = {name: "11", color: "22"} TagLineCommonCtrl.addNewTag(tag, color) expect(TagLineCommonCtrl.onAddTag).have.been.calledWith({name: tag, color: color}) expect(TagLineCommonCtrl.newTag.name).to.be.eql("") expect(TagLineCommonCtrl.newTag.color).to.be.null
[ { "context": "rs = [\n {\n id: 1,\n firstName: 'Ownie',\n lastName: 'Owner',\n memberPaymen", "end": 144, "score": 0.9995697736740112, "start": 139, "tag": "NAME", "value": "Ownie" }, { "context": "1,\n firstName: 'Ownie',\n lastName: 'O...
test/memberPayments.coffee
teamsnap/teamsnap-javascript-sdk
9
memberPayment = {} describe 'Member Payments', -> beforeEach (done) -> team.members = [ { id: 1, firstName: 'Ownie', lastName: 'Owner', memberPayments: [ { type: 'memberPayment', id: 222, amountDue: 100.00, amountPaid: 50.00, memberId: 1, teamId: team.id } ] } ] memberPayment = team.members[0].memberPayments[0] done() describe 'loadMemberPayments', -> it 'should be able to load all member payments for team', -> teamsnap.loadMemberPayments team.id, (err, result) -> expect(err).to.be.null result.should.be.an('array') describe 'memberPaymentTransaction', -> it 'should accept a memberPayment object', -> teamsnap.memberPaymentTransaction memberPayment, 4, (err, result) -> result.id.should.equal 222 it 'should accept a memberPaymentId', -> teamsnap.memberPaymentTransaction memberPayment.id, 10.00, (err, result) -> result.id.should.equal 222 it 'should adjust memberPayment.amoutPaid', -> teamsnap.memberPaymentTransaction memberPayment.id, 10.00, (err, result) -> result.amountPaid.should.equal 90.00
12981
memberPayment = {} describe 'Member Payments', -> beforeEach (done) -> team.members = [ { id: 1, firstName: '<NAME>', lastName: '<NAME>', memberPayments: [ { type: 'memberPayment', id: 222, amountDue: 100.00, amountPaid: 50.00, memberId: 1, teamId: team.id } ] } ] memberPayment = team.members[0].memberPayments[0] done() describe 'loadMemberPayments', -> it 'should be able to load all member payments for team', -> teamsnap.loadMemberPayments team.id, (err, result) -> expect(err).to.be.null result.should.be.an('array') describe 'memberPaymentTransaction', -> it 'should accept a memberPayment object', -> teamsnap.memberPaymentTransaction memberPayment, 4, (err, result) -> result.id.should.equal 222 it 'should accept a memberPaymentId', -> teamsnap.memberPaymentTransaction memberPayment.id, 10.00, (err, result) -> result.id.should.equal 222 it 'should adjust memberPayment.amoutPaid', -> teamsnap.memberPaymentTransaction memberPayment.id, 10.00, (err, result) -> result.amountPaid.should.equal 90.00
true
memberPayment = {} describe 'Member Payments', -> beforeEach (done) -> team.members = [ { id: 1, firstName: 'PI:NAME:<NAME>END_PI', lastName: 'PI:NAME:<NAME>END_PI', memberPayments: [ { type: 'memberPayment', id: 222, amountDue: 100.00, amountPaid: 50.00, memberId: 1, teamId: team.id } ] } ] memberPayment = team.members[0].memberPayments[0] done() describe 'loadMemberPayments', -> it 'should be able to load all member payments for team', -> teamsnap.loadMemberPayments team.id, (err, result) -> expect(err).to.be.null result.should.be.an('array') describe 'memberPaymentTransaction', -> it 'should accept a memberPayment object', -> teamsnap.memberPaymentTransaction memberPayment, 4, (err, result) -> result.id.should.equal 222 it 'should accept a memberPaymentId', -> teamsnap.memberPaymentTransaction memberPayment.id, 10.00, (err, result) -> result.id.should.equal 222 it 'should adjust memberPayment.amoutPaid', -> teamsnap.memberPaymentTransaction memberPayment.id, 10.00, (err, result) -> result.amountPaid.should.equal 90.00