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": "= new Date();\n\n\t\tif doc.password\n\t\t\tdoc.password = Steedos.encrypt(doc.password, doc.email, cryptIvForMail);\n\n\tdb.ma", "end": 1405, "score": 0.9959148168563843, "start": 1390, "tag": "PASSWORD", "value": "Steedos.encrypt" }, { "context": "modifier.$set.passwo...
creator/packages/steedos-app-mailbase/models/mail_accounts.coffee
yicone/steedos-platform
42
db.mail_accounts = new Meteor.Collection('mail_accounts') db.mail_accounts.allow update: (userId, doc, fields, modifier) -> return doc.owner == userId; insert: (userId, doc, fields, modifier) -> return doc.owner == userId; # db.mail_accounts._simpleSchema = new SimpleSchema Creator.Objects.mail_accounts = name: "mail_accounts" label: "邮件账户" icon: "apps" fields: email: label: "邮箱账户" type: "text" is_name:true required: true defaultValue: -> return Meteor.user().emails?[0]?.address password: label: "邮箱密码" type: "password" required: true list_views: all: label: "所有" filter_scope: "space" columns: ["email", "modified"] permission_set: user: allowCreate: true allowDelete: true allowEdit: true allowRead: true modifyAllRecords: false viewAllRecords: false admin: allowCreate: true allowDelete: true allowEdit: true allowRead: true modifyAllRecords: false viewAllRecords: false # if Meteor.isClient # db.mail_accounts._simpleSchema.i18n("mail_accounts") # db.mail_accounts.attachSchema(db.mail_accounts._simpleSchema) if Meteor.isServer cryptIvForMail = "-mail-2016fzb2e8" db.mail_accounts.before.insert (userId, doc) -> doc.created_by = userId; doc.created = new Date(); doc.modified_by = userId; doc.modified = new Date(); if doc.password doc.password = Steedos.encrypt(doc.password, doc.email, cryptIvForMail); db.mail_accounts.before.update (userId, doc, fieldNames, modifier, options) -> email = doc.email; modifier.$set.modified_by = userId; modifier.$set.modified = new Date(); if modifier.$set.email email = modifier.$set.email if modifier.$set.password modifier.$set.password = Steedos.encrypt(modifier.$set.password, email, cryptIvForMail); db.mail_accounts.after.findOne (userId, selector, options, doc)-> if doc?.password doc.password = Steedos.decrypt(doc.password, doc.email, cryptIvForMail) # db.mail_accounts.after.find (userId, selector, options, cursor)-> # cursor.forEach (item) -> # item.password = mailDecrypt.decrypt(item.password, item.email) if Meteor.isServer db.mail_accounts._ensureIndex({ "owner": 1 },{background: true})
51696
db.mail_accounts = new Meteor.Collection('mail_accounts') db.mail_accounts.allow update: (userId, doc, fields, modifier) -> return doc.owner == userId; insert: (userId, doc, fields, modifier) -> return doc.owner == userId; # db.mail_accounts._simpleSchema = new SimpleSchema Creator.Objects.mail_accounts = name: "mail_accounts" label: "邮件账户" icon: "apps" fields: email: label: "邮箱账户" type: "text" is_name:true required: true defaultValue: -> return Meteor.user().emails?[0]?.address password: label: "邮箱密码" type: "password" required: true list_views: all: label: "所有" filter_scope: "space" columns: ["email", "modified"] permission_set: user: allowCreate: true allowDelete: true allowEdit: true allowRead: true modifyAllRecords: false viewAllRecords: false admin: allowCreate: true allowDelete: true allowEdit: true allowRead: true modifyAllRecords: false viewAllRecords: false # if Meteor.isClient # db.mail_accounts._simpleSchema.i18n("mail_accounts") # db.mail_accounts.attachSchema(db.mail_accounts._simpleSchema) if Meteor.isServer cryptIvForMail = "-mail-2016fzb2e8" db.mail_accounts.before.insert (userId, doc) -> doc.created_by = userId; doc.created = new Date(); doc.modified_by = userId; doc.modified = new Date(); if doc.password doc.password = <PASSWORD>(doc.password, doc.email, cryptIvForMail); db.mail_accounts.before.update (userId, doc, fieldNames, modifier, options) -> email = doc.email; modifier.$set.modified_by = userId; modifier.$set.modified = new Date(); if modifier.$set.email email = modifier.$set.email if modifier.$set.password modifier.$set.password = <PASSWORD>.encrypt(modifier.$set.password, email, cryptIvForMail); db.mail_accounts.after.findOne (userId, selector, options, doc)-> if doc?.password doc.password = <PASSWORD>(doc.password, doc.email, cryptIvForMail) # db.mail_accounts.after.find (userId, selector, options, cursor)-> # cursor.forEach (item) -> # item.password = <PASSWORD>(item.password, item.email) if Meteor.isServer db.mail_accounts._ensureIndex({ "owner": 1 },{background: true})
true
db.mail_accounts = new Meteor.Collection('mail_accounts') db.mail_accounts.allow update: (userId, doc, fields, modifier) -> return doc.owner == userId; insert: (userId, doc, fields, modifier) -> return doc.owner == userId; # db.mail_accounts._simpleSchema = new SimpleSchema Creator.Objects.mail_accounts = name: "mail_accounts" label: "邮件账户" icon: "apps" fields: email: label: "邮箱账户" type: "text" is_name:true required: true defaultValue: -> return Meteor.user().emails?[0]?.address password: label: "邮箱密码" type: "password" required: true list_views: all: label: "所有" filter_scope: "space" columns: ["email", "modified"] permission_set: user: allowCreate: true allowDelete: true allowEdit: true allowRead: true modifyAllRecords: false viewAllRecords: false admin: allowCreate: true allowDelete: true allowEdit: true allowRead: true modifyAllRecords: false viewAllRecords: false # if Meteor.isClient # db.mail_accounts._simpleSchema.i18n("mail_accounts") # db.mail_accounts.attachSchema(db.mail_accounts._simpleSchema) if Meteor.isServer cryptIvForMail = "-mail-2016fzb2e8" db.mail_accounts.before.insert (userId, doc) -> doc.created_by = userId; doc.created = new Date(); doc.modified_by = userId; doc.modified = new Date(); if doc.password doc.password = PI:PASSWORD:<PASSWORD>END_PI(doc.password, doc.email, cryptIvForMail); db.mail_accounts.before.update (userId, doc, fieldNames, modifier, options) -> email = doc.email; modifier.$set.modified_by = userId; modifier.$set.modified = new Date(); if modifier.$set.email email = modifier.$set.email if modifier.$set.password modifier.$set.password = PI:PASSWORD:<PASSWORD>END_PI.encrypt(modifier.$set.password, email, cryptIvForMail); db.mail_accounts.after.findOne (userId, selector, options, doc)-> if doc?.password doc.password = PI:PASSWORD:<PASSWORD>END_PI(doc.password, doc.email, cryptIvForMail) # db.mail_accounts.after.find (userId, selector, options, cursor)-> # cursor.forEach (item) -> # item.password = PI:PASSWORD:<PASSWORD>END_PI(item.password, item.email) if Meteor.isServer db.mail_accounts._ensureIndex({ "owner": 1 },{background: true})
[ { "context": "me is 'join'\n params['password'] = params['moderatorPW']\n @urls.push _elem(name, \"#{name} as mode", "end": 8196, "score": 0.995927095413208, "start": 8185, "tag": "PASSWORD", "value": "moderatorPW" }, { "context": ", params))\n params['password']...
src/js/api_mate.coffee
jfederico/api-mate
0
$ -> placeholders = results: '#api-mate-results' modal: '#post-response-modal' apiMate = new ApiMate(placeholders) apiMate.start() $('#api-mate-results').on 'api-mate-urls-added', -> Application.bindTooltips() # A class that does all the logic of the API Mate. It's integrated with the html markup # via data attributes and a few classes. Can be used with other applications than the # API Mate to provide similar functionality. # # Depends on: # * jQuery # * underscore/lodash # * mustache # * bigbluebutton-api-js # * bootstrap (for the modal, especially) # window.ApiMate = class ApiMate # `placeholders` should be an object with the properties: # * `results`: a string with the jQuery selector for the element that will contain # the URLs generated. # * `modal`: a string with the jQuery selector for an element that will be used as # a modal window (should follow bootstrap's model for modals). # # `templates` should be an object with the properties: # * `results`: a string with a mustache template to show the list of links generated. # * `postSuccess`: a string with a mustache template with the internal content of the # modal when showing a success message for a POST request. # * `postError`: a string with a mustache template with the internal content of the # modal when showing an error message for a POST request. # * `preUpload`: a string with a mustache template to format the body of a the POST # request to pre-upload files when creating a conference. constructor: (@placeholders, @templates) -> @updatedTimer = null @urls = [] # last set of urls generated @placeholders ?= {} @templates ?= {} @templates['results'] ?= resultsTemplate @templates['postSuccess'] ?= postSuccessTemplate @templates['postError'] ?= postErrorTemplate @templates['preUpload'] ?= preUploadUrl @debug = false @urlsLast = null start: -> # set random values in some inputs @initializeMenu() # when the meeting name is changed, change the id also $("[data-api-mate-param*='meetingID']").on "keyup", -> $("[data-api-mate-param*='name']").val $(this).val() # triggers to generate the links $("[data-api-mate-param]").on "change keyup", (e) => @generateUrls() @addUrlsToPage(@urls) $("[data-api-mate-server]").on "change keyup", (e) => @generateUrls() @addUrlsToPage(@urls) $("[data-api-mate-special-param]").on "change keyup", (e) => @generateUrls() @addUrlsToPage(@urls) # expand or collapse links $("[data-api-mate-expand]").on "click", => selected = !$("[data-api-mate-expand]").hasClass("active") @expandLinks(selected) true # button to clear the inputs $("[data-api-mate-clear]").on "click", (e) => @clearAllFields() @generateUrls() @addUrlsToPage(@urls) # set our debug flag $("[data-api-mate-debug]").on "click", => selected = !$("[data-api-mate-debug]").hasClass("active") @debug = selected true # generate the links already on setup @generateUrls() @addUrlsToPage(@urls) # binding elements @bindPostRequests() # search @bindSearch() initializeMenu: -> vbridge = "7" + pad(Math.floor(Math.random() * 10000 - 1).toString(), 4) $("[data-api-mate-param*='voiceBridge']").val(vbridge) name = "random-" + Math.floor(Math.random() * 10000000).toString() $("[data-api-mate-param*='name']").val(name) $("[data-api-mate-param*='meetingID']").val(name) $("[data-api-mate-param*='recordID']").val(name) user = "User " + Math.floor(Math.random() * 10000000).toString() $("[data-api-mate-param*='fullName']").val(user) # set values based on parameters in the URL # gives priority to params in the hash (e.g. 'api_mate.html#sharedSecret=123') query = getHashParams() # but also accept params in the search string for backwards compatibility (e.g. 'api_mate.html?sharedSecret=123') query2 = parseQueryString(window.location.search.substring(1)) query = _.extend(query2, query) if query.server? $("[data-api-mate-server='url']").val(query.server) delete query.server # accept both 'salt' and 'sharedSecret', giving priority to 'sharedSecret' if query.salt? $("[data-api-mate-server='salt']").val(query.salt) delete query.salt if query.sharedSecret? $("[data-api-mate-server='salt']").val(query.sharedSecret) delete query.sharedSecret for prop, value of query $("[data-api-mate-param*='#{prop}']").val(value) $("[data-api-mate-special-param*='#{prop}']").val(value) # Add a div with all links and a close button to the global # results container addUrlsToPage: (urls) -> # don't do it again unless something changed isEqual = urls? and @urlsLast? and (JSON.stringify(urls) == JSON.stringify(@urlsLast)) return if isEqual @urlsLast = _.map(urls, _.clone) placeholder = $(@placeholders['results']) for item in urls desc = item.description if desc.match(/recordings/i) item.urlClass = "api-mate-url-recordings" else if desc.match(/mobile/i) item.urlClass = "api-mate-url-from-mobile" else if desc.match(/custom call/i) item.urlClass = "api-mate-url-custom-call" else item.urlClass = "api-mate-url-standard" opts = title: new Date().toTimeString() urls: urls html = Mustache.to_html(@templates['results'], opts) $('.results-tooltip').remove() $(placeholder).html(html) @expandLinks($("[data-api-mate-expand]").hasClass("active")) # mark the items as updated $('.api-mate-results', @placeholders['results']).addClass("updated") clearTimeout(@updatedTimer) @updatedTimer = setTimeout( => $('.api-mate-results', @placeholders['results']).removeClass("updated") , 300) $(@placeholders['results']).trigger('api-mate-urls-added') # Returns a BigBlueButtonApi configured with the server set by the user in the inputs. getApi: -> server = {} server.url = $("[data-api-mate-server='url']").val() server.salt = $("[data-api-mate-server='salt']").val() # Do some cleanups on the server URL to that pasted URLs in various formats work better # Remove trailing /, and add /api on the end if missing. server.url = server.url.replace(/(\/api)?\/?$/, '/api') server.name = server.url new BigBlueButtonApi(server.url, server.salt, @debug) # Generate urls for all API calls and store them internally in `@urls`. generateUrls: () -> params = {} $('[data-api-mate-param]').each -> $elem = $(this) attrs = $elem.attr('data-api-mate-param').split(',') value = inputValue($elem) if attrs? and value? for attr in attrs params[attr] = value true # don't ever stop lines = inputValue("textarea[data-api-mate-special-param='meta']") if lines? lines = lines.replace(/\r\n/g, "\n").split("\n") for line in lines separator = line.indexOf("=") if separator >= 0 paramName = line.substring(0, separator) paramValue = line.substring(separator+1, line.length) params["meta_" + paramName] = paramValue lines = inputValue("textarea[data-api-mate-special-param='custom-params']") if lines? lines = lines.replace(/\r\n/g, "\n").split("\n") for line in lines separator = line.indexOf("=") if separator >= 0 paramName = line.substring(0, separator) paramValue = line.substring(separator+1, line.length) params["custom_" + paramName] = paramValue lines = inputValue("textarea[data-api-mate-special-param='custom-calls']") if lines? lines = lines.replace(/\r\n/g, "\n").split("\n") customCalls = lines else customCalls = null # generate the list of links api = @getApi() @urls = [] # standard API calls _elem = (name, desc, url) -> { name: name, description: desc, url: url } for name in api.availableApiCalls() if name is 'join' params['password'] = params['moderatorPW'] @urls.push _elem(name, "#{name} as moderator", api.urlFor(name, params)) params['password'] = params['attendeePW'] @urls.push _elem(name, "#{name} as attendee", api.urlFor(name, params)) # so all other calls will use the moderator password params['password'] = params['moderatorPW'] else @urls.push _elem(name, name, api.urlFor(name, params)) # custom API calls set by the user if customCalls? for name in customCalls @urls.push _elem(name, "custom call: #{name}", api.urlFor(name, params, false)) # for mobile params['password'] = params['moderatorPW'] @urls.push _elem("join", "mobile call: join as moderator", api.setMobileProtocol(api.urlFor("join", params))) params['password'] = params['attendeePW'] @urls.push _elem("join", "mobile call: join as attendee", api.setMobileProtocol(api.urlFor("join", params))) # Empty all inputs in the configuration menu clearAllFields: -> $("[data-api-mate-param]").each -> $(this).val("") $(this).attr("checked", null) # Expand (if `selected` is true) or collapse the links. expandLinks: (selected) -> if selected $(".api-mate-link", @placeholders['results']).addClass('expanded') else $(".api-mate-link", @placeholders['results']).removeClass('expanded') # Logic for when a button to send a request via POST is clicked. bindPostRequests: -> _apiMate = this $(document).on 'click', 'a[data-api-mate-post]', (e) -> $target = $(this) href = $target.attr('data-url') # get the data to be posted for this method and the content type method = $target.attr('data-api-mate-post') data = _apiMate.getPostData(method) contentType = _apiMate.getPostContentType(method) $('[data-api-mate-post]').addClass('disabled') $.ajax url: href type: "POST" crossDomain: true contentType: contentType dataType: "xml" data: data complete: (jqxhr, status) -> # TODO: show the result properly formatted and highlighted in the modal modal = _apiMate.placeholders['modal'] postSuccess = _apiMate.templates['postSuccess'] postError = _apiMate.templates['postError'] if jqxhr.status is 200 $('.modal-header', modal).removeClass('alert-danger') $('.modal-header', modal).addClass('alert-success') html = Mustache.to_html(postSuccess, { response: jqxhr.responseText }) $('.modal-body', modal).html(html) else $('.modal-header h4', modal).text('Ooops!') $('.modal-header', modal).addClass('alert-danger') $('.modal-header', modal).removeClass('alert-success') opts = status: jqxhr.status statusText: jqxhr.statusText opts['response'] = jqxhr.responseText unless _.isEmpty(jqxhr.responseText) html = Mustache.to_html(postError, opts) $('.modal-body', modal).html(html) $(modal).modal({ show: true }) $('[data-api-mate-post]').removeClass('disabled') e.preventDefault() false getPostData: (method) -> if method is 'create' urls = inputValue("textarea[data-api-mate-param='pre-upload']") if urls? urls = urls.replace(/\r\n/g, "\n").split("\n") urls = _.map(urls, (u) -> { url: u }) opts = { urls: urls } Mustache.to_html(@templates['preUpload'], opts) else if method is 'setConfigXML' if isFilled("textarea[data-api-mate-param='configXML']") api = @getApi() query = "configXML=#{api.encodeForUrl($("#input-config-xml").val())}" query += "&meetingID=#{api.encodeForUrl($("#input-mid").val())}" checksum = api.checksum('setConfigXML', query) query += "&checksum=" + checksum query getPostContentType: (method) -> if method is 'create' 'application/xml; charset=utf-8' else if method is 'setConfigXML' 'application/x-www-form-urlencoded' bindSearch: -> _apiMate = this $(document).on 'keyup', '[data-api-mate-search-input]', (e) -> $target = $(this) searchTerm = inputValue($target) search = -> $elem = $(this) if searchTerm? and not _.isEmpty(searchTerm.trim()) visible = false searchRe = makeSearchRegexp(searchTerm) attrs = $elem.attr('data-api-mate-param')?.split(',') or [] attrs = attrs.concat($elem.attr('data-api-mate-search')?.split(',') or []) for attr in attrs visible = true if attr.match(searchRe) else visible = true if visible $elem.parents('.form-group').show() else $elem.parents('.form-group').hide() true # don't ever stop $('[data-api-mate-param]').each(search) $('[data-api-mate-special-param]').each(search) # Returns the value set in an input, if any. For checkboxes, returns the value # as a boolean. For any other input, return as a string. # `selector` can be a string with a selector or a jQuery object. inputValue = (selector) -> if _.isString(selector) $elem = $(selector) else $elem = selector type = $elem.attr('type') or $elem.prop('tagName')?.toLowerCase() switch type when 'checkbox' $elem.is(":checked") else value = $elem.val() if value? and not _.isEmpty(value.trim()) value else null # Check if an input text field has a valid value (not empty). isFilled = (field) -> value = $(field).val() value? and not _.isEmpty(value.trim()) # Pads a number `num` with zeros up to `size` characters. Returns a string with it. # Example: # pad(123, 5) # > '00123' pad = (num, size) -> s = '' s += '0' for [0..size-1] s += num s.substr(s.length-size) # Parse the query string into an object # From http://www.joezimjs.com/javascript/3-ways-to-parse-a-query-string-in-a-url/ parseQueryString = (queryString) -> params = {} # Split into key/value pairs if queryString? and not _.isEmpty(queryString) queries = queryString.split("&") else queries = [] # Convert the array of strings into an object i = 0 l = queries.length while i < l temp = queries[i].split('=') params[temp[0]] = temp[1] i++ params makeSearchRegexp = (term) -> terms = term.split(" ") terms = _.filter(terms, (t) -> not _.isEmpty(t.trim())) terms = _.map(terms, (t) -> ".*#{t}.*") terms = terms.join('|') new RegExp(terms, "i"); # Get the parameters from the hash in the URL # Adapted from: http://stackoverflow.com/questions/4197591/parsing-url-hash-fragment-identifier-with-javascript#answer-4198132 getHashParams = -> hashParams = {} a = /\+/g # Regex for replacing addition symbol with a space r = /([^&;=]+)=?([^&;]*)/g d = (s) -> decodeURIComponent(s.replace(a, " ")) q = window.location.hash.substring(1) hashParams[d(e[1])] = d(e[2]) while e = r.exec(q) hashParams
5078
$ -> placeholders = results: '#api-mate-results' modal: '#post-response-modal' apiMate = new ApiMate(placeholders) apiMate.start() $('#api-mate-results').on 'api-mate-urls-added', -> Application.bindTooltips() # A class that does all the logic of the API Mate. It's integrated with the html markup # via data attributes and a few classes. Can be used with other applications than the # API Mate to provide similar functionality. # # Depends on: # * jQuery # * underscore/lodash # * mustache # * bigbluebutton-api-js # * bootstrap (for the modal, especially) # window.ApiMate = class ApiMate # `placeholders` should be an object with the properties: # * `results`: a string with the jQuery selector for the element that will contain # the URLs generated. # * `modal`: a string with the jQuery selector for an element that will be used as # a modal window (should follow bootstrap's model for modals). # # `templates` should be an object with the properties: # * `results`: a string with a mustache template to show the list of links generated. # * `postSuccess`: a string with a mustache template with the internal content of the # modal when showing a success message for a POST request. # * `postError`: a string with a mustache template with the internal content of the # modal when showing an error message for a POST request. # * `preUpload`: a string with a mustache template to format the body of a the POST # request to pre-upload files when creating a conference. constructor: (@placeholders, @templates) -> @updatedTimer = null @urls = [] # last set of urls generated @placeholders ?= {} @templates ?= {} @templates['results'] ?= resultsTemplate @templates['postSuccess'] ?= postSuccessTemplate @templates['postError'] ?= postErrorTemplate @templates['preUpload'] ?= preUploadUrl @debug = false @urlsLast = null start: -> # set random values in some inputs @initializeMenu() # when the meeting name is changed, change the id also $("[data-api-mate-param*='meetingID']").on "keyup", -> $("[data-api-mate-param*='name']").val $(this).val() # triggers to generate the links $("[data-api-mate-param]").on "change keyup", (e) => @generateUrls() @addUrlsToPage(@urls) $("[data-api-mate-server]").on "change keyup", (e) => @generateUrls() @addUrlsToPage(@urls) $("[data-api-mate-special-param]").on "change keyup", (e) => @generateUrls() @addUrlsToPage(@urls) # expand or collapse links $("[data-api-mate-expand]").on "click", => selected = !$("[data-api-mate-expand]").hasClass("active") @expandLinks(selected) true # button to clear the inputs $("[data-api-mate-clear]").on "click", (e) => @clearAllFields() @generateUrls() @addUrlsToPage(@urls) # set our debug flag $("[data-api-mate-debug]").on "click", => selected = !$("[data-api-mate-debug]").hasClass("active") @debug = selected true # generate the links already on setup @generateUrls() @addUrlsToPage(@urls) # binding elements @bindPostRequests() # search @bindSearch() initializeMenu: -> vbridge = "7" + pad(Math.floor(Math.random() * 10000 - 1).toString(), 4) $("[data-api-mate-param*='voiceBridge']").val(vbridge) name = "random-" + Math.floor(Math.random() * 10000000).toString() $("[data-api-mate-param*='name']").val(name) $("[data-api-mate-param*='meetingID']").val(name) $("[data-api-mate-param*='recordID']").val(name) user = "User " + Math.floor(Math.random() * 10000000).toString() $("[data-api-mate-param*='fullName']").val(user) # set values based on parameters in the URL # gives priority to params in the hash (e.g. 'api_mate.html#sharedSecret=123') query = getHashParams() # but also accept params in the search string for backwards compatibility (e.g. 'api_mate.html?sharedSecret=123') query2 = parseQueryString(window.location.search.substring(1)) query = _.extend(query2, query) if query.server? $("[data-api-mate-server='url']").val(query.server) delete query.server # accept both 'salt' and 'sharedSecret', giving priority to 'sharedSecret' if query.salt? $("[data-api-mate-server='salt']").val(query.salt) delete query.salt if query.sharedSecret? $("[data-api-mate-server='salt']").val(query.sharedSecret) delete query.sharedSecret for prop, value of query $("[data-api-mate-param*='#{prop}']").val(value) $("[data-api-mate-special-param*='#{prop}']").val(value) # Add a div with all links and a close button to the global # results container addUrlsToPage: (urls) -> # don't do it again unless something changed isEqual = urls? and @urlsLast? and (JSON.stringify(urls) == JSON.stringify(@urlsLast)) return if isEqual @urlsLast = _.map(urls, _.clone) placeholder = $(@placeholders['results']) for item in urls desc = item.description if desc.match(/recordings/i) item.urlClass = "api-mate-url-recordings" else if desc.match(/mobile/i) item.urlClass = "api-mate-url-from-mobile" else if desc.match(/custom call/i) item.urlClass = "api-mate-url-custom-call" else item.urlClass = "api-mate-url-standard" opts = title: new Date().toTimeString() urls: urls html = Mustache.to_html(@templates['results'], opts) $('.results-tooltip').remove() $(placeholder).html(html) @expandLinks($("[data-api-mate-expand]").hasClass("active")) # mark the items as updated $('.api-mate-results', @placeholders['results']).addClass("updated") clearTimeout(@updatedTimer) @updatedTimer = setTimeout( => $('.api-mate-results', @placeholders['results']).removeClass("updated") , 300) $(@placeholders['results']).trigger('api-mate-urls-added') # Returns a BigBlueButtonApi configured with the server set by the user in the inputs. getApi: -> server = {} server.url = $("[data-api-mate-server='url']").val() server.salt = $("[data-api-mate-server='salt']").val() # Do some cleanups on the server URL to that pasted URLs in various formats work better # Remove trailing /, and add /api on the end if missing. server.url = server.url.replace(/(\/api)?\/?$/, '/api') server.name = server.url new BigBlueButtonApi(server.url, server.salt, @debug) # Generate urls for all API calls and store them internally in `@urls`. generateUrls: () -> params = {} $('[data-api-mate-param]').each -> $elem = $(this) attrs = $elem.attr('data-api-mate-param').split(',') value = inputValue($elem) if attrs? and value? for attr in attrs params[attr] = value true # don't ever stop lines = inputValue("textarea[data-api-mate-special-param='meta']") if lines? lines = lines.replace(/\r\n/g, "\n").split("\n") for line in lines separator = line.indexOf("=") if separator >= 0 paramName = line.substring(0, separator) paramValue = line.substring(separator+1, line.length) params["meta_" + paramName] = paramValue lines = inputValue("textarea[data-api-mate-special-param='custom-params']") if lines? lines = lines.replace(/\r\n/g, "\n").split("\n") for line in lines separator = line.indexOf("=") if separator >= 0 paramName = line.substring(0, separator) paramValue = line.substring(separator+1, line.length) params["custom_" + paramName] = paramValue lines = inputValue("textarea[data-api-mate-special-param='custom-calls']") if lines? lines = lines.replace(/\r\n/g, "\n").split("\n") customCalls = lines else customCalls = null # generate the list of links api = @getApi() @urls = [] # standard API calls _elem = (name, desc, url) -> { name: name, description: desc, url: url } for name in api.availableApiCalls() if name is 'join' params['password'] = params['<PASSWORD>'] @urls.push _elem(name, "#{name} as moderator", api.urlFor(name, params)) params['password'] = params['at<PASSWORD>'] @urls.push _elem(name, "#{name} as attendee", api.urlFor(name, params)) # so all other calls will use the moderator password params['password'] = params['<PASSWORD>'] else @urls.push _elem(name, name, api.urlFor(name, params)) # custom API calls set by the user if customCalls? for name in customCalls @urls.push _elem(name, "custom call: #{name}", api.urlFor(name, params, false)) # for mobile params['password'] = params['<PASSWORD>'] @urls.push _elem("join", "mobile call: join as moderator", api.setMobileProtocol(api.urlFor("join", params))) params['password'] = params['attendee<PASSWORD>'] @urls.push _elem("join", "mobile call: join as attendee", api.setMobileProtocol(api.urlFor("join", params))) # Empty all inputs in the configuration menu clearAllFields: -> $("[data-api-mate-param]").each -> $(this).val("") $(this).attr("checked", null) # Expand (if `selected` is true) or collapse the links. expandLinks: (selected) -> if selected $(".api-mate-link", @placeholders['results']).addClass('expanded') else $(".api-mate-link", @placeholders['results']).removeClass('expanded') # Logic for when a button to send a request via POST is clicked. bindPostRequests: -> _apiMate = this $(document).on 'click', 'a[data-api-mate-post]', (e) -> $target = $(this) href = $target.attr('data-url') # get the data to be posted for this method and the content type method = $target.attr('data-api-mate-post') data = _apiMate.getPostData(method) contentType = _apiMate.getPostContentType(method) $('[data-api-mate-post]').addClass('disabled') $.ajax url: href type: "POST" crossDomain: true contentType: contentType dataType: "xml" data: data complete: (jqxhr, status) -> # TODO: show the result properly formatted and highlighted in the modal modal = _apiMate.placeholders['modal'] postSuccess = _apiMate.templates['postSuccess'] postError = _apiMate.templates['postError'] if jqxhr.status is 200 $('.modal-header', modal).removeClass('alert-danger') $('.modal-header', modal).addClass('alert-success') html = Mustache.to_html(postSuccess, { response: jqxhr.responseText }) $('.modal-body', modal).html(html) else $('.modal-header h4', modal).text('Ooops!') $('.modal-header', modal).addClass('alert-danger') $('.modal-header', modal).removeClass('alert-success') opts = status: jqxhr.status statusText: jqxhr.statusText opts['response'] = jqxhr.responseText unless _.isEmpty(jqxhr.responseText) html = Mustache.to_html(postError, opts) $('.modal-body', modal).html(html) $(modal).modal({ show: true }) $('[data-api-mate-post]').removeClass('disabled') e.preventDefault() false getPostData: (method) -> if method is 'create' urls = inputValue("textarea[data-api-mate-param='pre-upload']") if urls? urls = urls.replace(/\r\n/g, "\n").split("\n") urls = _.map(urls, (u) -> { url: u }) opts = { urls: urls } Mustache.to_html(@templates['preUpload'], opts) else if method is 'setConfigXML' if isFilled("textarea[data-api-mate-param='configXML']") api = @getApi() query = "configXML=#{api.encodeForUrl($("#input-config-xml").val())}" query += "&meetingID=#{api.encodeForUrl($("#input-mid").val())}" checksum = api.checksum('setConfigXML', query) query += "&checksum=" + checksum query getPostContentType: (method) -> if method is 'create' 'application/xml; charset=utf-8' else if method is 'setConfigXML' 'application/x-www-form-urlencoded' bindSearch: -> _apiMate = this $(document).on 'keyup', '[data-api-mate-search-input]', (e) -> $target = $(this) searchTerm = inputValue($target) search = -> $elem = $(this) if searchTerm? and not _.isEmpty(searchTerm.trim()) visible = false searchRe = makeSearchRegexp(searchTerm) attrs = $elem.attr('data-api-mate-param')?.split(',') or [] attrs = attrs.concat($elem.attr('data-api-mate-search')?.split(',') or []) for attr in attrs visible = true if attr.match(searchRe) else visible = true if visible $elem.parents('.form-group').show() else $elem.parents('.form-group').hide() true # don't ever stop $('[data-api-mate-param]').each(search) $('[data-api-mate-special-param]').each(search) # Returns the value set in an input, if any. For checkboxes, returns the value # as a boolean. For any other input, return as a string. # `selector` can be a string with a selector or a jQuery object. inputValue = (selector) -> if _.isString(selector) $elem = $(selector) else $elem = selector type = $elem.attr('type') or $elem.prop('tagName')?.toLowerCase() switch type when 'checkbox' $elem.is(":checked") else value = $elem.val() if value? and not _.isEmpty(value.trim()) value else null # Check if an input text field has a valid value (not empty). isFilled = (field) -> value = $(field).val() value? and not _.isEmpty(value.trim()) # Pads a number `num` with zeros up to `size` characters. Returns a string with it. # Example: # pad(123, 5) # > '00123' pad = (num, size) -> s = '' s += '0' for [0..size-1] s += num s.substr(s.length-size) # Parse the query string into an object # From http://www.joezimjs.com/javascript/3-ways-to-parse-a-query-string-in-a-url/ parseQueryString = (queryString) -> params = {} # Split into key/value pairs if queryString? and not _.isEmpty(queryString) queries = queryString.split("&") else queries = [] # Convert the array of strings into an object i = 0 l = queries.length while i < l temp = queries[i].split('=') params[temp[0]] = temp[1] i++ params makeSearchRegexp = (term) -> terms = term.split(" ") terms = _.filter(terms, (t) -> not _.isEmpty(t.trim())) terms = _.map(terms, (t) -> ".*#{t}.*") terms = terms.join('|') new RegExp(terms, "i"); # Get the parameters from the hash in the URL # Adapted from: http://stackoverflow.com/questions/4197591/parsing-url-hash-fragment-identifier-with-javascript#answer-4198132 getHashParams = -> hashParams = {} a = /\+/g # Regex for replacing addition symbol with a space r = /([^&;=]+)=?([^&;]*)/g d = (s) -> decodeURIComponent(s.replace(a, " ")) q = window.location.hash.substring(1) hashParams[d(e[1])] = d(e[2]) while e = r.exec(q) hashParams
true
$ -> placeholders = results: '#api-mate-results' modal: '#post-response-modal' apiMate = new ApiMate(placeholders) apiMate.start() $('#api-mate-results').on 'api-mate-urls-added', -> Application.bindTooltips() # A class that does all the logic of the API Mate. It's integrated with the html markup # via data attributes and a few classes. Can be used with other applications than the # API Mate to provide similar functionality. # # Depends on: # * jQuery # * underscore/lodash # * mustache # * bigbluebutton-api-js # * bootstrap (for the modal, especially) # window.ApiMate = class ApiMate # `placeholders` should be an object with the properties: # * `results`: a string with the jQuery selector for the element that will contain # the URLs generated. # * `modal`: a string with the jQuery selector for an element that will be used as # a modal window (should follow bootstrap's model for modals). # # `templates` should be an object with the properties: # * `results`: a string with a mustache template to show the list of links generated. # * `postSuccess`: a string with a mustache template with the internal content of the # modal when showing a success message for a POST request. # * `postError`: a string with a mustache template with the internal content of the # modal when showing an error message for a POST request. # * `preUpload`: a string with a mustache template to format the body of a the POST # request to pre-upload files when creating a conference. constructor: (@placeholders, @templates) -> @updatedTimer = null @urls = [] # last set of urls generated @placeholders ?= {} @templates ?= {} @templates['results'] ?= resultsTemplate @templates['postSuccess'] ?= postSuccessTemplate @templates['postError'] ?= postErrorTemplate @templates['preUpload'] ?= preUploadUrl @debug = false @urlsLast = null start: -> # set random values in some inputs @initializeMenu() # when the meeting name is changed, change the id also $("[data-api-mate-param*='meetingID']").on "keyup", -> $("[data-api-mate-param*='name']").val $(this).val() # triggers to generate the links $("[data-api-mate-param]").on "change keyup", (e) => @generateUrls() @addUrlsToPage(@urls) $("[data-api-mate-server]").on "change keyup", (e) => @generateUrls() @addUrlsToPage(@urls) $("[data-api-mate-special-param]").on "change keyup", (e) => @generateUrls() @addUrlsToPage(@urls) # expand or collapse links $("[data-api-mate-expand]").on "click", => selected = !$("[data-api-mate-expand]").hasClass("active") @expandLinks(selected) true # button to clear the inputs $("[data-api-mate-clear]").on "click", (e) => @clearAllFields() @generateUrls() @addUrlsToPage(@urls) # set our debug flag $("[data-api-mate-debug]").on "click", => selected = !$("[data-api-mate-debug]").hasClass("active") @debug = selected true # generate the links already on setup @generateUrls() @addUrlsToPage(@urls) # binding elements @bindPostRequests() # search @bindSearch() initializeMenu: -> vbridge = "7" + pad(Math.floor(Math.random() * 10000 - 1).toString(), 4) $("[data-api-mate-param*='voiceBridge']").val(vbridge) name = "random-" + Math.floor(Math.random() * 10000000).toString() $("[data-api-mate-param*='name']").val(name) $("[data-api-mate-param*='meetingID']").val(name) $("[data-api-mate-param*='recordID']").val(name) user = "User " + Math.floor(Math.random() * 10000000).toString() $("[data-api-mate-param*='fullName']").val(user) # set values based on parameters in the URL # gives priority to params in the hash (e.g. 'api_mate.html#sharedSecret=123') query = getHashParams() # but also accept params in the search string for backwards compatibility (e.g. 'api_mate.html?sharedSecret=123') query2 = parseQueryString(window.location.search.substring(1)) query = _.extend(query2, query) if query.server? $("[data-api-mate-server='url']").val(query.server) delete query.server # accept both 'salt' and 'sharedSecret', giving priority to 'sharedSecret' if query.salt? $("[data-api-mate-server='salt']").val(query.salt) delete query.salt if query.sharedSecret? $("[data-api-mate-server='salt']").val(query.sharedSecret) delete query.sharedSecret for prop, value of query $("[data-api-mate-param*='#{prop}']").val(value) $("[data-api-mate-special-param*='#{prop}']").val(value) # Add a div with all links and a close button to the global # results container addUrlsToPage: (urls) -> # don't do it again unless something changed isEqual = urls? and @urlsLast? and (JSON.stringify(urls) == JSON.stringify(@urlsLast)) return if isEqual @urlsLast = _.map(urls, _.clone) placeholder = $(@placeholders['results']) for item in urls desc = item.description if desc.match(/recordings/i) item.urlClass = "api-mate-url-recordings" else if desc.match(/mobile/i) item.urlClass = "api-mate-url-from-mobile" else if desc.match(/custom call/i) item.urlClass = "api-mate-url-custom-call" else item.urlClass = "api-mate-url-standard" opts = title: new Date().toTimeString() urls: urls html = Mustache.to_html(@templates['results'], opts) $('.results-tooltip').remove() $(placeholder).html(html) @expandLinks($("[data-api-mate-expand]").hasClass("active")) # mark the items as updated $('.api-mate-results', @placeholders['results']).addClass("updated") clearTimeout(@updatedTimer) @updatedTimer = setTimeout( => $('.api-mate-results', @placeholders['results']).removeClass("updated") , 300) $(@placeholders['results']).trigger('api-mate-urls-added') # Returns a BigBlueButtonApi configured with the server set by the user in the inputs. getApi: -> server = {} server.url = $("[data-api-mate-server='url']").val() server.salt = $("[data-api-mate-server='salt']").val() # Do some cleanups on the server URL to that pasted URLs in various formats work better # Remove trailing /, and add /api on the end if missing. server.url = server.url.replace(/(\/api)?\/?$/, '/api') server.name = server.url new BigBlueButtonApi(server.url, server.salt, @debug) # Generate urls for all API calls and store them internally in `@urls`. generateUrls: () -> params = {} $('[data-api-mate-param]').each -> $elem = $(this) attrs = $elem.attr('data-api-mate-param').split(',') value = inputValue($elem) if attrs? and value? for attr in attrs params[attr] = value true # don't ever stop lines = inputValue("textarea[data-api-mate-special-param='meta']") if lines? lines = lines.replace(/\r\n/g, "\n").split("\n") for line in lines separator = line.indexOf("=") if separator >= 0 paramName = line.substring(0, separator) paramValue = line.substring(separator+1, line.length) params["meta_" + paramName] = paramValue lines = inputValue("textarea[data-api-mate-special-param='custom-params']") if lines? lines = lines.replace(/\r\n/g, "\n").split("\n") for line in lines separator = line.indexOf("=") if separator >= 0 paramName = line.substring(0, separator) paramValue = line.substring(separator+1, line.length) params["custom_" + paramName] = paramValue lines = inputValue("textarea[data-api-mate-special-param='custom-calls']") if lines? lines = lines.replace(/\r\n/g, "\n").split("\n") customCalls = lines else customCalls = null # generate the list of links api = @getApi() @urls = [] # standard API calls _elem = (name, desc, url) -> { name: name, description: desc, url: url } for name in api.availableApiCalls() if name is 'join' params['password'] = params['PI:PASSWORD:<PASSWORD>END_PI'] @urls.push _elem(name, "#{name} as moderator", api.urlFor(name, params)) params['password'] = params['atPI:PASSWORD:<PASSWORD>END_PI'] @urls.push _elem(name, "#{name} as attendee", api.urlFor(name, params)) # so all other calls will use the moderator password params['password'] = params['PI:PASSWORD:<PASSWORD>END_PI'] else @urls.push _elem(name, name, api.urlFor(name, params)) # custom API calls set by the user if customCalls? for name in customCalls @urls.push _elem(name, "custom call: #{name}", api.urlFor(name, params, false)) # for mobile params['password'] = params['PI:PASSWORD:<PASSWORD>END_PI'] @urls.push _elem("join", "mobile call: join as moderator", api.setMobileProtocol(api.urlFor("join", params))) params['password'] = params['attendeePI:PASSWORD:<PASSWORD>END_PI'] @urls.push _elem("join", "mobile call: join as attendee", api.setMobileProtocol(api.urlFor("join", params))) # Empty all inputs in the configuration menu clearAllFields: -> $("[data-api-mate-param]").each -> $(this).val("") $(this).attr("checked", null) # Expand (if `selected` is true) or collapse the links. expandLinks: (selected) -> if selected $(".api-mate-link", @placeholders['results']).addClass('expanded') else $(".api-mate-link", @placeholders['results']).removeClass('expanded') # Logic for when a button to send a request via POST is clicked. bindPostRequests: -> _apiMate = this $(document).on 'click', 'a[data-api-mate-post]', (e) -> $target = $(this) href = $target.attr('data-url') # get the data to be posted for this method and the content type method = $target.attr('data-api-mate-post') data = _apiMate.getPostData(method) contentType = _apiMate.getPostContentType(method) $('[data-api-mate-post]').addClass('disabled') $.ajax url: href type: "POST" crossDomain: true contentType: contentType dataType: "xml" data: data complete: (jqxhr, status) -> # TODO: show the result properly formatted and highlighted in the modal modal = _apiMate.placeholders['modal'] postSuccess = _apiMate.templates['postSuccess'] postError = _apiMate.templates['postError'] if jqxhr.status is 200 $('.modal-header', modal).removeClass('alert-danger') $('.modal-header', modal).addClass('alert-success') html = Mustache.to_html(postSuccess, { response: jqxhr.responseText }) $('.modal-body', modal).html(html) else $('.modal-header h4', modal).text('Ooops!') $('.modal-header', modal).addClass('alert-danger') $('.modal-header', modal).removeClass('alert-success') opts = status: jqxhr.status statusText: jqxhr.statusText opts['response'] = jqxhr.responseText unless _.isEmpty(jqxhr.responseText) html = Mustache.to_html(postError, opts) $('.modal-body', modal).html(html) $(modal).modal({ show: true }) $('[data-api-mate-post]').removeClass('disabled') e.preventDefault() false getPostData: (method) -> if method is 'create' urls = inputValue("textarea[data-api-mate-param='pre-upload']") if urls? urls = urls.replace(/\r\n/g, "\n").split("\n") urls = _.map(urls, (u) -> { url: u }) opts = { urls: urls } Mustache.to_html(@templates['preUpload'], opts) else if method is 'setConfigXML' if isFilled("textarea[data-api-mate-param='configXML']") api = @getApi() query = "configXML=#{api.encodeForUrl($("#input-config-xml").val())}" query += "&meetingID=#{api.encodeForUrl($("#input-mid").val())}" checksum = api.checksum('setConfigXML', query) query += "&checksum=" + checksum query getPostContentType: (method) -> if method is 'create' 'application/xml; charset=utf-8' else if method is 'setConfigXML' 'application/x-www-form-urlencoded' bindSearch: -> _apiMate = this $(document).on 'keyup', '[data-api-mate-search-input]', (e) -> $target = $(this) searchTerm = inputValue($target) search = -> $elem = $(this) if searchTerm? and not _.isEmpty(searchTerm.trim()) visible = false searchRe = makeSearchRegexp(searchTerm) attrs = $elem.attr('data-api-mate-param')?.split(',') or [] attrs = attrs.concat($elem.attr('data-api-mate-search')?.split(',') or []) for attr in attrs visible = true if attr.match(searchRe) else visible = true if visible $elem.parents('.form-group').show() else $elem.parents('.form-group').hide() true # don't ever stop $('[data-api-mate-param]').each(search) $('[data-api-mate-special-param]').each(search) # Returns the value set in an input, if any. For checkboxes, returns the value # as a boolean. For any other input, return as a string. # `selector` can be a string with a selector or a jQuery object. inputValue = (selector) -> if _.isString(selector) $elem = $(selector) else $elem = selector type = $elem.attr('type') or $elem.prop('tagName')?.toLowerCase() switch type when 'checkbox' $elem.is(":checked") else value = $elem.val() if value? and not _.isEmpty(value.trim()) value else null # Check if an input text field has a valid value (not empty). isFilled = (field) -> value = $(field).val() value? and not _.isEmpty(value.trim()) # Pads a number `num` with zeros up to `size` characters. Returns a string with it. # Example: # pad(123, 5) # > '00123' pad = (num, size) -> s = '' s += '0' for [0..size-1] s += num s.substr(s.length-size) # Parse the query string into an object # From http://www.joezimjs.com/javascript/3-ways-to-parse-a-query-string-in-a-url/ parseQueryString = (queryString) -> params = {} # Split into key/value pairs if queryString? and not _.isEmpty(queryString) queries = queryString.split("&") else queries = [] # Convert the array of strings into an object i = 0 l = queries.length while i < l temp = queries[i].split('=') params[temp[0]] = temp[1] i++ params makeSearchRegexp = (term) -> terms = term.split(" ") terms = _.filter(terms, (t) -> not _.isEmpty(t.trim())) terms = _.map(terms, (t) -> ".*#{t}.*") terms = terms.join('|') new RegExp(terms, "i"); # Get the parameters from the hash in the URL # Adapted from: http://stackoverflow.com/questions/4197591/parsing-url-hash-fragment-identifier-with-javascript#answer-4198132 getHashParams = -> hashParams = {} a = /\+/g # Regex for replacing addition symbol with a space r = /([^&;=]+)=?([^&;]*)/g d = (s) -> decodeURIComponent(s.replace(a, " ")) q = window.location.hash.substring(1) hashParams[d(e[1])] = d(e[2]) while e = r.exec(q) hashParams
[ { "context": " a_key_1: '1'\n a_key_overwritten: a_key: 'overwrite 2'\n a_key_2: '2'\n \n it '$ keys in first le", "end": 1696, "score": 0.9938105940818787, "start": 1685, "tag": "KEY", "value": "overwrite 2" }, { "context": "overwritten: a_key: 'overwrite 2'\n ...
packages/core/test/session/contextualize.coffee
shivaylamba/meilisearch-gatsby-plugin-guide
31
{tags} = require '../test' contextualize = require '../../src/session/contextualize' normalize = require '../../src/session/normalize' describe 'session.contextualize', -> return unless tags.api it 'handle function as handler', -> expect = config: a: '' handler: (->) metadata: {}, hooks: {}, state: {} # String is place before objects contextualize [ (->) {a: ''} ] .should.eql expect # String is place after objects contextualize [ {a: ''} (->) ] .should.eql expect it 'handle string as metadata.argument', -> expect = config: b: '' metadata: argument: 'a' hooks: {}, state: {} # String is place before objects contextualize [ 'a' {b: ''} ] .should.eql expect # String is place after objects contextualize [ {b: ''} 'a' ] .should.eql expect it '$ merge config in first level', -> a_config_1 = { a_key_1: '1', a_key_overwritten: { a_key: 'overwrite 1'}} a_config_2 = { a_key_2: '2', a_key_overwritten: { a_key: 'overwrite 2'}} contextualize [ $: config: a_config_1 , $: config: a_config_2 ] .config.should.eql a_key_1: '1' a_key_overwritten: a_key: 'overwrite 2' a_key_2: '2' it '$ merge metadata in first level', -> a_metadata_1 = { a_key_1: '1', a_key_overwritten: { a_key: 'overwrite 1'}} a_metadata_2 = { a_key_2: '2', a_key_overwritten: { a_key: 'overwrite 2'}} contextualize [ $: metadata: a_metadata_1 , $: metadata: a_metadata_2 ] .metadata.should.eql a_key_1: '1' a_key_overwritten: a_key: 'overwrite 2' a_key_2: '2' it '$ keys in first level unless config or metadata', -> an_arg_1 = { a_key_1: '1', a_key_overwritten: { a_key: 'overwrite 1'}} an_arg_2 = { a_key_2: '2', a_key_overwritten: { a_key: 'overwrite 2'}} result = contextualize [ $: an_arg_1 , $: an_arg_2 ] { a_key_1: result.a_key_1 a_key_overwritten: result.a_key_overwritten a_key_2: result.a_key_2 }.should.eql a_key_1: '1' a_key_overwritten: a_key: 'overwrite 2' a_key_2: '2' it '$$ interpreted as metadata', -> expect = metadata: a: '1', b: '2' config: b: '' hooks: {} state: {} # Metadata in first argument contextualize [ $$: a: '1', b: '2' b: '' ] .should.eql expect # Metadata are overwritten contextualize [ $$: a: 'x', b: 'x' {b: '', $a: '1', $b: '2'} ] .should.eql expect
8924
{tags} = require '../test' contextualize = require '../../src/session/contextualize' normalize = require '../../src/session/normalize' describe 'session.contextualize', -> return unless tags.api it 'handle function as handler', -> expect = config: a: '' handler: (->) metadata: {}, hooks: {}, state: {} # String is place before objects contextualize [ (->) {a: ''} ] .should.eql expect # String is place after objects contextualize [ {a: ''} (->) ] .should.eql expect it 'handle string as metadata.argument', -> expect = config: b: '' metadata: argument: 'a' hooks: {}, state: {} # String is place before objects contextualize [ 'a' {b: ''} ] .should.eql expect # String is place after objects contextualize [ {b: ''} 'a' ] .should.eql expect it '$ merge config in first level', -> a_config_1 = { a_key_1: '1', a_key_overwritten: { a_key: 'overwrite 1'}} a_config_2 = { a_key_2: '2', a_key_overwritten: { a_key: 'overwrite 2'}} contextualize [ $: config: a_config_1 , $: config: a_config_2 ] .config.should.eql a_key_1: '1' a_key_overwritten: a_key: 'overwrite 2' a_key_2: '2' it '$ merge metadata in first level', -> a_metadata_1 = { a_key_1: '1', a_key_overwritten: { a_key: 'overwrite 1'}} a_metadata_2 = { a_key_2: '2', a_key_overwritten: { a_key: 'overwrite 2'}} contextualize [ $: metadata: a_metadata_1 , $: metadata: a_metadata_2 ] .metadata.should.eql a_key_1: '1' a_key_overwritten: a_key: '<KEY>' a_key_2: '<KEY>' it '$ keys in first level unless config or metadata', -> an_arg_1 = { a_key_1: '<KEY>', a_key_overwritten: { a_key: '<KEY>'}} an_arg_2 = { a_key_2: '<KEY>', a_key_overwritten: { a_key: '<KEY>'}} result = contextualize [ $: an_arg_1 , $: an_arg_2 ] { a_key_1: result.a_key_1 a_key_overwritten: result.a_key_overwritten a_key_2: result.a_key_2 }.should.eql a_key_1: '<KEY>' a_key_overwritten: a_key: '<KEY>' a_key_2: '<KEY>' it '$$ interpreted as metadata', -> expect = metadata: a: '1', b: '2' config: b: '' hooks: {} state: {} # Metadata in first argument contextualize [ $$: a: '1', b: '2' b: '' ] .should.eql expect # Metadata are overwritten contextualize [ $$: a: 'x', b: 'x' {b: '', $a: '1', $b: '2'} ] .should.eql expect
true
{tags} = require '../test' contextualize = require '../../src/session/contextualize' normalize = require '../../src/session/normalize' describe 'session.contextualize', -> return unless tags.api it 'handle function as handler', -> expect = config: a: '' handler: (->) metadata: {}, hooks: {}, state: {} # String is place before objects contextualize [ (->) {a: ''} ] .should.eql expect # String is place after objects contextualize [ {a: ''} (->) ] .should.eql expect it 'handle string as metadata.argument', -> expect = config: b: '' metadata: argument: 'a' hooks: {}, state: {} # String is place before objects contextualize [ 'a' {b: ''} ] .should.eql expect # String is place after objects contextualize [ {b: ''} 'a' ] .should.eql expect it '$ merge config in first level', -> a_config_1 = { a_key_1: '1', a_key_overwritten: { a_key: 'overwrite 1'}} a_config_2 = { a_key_2: '2', a_key_overwritten: { a_key: 'overwrite 2'}} contextualize [ $: config: a_config_1 , $: config: a_config_2 ] .config.should.eql a_key_1: '1' a_key_overwritten: a_key: 'overwrite 2' a_key_2: '2' it '$ merge metadata in first level', -> a_metadata_1 = { a_key_1: '1', a_key_overwritten: { a_key: 'overwrite 1'}} a_metadata_2 = { a_key_2: '2', a_key_overwritten: { a_key: 'overwrite 2'}} contextualize [ $: metadata: a_metadata_1 , $: metadata: a_metadata_2 ] .metadata.should.eql a_key_1: '1' a_key_overwritten: a_key: 'PI:KEY:<KEY>END_PI' a_key_2: 'PI:KEY:<KEY>END_PI' it '$ keys in first level unless config or metadata', -> an_arg_1 = { a_key_1: 'PI:KEY:<KEY>END_PI', a_key_overwritten: { a_key: 'PI:KEY:<KEY>END_PI'}} an_arg_2 = { a_key_2: 'PI:KEY:<KEY>END_PI', a_key_overwritten: { a_key: 'PI:KEY:<KEY>END_PI'}} result = contextualize [ $: an_arg_1 , $: an_arg_2 ] { a_key_1: result.a_key_1 a_key_overwritten: result.a_key_overwritten a_key_2: result.a_key_2 }.should.eql a_key_1: 'PI:KEY:<KEY>END_PI' a_key_overwritten: a_key: 'PI:KEY:<KEY>END_PI' a_key_2: 'PI:KEY:<KEY>END_PI' it '$$ interpreted as metadata', -> expect = metadata: a: '1', b: '2' config: b: '' hooks: {} state: {} # Metadata in first argument contextualize [ $$: a: '1', b: '2' b: '' ] .should.eql expect # Metadata are overwritten contextualize [ $$: a: 'x', b: 'x' {b: '', $a: '1', $b: '2'} ] .should.eql expect
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9994886517524719, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-stream3-pause-then-read.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. push = -> chunk = (if chunks-- > 0 then new Buffer(chunkSize) else null) if chunk totalPushed += chunk.length chunk.fill "x" r.push chunk return # first we read 100 bytes read100 = -> readn 100, onData return readn = (n, then_) -> console.error "read %d", n expectEndingData -= n (read = -> c = r.read(n) unless c r.once "readable", read else assert.equal c.length, n assert not r._readableState.flowing then_() return )() return # then we listen to some data events onData = -> expectEndingData -= 100 console.error "onData" seen = 0 r.on "data", od = (c) -> seen += c.length if seen >= 100 # seen enough r.removeListener "data", od r.pause() if seen > 100 # oh no, seen too much! # put the extra back. diff = seen - 100 r.unshift c.slice(c.length - diff) console.error "seen too much", seen, diff # Nothing should be lost in between setImmediate pipeLittle return return # Just pipe 200 bytes, then unshift the extra and unpipe pipeLittle = -> expectEndingData -= 200 console.error "pipe a little" w = new Writable() written = 0 w.on "finish", -> assert.equal written, 200 setImmediate read1234 return w._write = (chunk, encoding, cb) -> written += chunk.length if written >= 200 r.unpipe w w.end() cb() if written > 200 diff = written - 200 written -= diff r.unshift chunk.slice(chunk.length - diff) else setImmediate cb return r.pipe w return # now read 1234 more bytes read1234 = -> readn 1234, resumePause return resumePause = -> console.error "resumePause" # don't read anything, just resume and re-pause a whole bunch r.resume() r.pause() r.resume() r.pause() r.resume() r.pause() r.resume() r.pause() r.resume() r.pause() setImmediate pipe return pipe = -> console.error "pipe the rest" w = new Writable() written = 0 w._write = (chunk, encoding, cb) -> written += chunk.length cb() return w.on "finish", -> console.error "written", written, totalPushed assert.equal written, expectEndingData assert.equal totalPushed, expectTotalData console.log "ok" return r.pipe w return common = require("../common") assert = require("assert") stream = require("stream") Readable = stream.Readable Writable = stream.Writable totalChunks = 100 chunkSize = 99 expectTotalData = totalChunks * chunkSize expectEndingData = expectTotalData r = new Readable(highWaterMark: 1000) chunks = totalChunks r._read = (n) -> unless chunks % 2 setImmediate push else unless chunks % 3 process.nextTick push else push() return totalPushed = 0 read100()
195518
# 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. push = -> chunk = (if chunks-- > 0 then new Buffer(chunkSize) else null) if chunk totalPushed += chunk.length chunk.fill "x" r.push chunk return # first we read 100 bytes read100 = -> readn 100, onData return readn = (n, then_) -> console.error "read %d", n expectEndingData -= n (read = -> c = r.read(n) unless c r.once "readable", read else assert.equal c.length, n assert not r._readableState.flowing then_() return )() return # then we listen to some data events onData = -> expectEndingData -= 100 console.error "onData" seen = 0 r.on "data", od = (c) -> seen += c.length if seen >= 100 # seen enough r.removeListener "data", od r.pause() if seen > 100 # oh no, seen too much! # put the extra back. diff = seen - 100 r.unshift c.slice(c.length - diff) console.error "seen too much", seen, diff # Nothing should be lost in between setImmediate pipeLittle return return # Just pipe 200 bytes, then unshift the extra and unpipe pipeLittle = -> expectEndingData -= 200 console.error "pipe a little" w = new Writable() written = 0 w.on "finish", -> assert.equal written, 200 setImmediate read1234 return w._write = (chunk, encoding, cb) -> written += chunk.length if written >= 200 r.unpipe w w.end() cb() if written > 200 diff = written - 200 written -= diff r.unshift chunk.slice(chunk.length - diff) else setImmediate cb return r.pipe w return # now read 1234 more bytes read1234 = -> readn 1234, resumePause return resumePause = -> console.error "resumePause" # don't read anything, just resume and re-pause a whole bunch r.resume() r.pause() r.resume() r.pause() r.resume() r.pause() r.resume() r.pause() r.resume() r.pause() setImmediate pipe return pipe = -> console.error "pipe the rest" w = new Writable() written = 0 w._write = (chunk, encoding, cb) -> written += chunk.length cb() return w.on "finish", -> console.error "written", written, totalPushed assert.equal written, expectEndingData assert.equal totalPushed, expectTotalData console.log "ok" return r.pipe w return common = require("../common") assert = require("assert") stream = require("stream") Readable = stream.Readable Writable = stream.Writable totalChunks = 100 chunkSize = 99 expectTotalData = totalChunks * chunkSize expectEndingData = expectTotalData r = new Readable(highWaterMark: 1000) chunks = totalChunks r._read = (n) -> unless chunks % 2 setImmediate push else unless chunks % 3 process.nextTick push else push() return totalPushed = 0 read100()
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. push = -> chunk = (if chunks-- > 0 then new Buffer(chunkSize) else null) if chunk totalPushed += chunk.length chunk.fill "x" r.push chunk return # first we read 100 bytes read100 = -> readn 100, onData return readn = (n, then_) -> console.error "read %d", n expectEndingData -= n (read = -> c = r.read(n) unless c r.once "readable", read else assert.equal c.length, n assert not r._readableState.flowing then_() return )() return # then we listen to some data events onData = -> expectEndingData -= 100 console.error "onData" seen = 0 r.on "data", od = (c) -> seen += c.length if seen >= 100 # seen enough r.removeListener "data", od r.pause() if seen > 100 # oh no, seen too much! # put the extra back. diff = seen - 100 r.unshift c.slice(c.length - diff) console.error "seen too much", seen, diff # Nothing should be lost in between setImmediate pipeLittle return return # Just pipe 200 bytes, then unshift the extra and unpipe pipeLittle = -> expectEndingData -= 200 console.error "pipe a little" w = new Writable() written = 0 w.on "finish", -> assert.equal written, 200 setImmediate read1234 return w._write = (chunk, encoding, cb) -> written += chunk.length if written >= 200 r.unpipe w w.end() cb() if written > 200 diff = written - 200 written -= diff r.unshift chunk.slice(chunk.length - diff) else setImmediate cb return r.pipe w return # now read 1234 more bytes read1234 = -> readn 1234, resumePause return resumePause = -> console.error "resumePause" # don't read anything, just resume and re-pause a whole bunch r.resume() r.pause() r.resume() r.pause() r.resume() r.pause() r.resume() r.pause() r.resume() r.pause() setImmediate pipe return pipe = -> console.error "pipe the rest" w = new Writable() written = 0 w._write = (chunk, encoding, cb) -> written += chunk.length cb() return w.on "finish", -> console.error "written", written, totalPushed assert.equal written, expectEndingData assert.equal totalPushed, expectTotalData console.log "ok" return r.pipe w return common = require("../common") assert = require("assert") stream = require("stream") Readable = stream.Readable Writable = stream.Writable totalChunks = 100 chunkSize = 99 expectTotalData = totalChunks * chunkSize expectEndingData = expectTotalData r = new Readable(highWaterMark: 1000) chunks = totalChunks r._read = (n) -> unless chunks % 2 setImmediate push else unless chunks % 3 process.nextTick push else push() return totalPushed = 0 read100()
[ { "context": "ge then 'runtime' else 'extension'\n\nstorageKey = 'metrics'\nstorageOptionKey = 'option'\nstorageDataKey = 'st", "end": 124, "score": 0.7664830088615417, "start": 117, "tag": "KEY", "value": "metrics" }, { "context": "sion'\n\nstorageKey = 'metrics'\nstorageOptionKey =...
app/scripts/background.coffee
ryaneof/tab-performance
0
'use strict'; env = if chrome.runtime and chrome.runtime.sendMessage then 'runtime' else 'extension' storageKey = 'metrics' storageOptionKey = 'option' storageDataKey = 'structure' defaultMetrics = 'tabLoad' tabIdKey = (id) -> 'tab' + id # calc metrics calcPerfMetrics = (raw) -> res = raw init = if !raw.redirectStart then raw.fetchStart else raw.redirectStart res.init = init res.redirectTime = 0 res.redirectSpent = raw.redirectEnd - raw.redirectStart res.domainLookupTime = raw.domainLookupStart - init res.domainLookupSpent = raw.domainLookupEnd - raw.domainLookupStart res.connectTime = raw.connectStart - init res.connectSpent = raw.connectEnd - raw.connectStart res.requestTime = raw.responseStart - init res.requestSpent = raw.responseEnd - raw.responseStart res.responseTime = raw.responseStart - init res.responseSpent = raw.responseEnd - raw.responseStart res.domTime = raw.domLoading - init res.domSpent = raw.domComplete - raw.domLoading res.domContentLoadedEventTime = raw.domContentLoadedEventStart - init res.domContentLoadedEventSpent = raw.domContentLoadedEventEnd - raw.domContentLoadedEventStart res.loadEventTime = raw.loadEventStart - init res.loadEventSpent = raw.loadEventEnd - raw.loadEventStart res.tabLoadSpent = raw.loadEventEnd - init return res # on page loaded, apply calc metrics messageListener = (performance, sender) -> perf = calcPerfMetrics(performance) chrome.storage.local.get([ storageKey, storageOptionKey, storageDataKey ], (data) -> data[storageKey][tabIdKey(sender.tab.id)] = perf badgeOpts = text: ((perf[data[storageOptionKey] + 'Spent'] / 1000).toPrecision(3) + '').substring(0, 4) tabId: sender.tab.id chrome.browserAction.setBadgeText(badgeOpts) chrome.storage.local.set(data) ) # on tab removed removeListener = (tabId) -> chrome.storage.local.get(storageKey, (data) -> if data[storageKey] delete data[storageKey][tabIdKey(tabId)] chrome.storage.local.set(data) ) # init data strcture, default metrics installListener = () -> data = {} data[storageKey] = {} data[storageOptionKey] = defaultMetrics data[storageDataKey] = tabLoad: name: 'Total' green: 1000 red: 3000 redirect: name: 'Redirect' green: 10 red: 1000 domainLookup: name: 'DNS' green: 50 red: 1000 connect: name: 'Connect' green: 50 red: 1000 request: name: 'Request' green: 50 red: 1000 response: name: 'Response' green: 50 red: 1000 dom: name: 'DOM Loading' green: 50 red: 1000 domContentLoadedEvent: name: 'DOM Content Loaded Event' green: 50 red: 1000 loadEvent: name: 'Load Event' green: 50 red: 1000 chrome.storage.local.set(data) # add event listeners chrome[env].onMessage.addListener(messageListener) chrome.tabs.onRemoved.addListener(removeListener) chrome[env].onInstalled.addListener(installListener)
35249
'use strict'; env = if chrome.runtime and chrome.runtime.sendMessage then 'runtime' else 'extension' storageKey = '<KEY>' storageOptionKey = '<KEY>' storageDataKey = '<KEY>' defaultMetrics = 'tabLoad' tabIdKey = (id) -> '<KEY>' + id # calc metrics calcPerfMetrics = (raw) -> res = raw init = if !raw.redirectStart then raw.fetchStart else raw.redirectStart res.init = init res.redirectTime = 0 res.redirectSpent = raw.redirectEnd - raw.redirectStart res.domainLookupTime = raw.domainLookupStart - init res.domainLookupSpent = raw.domainLookupEnd - raw.domainLookupStart res.connectTime = raw.connectStart - init res.connectSpent = raw.connectEnd - raw.connectStart res.requestTime = raw.responseStart - init res.requestSpent = raw.responseEnd - raw.responseStart res.responseTime = raw.responseStart - init res.responseSpent = raw.responseEnd - raw.responseStart res.domTime = raw.domLoading - init res.domSpent = raw.domComplete - raw.domLoading res.domContentLoadedEventTime = raw.domContentLoadedEventStart - init res.domContentLoadedEventSpent = raw.domContentLoadedEventEnd - raw.domContentLoadedEventStart res.loadEventTime = raw.loadEventStart - init res.loadEventSpent = raw.loadEventEnd - raw.loadEventStart res.tabLoadSpent = raw.loadEventEnd - init return res # on page loaded, apply calc metrics messageListener = (performance, sender) -> perf = calcPerfMetrics(performance) chrome.storage.local.get([ storageKey, storageOptionKey, storageDataKey ], (data) -> data[storageKey][tabIdKey(sender.tab.id)] = perf badgeOpts = text: ((perf[data[storageOptionKey] + 'Spent'] / 1000).toPrecision(3) + '').substring(0, 4) tabId: sender.tab.id chrome.browserAction.setBadgeText(badgeOpts) chrome.storage.local.set(data) ) # on tab removed removeListener = (tabId) -> chrome.storage.local.get(storageKey, (data) -> if data[storageKey] delete data[storageKey][tabIdKey(tabId)] chrome.storage.local.set(data) ) # init data strcture, default metrics installListener = () -> data = {} data[storageKey] = {} data[storageOptionKey] = defaultMetrics data[storageDataKey] = tabLoad: name: 'Total' green: 1000 red: 3000 redirect: name: 'Redirect' green: 10 red: 1000 domainLookup: name: 'DNS' green: 50 red: 1000 connect: name: 'Connect' green: 50 red: 1000 request: name: 'Request' green: 50 red: 1000 response: name: 'Response' green: 50 red: 1000 dom: name: 'DOM Loading' green: 50 red: 1000 domContentLoadedEvent: name: 'DOM Content Loaded Event' green: 50 red: 1000 loadEvent: name: 'Load Event' green: 50 red: 1000 chrome.storage.local.set(data) # add event listeners chrome[env].onMessage.addListener(messageListener) chrome.tabs.onRemoved.addListener(removeListener) chrome[env].onInstalled.addListener(installListener)
true
'use strict'; env = if chrome.runtime and chrome.runtime.sendMessage then 'runtime' else 'extension' storageKey = 'PI:KEY:<KEY>END_PI' storageOptionKey = 'PI:KEY:<KEY>END_PI' storageDataKey = 'PI:KEY:<KEY>END_PI' defaultMetrics = 'tabLoad' tabIdKey = (id) -> 'PI:KEY:<KEY>END_PI' + id # calc metrics calcPerfMetrics = (raw) -> res = raw init = if !raw.redirectStart then raw.fetchStart else raw.redirectStart res.init = init res.redirectTime = 0 res.redirectSpent = raw.redirectEnd - raw.redirectStart res.domainLookupTime = raw.domainLookupStart - init res.domainLookupSpent = raw.domainLookupEnd - raw.domainLookupStart res.connectTime = raw.connectStart - init res.connectSpent = raw.connectEnd - raw.connectStart res.requestTime = raw.responseStart - init res.requestSpent = raw.responseEnd - raw.responseStart res.responseTime = raw.responseStart - init res.responseSpent = raw.responseEnd - raw.responseStart res.domTime = raw.domLoading - init res.domSpent = raw.domComplete - raw.domLoading res.domContentLoadedEventTime = raw.domContentLoadedEventStart - init res.domContentLoadedEventSpent = raw.domContentLoadedEventEnd - raw.domContentLoadedEventStart res.loadEventTime = raw.loadEventStart - init res.loadEventSpent = raw.loadEventEnd - raw.loadEventStart res.tabLoadSpent = raw.loadEventEnd - init return res # on page loaded, apply calc metrics messageListener = (performance, sender) -> perf = calcPerfMetrics(performance) chrome.storage.local.get([ storageKey, storageOptionKey, storageDataKey ], (data) -> data[storageKey][tabIdKey(sender.tab.id)] = perf badgeOpts = text: ((perf[data[storageOptionKey] + 'Spent'] / 1000).toPrecision(3) + '').substring(0, 4) tabId: sender.tab.id chrome.browserAction.setBadgeText(badgeOpts) chrome.storage.local.set(data) ) # on tab removed removeListener = (tabId) -> chrome.storage.local.get(storageKey, (data) -> if data[storageKey] delete data[storageKey][tabIdKey(tabId)] chrome.storage.local.set(data) ) # init data strcture, default metrics installListener = () -> data = {} data[storageKey] = {} data[storageOptionKey] = defaultMetrics data[storageDataKey] = tabLoad: name: 'Total' green: 1000 red: 3000 redirect: name: 'Redirect' green: 10 red: 1000 domainLookup: name: 'DNS' green: 50 red: 1000 connect: name: 'Connect' green: 50 red: 1000 request: name: 'Request' green: 50 red: 1000 response: name: 'Response' green: 50 red: 1000 dom: name: 'DOM Loading' green: 50 red: 1000 domContentLoadedEvent: name: 'DOM Content Loaded Event' green: 50 red: 1000 loadEvent: name: 'Load Event' green: 50 red: 1000 chrome.storage.local.set(data) # add event listeners chrome[env].onMessage.addListener(messageListener) chrome.tabs.onRemoved.addListener(removeListener) chrome[env].onInstalled.addListener(installListener)
[ { "context": " Unit = Tmp.Unit\n unit = new Unit(name: 'Zeratul', info: 'Dark Templar')\n\n itSync 'should perfo", "end": 263, "score": 0.9996857047080994, "start": 256, "tag": "NAME", "value": "Zeratul" }, { "context": "its.count().should.eql 1\n units.first(name: '...
spec/model/crud-spec.coffee
wanbok/mongo-model
1
require '../helper' describe "Model CRUD", -> withMongo() describe "Main Object", -> [Unit, unit] = [null, null] beforeEach -> class Tmp.Unit extends Model @collection 'units' Unit = Tmp.Unit unit = new Unit(name: 'Zeratul', info: 'Dark Templar') itSync 'should perform CRUD with collection methods', -> # Read. units = $db.collection 'units' units.count().should.eql 0 units.all().should.eql [] _(units.first()).should.not.exist # Create. units.save(unit).should.eql true _(unit._id).should.exist # Read. units.count().should.eql 1 obj = units.first() obj.toHash().should.eql unit.toHash() obj.constructor.should.eql unit.constructor # Update. unit.info = 'Killer of Cerebrates' units.save(unit).should.be.true units.count().should.eql 1 units.first(name: 'Zeratul').info.should.eql 'Killer of Cerebrates' # Delete. units.delete(unit).should.be.true units.count().should.eql 0 itSync 'should perform CRUD with model methods', -> # Read. Unit.count().should.eql 0 Unit.all().should.eql [] _(Unit.first()).should.not.exist # Create. unit.save().should.be.true _(unit._id).should.exist # Read. Unit.count().should.eql 1 all = Unit.all() all.length.should.eql 1 all[0].toHash().should.eql unit.toHash() Unit.first().toHash().should.eql unit.toHash() # Update. unit.info = 'Killer of Cerebrates' unit.save().should.be.true Unit.count().should.eql 1 Unit.first(name: 'Zeratul').info.should.eql 'Killer of Cerebrates' # Delete. unit.delete().should.be.true Unit.count().should.eql 0 itSync 'should be able to save model to another collection', -> heroes = $db.collection 'heroes' unit.save collection: heroes heroes.first().toHash().should.eql unit.toHash() itSync 'should be able to save model to another collection defined as symbol', -> heroes = $db.collection 'heroes' unit.save collection: 'heroes' heroes.first().toHash().should.eql unit.toHash() itSync 'should update with modifiers', -> unit.save() Unit.update {_id: unit._id}, $set: {name: 'Tassadar'} unit.reload() unit.name.should.eql 'Tassadar' unit.update $set: {name: 'Fenix'} unit.reload() unit.name.should.eql 'Fenix' itSync 'should build model', -> unit = Unit.build name: 'Zeratul' unit.name.should.eql 'Zeratul' itSync 'should create model', -> unit = Unit.create name: 'Zeratul' unit.toHash().should.eql {name : 'Zeratul', _id : unit._id, _class : 'Unit'} Unit.first().name.should.eql 'Zeratul' itSync 'should delete all models', -> Unit.create name: 'Zeratul' Unit.count().should.eql 1 Unit.delete() Unit.count().should.eql 0 itSync "should allow to read object as hash, without unmarshalling", -> units = $db.collection 'units' units.save unit units.first({}, object: false).should.eql unit.toHash() itSync 'should reload model', -> unit = Unit.create name: 'Zeratul' unit.name = 'Jim' unit.reload() unit.name.should.eql 'Zeratul' describe "Embedded Object", -> unit = null beforeEach -> class Tmp.Unit extends Model @embedded 'items' class Tmp.Item extends Model unit = new Tmp.Unit() unit.items = [ new Tmp.Item(name: 'Psionic blade') new Tmp.Item(name: 'Plasma shield') ] itSync 'should perform CRUD', -> # Create. units = $db.collection 'units' units.save unit _(unit._id).should.exist item = unit.items[0] _(item._id).should.not.exist # Read. units.count().should.eql 1 unit2 = units.first() unit2.toHash().should.eql unit.toHash() item = unit.items[0] _(item._id).should.not.exist # Update. unit.items[0].name = 'Psionic blade level 3' item = new Tmp.Item name: 'Power suit' unit.items.push item units.save unit units.count().should.eql 1 unit2 = units.first() unit2.toHash().should.eql unit.toHash() # Delete. units.delete unit units.count().should.eql 0 itSync "should have :_parent reference to the main object", -> units = $db.collection 'units' units.save unit unit = units.first() _(unit._parent).should.not.exist unit.items[0]._parent.should.eql unit it "should convert object to and from mongo-hash", -> class Tmp.Post extends Model @embedded 'tags', 'comments' class Tmp.Comment extends Model # Should aslo allow to use models that # are saved to array. # To do so we need to use toMongo and afterFromMongo. class Tmp.Tags extends Model constructor: -> @array = [] push: (args...) -> @array.push args... toMongo: -> @array Tmp.Post.prototype.afterFromMongo = (doc) -> @tags = new Tmp.Tags @tags.array = doc.tags # Creating some data. comment = new Tmp.Comment() comment.text = 'Some text' tags = new Tmp.Tags() tags.push 'a', 'b' post = new Tmp.Post() post.title = 'Some title' post.comments = [comment] post.tags = tags hash = { _class : 'Post', title : 'Some title', comments : [{text: 'Some text', _class: 'Comment'}], tags : ['a', 'b'] } # Converting to mongo. post.toMongo().should.eql hash [post._id, hash._id] = ['some id', 'some id'] post.toMongo().should.eql hash # Converting from mongo. Model._fromMongo(hash).toMongo().should.eql hash
164309
require '../helper' describe "Model CRUD", -> withMongo() describe "Main Object", -> [Unit, unit] = [null, null] beforeEach -> class Tmp.Unit extends Model @collection 'units' Unit = Tmp.Unit unit = new Unit(name: '<NAME>', info: 'Dark Templar') itSync 'should perform CRUD with collection methods', -> # Read. units = $db.collection 'units' units.count().should.eql 0 units.all().should.eql [] _(units.first()).should.not.exist # Create. units.save(unit).should.eql true _(unit._id).should.exist # Read. units.count().should.eql 1 obj = units.first() obj.toHash().should.eql unit.toHash() obj.constructor.should.eql unit.constructor # Update. unit.info = 'Killer of Cerebrates' units.save(unit).should.be.true units.count().should.eql 1 units.first(name: '<NAME>').info.should.eql 'Killer of Cerebrates' # Delete. units.delete(unit).should.be.true units.count().should.eql 0 itSync 'should perform CRUD with model methods', -> # Read. Unit.count().should.eql 0 Unit.all().should.eql [] _(Unit.first()).should.not.exist # Create. unit.save().should.be.true _(unit._id).should.exist # Read. Unit.count().should.eql 1 all = Unit.all() all.length.should.eql 1 all[0].toHash().should.eql unit.toHash() Unit.first().toHash().should.eql unit.toHash() # Update. unit.info = 'Killer of Cerebrates' unit.save().should.be.true Unit.count().should.eql 1 Unit.first(name: '<NAME>').info.should.eql 'Killer of Cerebrates' # Delete. unit.delete().should.be.true Unit.count().should.eql 0 itSync 'should be able to save model to another collection', -> heroes = $db.collection 'heroes' unit.save collection: heroes heroes.first().toHash().should.eql unit.toHash() itSync 'should be able to save model to another collection defined as symbol', -> heroes = $db.collection 'heroes' unit.save collection: 'heroes' heroes.first().toHash().should.eql unit.toHash() itSync 'should update with modifiers', -> unit.save() Unit.update {_id: unit._id}, $set: {name: '<NAME>'} unit.reload() unit.name.should.eql '<NAME>' unit.update $set: {name: '<NAME>'} unit.reload() unit.name.should.eql '<NAME>' itSync 'should build model', -> unit = Unit.build name: '<NAME>' unit.name.should.eql '<NAME>' itSync 'should create model', -> unit = Unit.create name: '<NAME>' unit.toHash().should.eql {name : '<NAME>', _id : unit._id, _class : 'Unit'} Unit.first().name.should.eql '<NAME>' itSync 'should delete all models', -> Unit.create name: '<NAME>' Unit.count().should.eql 1 Unit.delete() Unit.count().should.eql 0 itSync "should allow to read object as hash, without unmarshalling", -> units = $db.collection 'units' units.save unit units.first({}, object: false).should.eql unit.toHash() itSync 'should reload model', -> unit = Unit.create name: '<NAME>' unit.name = '<NAME>' unit.reload() unit.name.should.eql '<NAME>' describe "Embedded Object", -> unit = null beforeEach -> class Tmp.Unit extends Model @embedded 'items' class Tmp.Item extends Model unit = new Tmp.Unit() unit.items = [ new Tmp.Item(name: 'Psionic blade') new Tmp.Item(name: 'Plasma shield') ] itSync 'should perform CRUD', -> # Create. units = $db.collection 'units' units.save unit _(unit._id).should.exist item = unit.items[0] _(item._id).should.not.exist # Read. units.count().should.eql 1 unit2 = units.first() unit2.toHash().should.eql unit.toHash() item = unit.items[0] _(item._id).should.not.exist # Update. unit.items[0].name = 'Psionic blade level 3' item = new Tmp.Item name: 'Power suit' unit.items.push item units.save unit units.count().should.eql 1 unit2 = units.first() unit2.toHash().should.eql unit.toHash() # Delete. units.delete unit units.count().should.eql 0 itSync "should have :_parent reference to the main object", -> units = $db.collection 'units' units.save unit unit = units.first() _(unit._parent).should.not.exist unit.items[0]._parent.should.eql unit it "should convert object to and from mongo-hash", -> class Tmp.Post extends Model @embedded 'tags', 'comments' class Tmp.Comment extends Model # Should aslo allow to use models that # are saved to array. # To do so we need to use toMongo and afterFromMongo. class Tmp.Tags extends Model constructor: -> @array = [] push: (args...) -> @array.push args... toMongo: -> @array Tmp.Post.prototype.afterFromMongo = (doc) -> @tags = new Tmp.Tags @tags.array = doc.tags # Creating some data. comment = new Tmp.Comment() comment.text = 'Some text' tags = new Tmp.Tags() tags.push 'a', 'b' post = new Tmp.Post() post.title = 'Some title' post.comments = [comment] post.tags = tags hash = { _class : 'Post', title : 'Some title', comments : [{text: 'Some text', _class: 'Comment'}], tags : ['a', 'b'] } # Converting to mongo. post.toMongo().should.eql hash [post._id, hash._id] = ['some id', 'some id'] post.toMongo().should.eql hash # Converting from mongo. Model._fromMongo(hash).toMongo().should.eql hash
true
require '../helper' describe "Model CRUD", -> withMongo() describe "Main Object", -> [Unit, unit] = [null, null] beforeEach -> class Tmp.Unit extends Model @collection 'units' Unit = Tmp.Unit unit = new Unit(name: 'PI:NAME:<NAME>END_PI', info: 'Dark Templar') itSync 'should perform CRUD with collection methods', -> # Read. units = $db.collection 'units' units.count().should.eql 0 units.all().should.eql [] _(units.first()).should.not.exist # Create. units.save(unit).should.eql true _(unit._id).should.exist # Read. units.count().should.eql 1 obj = units.first() obj.toHash().should.eql unit.toHash() obj.constructor.should.eql unit.constructor # Update. unit.info = 'Killer of Cerebrates' units.save(unit).should.be.true units.count().should.eql 1 units.first(name: 'PI:NAME:<NAME>END_PI').info.should.eql 'Killer of Cerebrates' # Delete. units.delete(unit).should.be.true units.count().should.eql 0 itSync 'should perform CRUD with model methods', -> # Read. Unit.count().should.eql 0 Unit.all().should.eql [] _(Unit.first()).should.not.exist # Create. unit.save().should.be.true _(unit._id).should.exist # Read. Unit.count().should.eql 1 all = Unit.all() all.length.should.eql 1 all[0].toHash().should.eql unit.toHash() Unit.first().toHash().should.eql unit.toHash() # Update. unit.info = 'Killer of Cerebrates' unit.save().should.be.true Unit.count().should.eql 1 Unit.first(name: 'PI:NAME:<NAME>END_PI').info.should.eql 'Killer of Cerebrates' # Delete. unit.delete().should.be.true Unit.count().should.eql 0 itSync 'should be able to save model to another collection', -> heroes = $db.collection 'heroes' unit.save collection: heroes heroes.first().toHash().should.eql unit.toHash() itSync 'should be able to save model to another collection defined as symbol', -> heroes = $db.collection 'heroes' unit.save collection: 'heroes' heroes.first().toHash().should.eql unit.toHash() itSync 'should update with modifiers', -> unit.save() Unit.update {_id: unit._id}, $set: {name: 'PI:NAME:<NAME>END_PI'} unit.reload() unit.name.should.eql 'PI:NAME:<NAME>END_PI' unit.update $set: {name: 'PI:NAME:<NAME>END_PI'} unit.reload() unit.name.should.eql 'PI:NAME:<NAME>END_PI' itSync 'should build model', -> unit = Unit.build name: 'PI:NAME:<NAME>END_PI' unit.name.should.eql 'PI:NAME:<NAME>END_PI' itSync 'should create model', -> unit = Unit.create name: 'PI:NAME:<NAME>END_PI' unit.toHash().should.eql {name : 'PI:NAME:<NAME>END_PI', _id : unit._id, _class : 'Unit'} Unit.first().name.should.eql 'PI:NAME:<NAME>END_PI' itSync 'should delete all models', -> Unit.create name: 'PI:NAME:<NAME>END_PI' Unit.count().should.eql 1 Unit.delete() Unit.count().should.eql 0 itSync "should allow to read object as hash, without unmarshalling", -> units = $db.collection 'units' units.save unit units.first({}, object: false).should.eql unit.toHash() itSync 'should reload model', -> unit = Unit.create name: 'PI:NAME:<NAME>END_PI' unit.name = 'PI:NAME:<NAME>END_PI' unit.reload() unit.name.should.eql 'PI:NAME:<NAME>END_PI' describe "Embedded Object", -> unit = null beforeEach -> class Tmp.Unit extends Model @embedded 'items' class Tmp.Item extends Model unit = new Tmp.Unit() unit.items = [ new Tmp.Item(name: 'Psionic blade') new Tmp.Item(name: 'Plasma shield') ] itSync 'should perform CRUD', -> # Create. units = $db.collection 'units' units.save unit _(unit._id).should.exist item = unit.items[0] _(item._id).should.not.exist # Read. units.count().should.eql 1 unit2 = units.first() unit2.toHash().should.eql unit.toHash() item = unit.items[0] _(item._id).should.not.exist # Update. unit.items[0].name = 'Psionic blade level 3' item = new Tmp.Item name: 'Power suit' unit.items.push item units.save unit units.count().should.eql 1 unit2 = units.first() unit2.toHash().should.eql unit.toHash() # Delete. units.delete unit units.count().should.eql 0 itSync "should have :_parent reference to the main object", -> units = $db.collection 'units' units.save unit unit = units.first() _(unit._parent).should.not.exist unit.items[0]._parent.should.eql unit it "should convert object to and from mongo-hash", -> class Tmp.Post extends Model @embedded 'tags', 'comments' class Tmp.Comment extends Model # Should aslo allow to use models that # are saved to array. # To do so we need to use toMongo and afterFromMongo. class Tmp.Tags extends Model constructor: -> @array = [] push: (args...) -> @array.push args... toMongo: -> @array Tmp.Post.prototype.afterFromMongo = (doc) -> @tags = new Tmp.Tags @tags.array = doc.tags # Creating some data. comment = new Tmp.Comment() comment.text = 'Some text' tags = new Tmp.Tags() tags.push 'a', 'b' post = new Tmp.Post() post.title = 'Some title' post.comments = [comment] post.tags = tags hash = { _class : 'Post', title : 'Some title', comments : [{text: 'Some text', _class: 'Comment'}], tags : ['a', 'b'] } # Converting to mongo. post.toMongo().should.eql hash [post._id, hash._id] = ['some id', 'some id'] post.toMongo().should.eql hash # Converting from mongo. Model._fromMongo(hash).toMongo().should.eql hash
[ { "context": "\"\n appSecret: process.env.FACEBOOK_APPSECRET or \"c82696768ae4ad8b63db874cb64eb558\"\n appNamespace: process.env.FACEBOOK_APPNAMESPAC", "end": 252, "score": 0.9963421821594238, "start": 220, "tag": "KEY", "value": "c82696768ae4ad8b63db874cb64eb558" } ]
node_modules/liquid.coffee/example/scrumptious/config.coffee
darkoverlordofdata/shmupwarz-ooc
1
config = {} # should end in / config.rootUrl = process.env.ROOT_URL or "http://localhost:3000/" config.facebook = appId: process.env.FACEBOOK_APPID or "130243393813697" appSecret: process.env.FACEBOOK_APPSECRET or "c82696768ae4ad8b63db874cb64eb558" appNamespace: process.env.FACEBOOK_APPNAMESPACE or "nodescrumptious" redirectUri: process.env.FACEBOOK_REDIRECTURI or config.rootUrl + "login/callback" module.exports = config
175167
config = {} # should end in / config.rootUrl = process.env.ROOT_URL or "http://localhost:3000/" config.facebook = appId: process.env.FACEBOOK_APPID or "130243393813697" appSecret: process.env.FACEBOOK_APPSECRET or "<KEY>" appNamespace: process.env.FACEBOOK_APPNAMESPACE or "nodescrumptious" redirectUri: process.env.FACEBOOK_REDIRECTURI or config.rootUrl + "login/callback" module.exports = config
true
config = {} # should end in / config.rootUrl = process.env.ROOT_URL or "http://localhost:3000/" config.facebook = appId: process.env.FACEBOOK_APPID or "130243393813697" appSecret: process.env.FACEBOOK_APPSECRET or "PI:KEY:<KEY>END_PI" appNamespace: process.env.FACEBOOK_APPNAMESPACE or "nodescrumptious" redirectUri: process.env.FACEBOOK_REDIRECTURI or config.rootUrl + "login/callback" module.exports = config
[ { "context": "ote.org without potty mouth filter\n#\n# Author:\n# nickfloyd\n\nSelect \t= require(\"soupselect\").select\nHtmlP", "end": 504, "score": 0.9996455907821655, "start": 495, "tag": "USERNAME", "value": "nickfloyd" }, { "context": ") ->\n\t\tmsg\n\t\t\t.http(\"http://...
src/scripts/mitch-hedberg.coffee
junhui/hubot-scripts
1
# Description: # Allows Hubot to find an awesome Mitch Hedberg quotes # # Dependencies: # "htmlparser": "1.7.6" # "soupselect": "0.2.0" # "jsdom": "0.2.14" # "underscore": "1.3.3" # # Configuration: # None # # Commands: # hubot get mitch - This spits out one of the many awesome Mitch Hedberg quotes from wikiquote.org with filter # hubot get dirty mitch - This spits out one of the many awesome Mitch Hedberg quotes from wikiquote.org without potty mouth filter # # Author: # nickfloyd Select = require("soupselect").select HtmlParser = require "htmlparser" JsDom = require "jsdom" _ = require("underscore") StaticQuotes = [ "A severed foot is the ultimate stocking stuffer.", "I hope the next time I move I get a real easy phone number, something that's real easy to remember. Something like two two two two two two two. I would say \"Sweet.\" And then people would say, \"Mitch, how do I get a hold of you?\" I'd say, \"Just press two for a while and when I answer, you will know you have pressed two enough.", "My friend asked me if I wanted a frozen banana, I said \"No, but I want a regular banana later, so ... yeah\".", "On a traffic light green means 'go' and yellow means 'yield', but on a banana it's just the opposite. Green means 'hold on,' yellow means 'go ahead,' and red means, 'where did you get that banana ?'", "I'm against picketing, but I don't know how to show it.", "I think Bigfoot is blurry, that's the problem. It's not the photographer's fault. Bigfoot is blurry, and that's extra scary to me. There's a large, out-of-focus monster roaming the countryside. Run, he's fuzzy, get out of here.", "One time, this guy handed me a picture of him, he said,\"Here's a picture of me when I was younger.\" Every picture is of you when you were younger. ", "My fake plants died because I did not pretend to water them.", "I walked into Target, but I missed. I think the entrance to Target should have people splattered all around. And, when I finally get in, the guy says, \"Can I help you?\" \"Just practicing.\"", "When I was a boy, I laid in my twin-sized bed and wondered where my brother was.", "Is a hippopotamus a hippopotamus or just a really cool opotamus?", "If I had a dollar for every time I said that, I'd be making money in a very weird way.", "My belt holds up my pants and my pants have belt loops that hold up the belt. What's really goin on down there? Who is the real hero?", "I'm an ice sculptor - last night I made a cube.", "If you have dentures, don't use artificial sweetener, cause you'll get a fake cavity.", "I saw this dude, he was wearing a leather jacket, and at the same time he was eating a hamburger and drinking a glass of milk. I said to him \"Dude, you're a cow. The metamorphosis is complete. Don't fall asleep or I'll tip you over.\"", "A burrito is a sleeping bag for ground beef.", "Here's a thought for sweat shop owners: Air Conditioning. Problem solved.", "I saw a sheet lying on the floor, it must have been a ghost that had passed out... So I kicked it.", "The Kit-Kat candy bar has the name 'Kit-Kat' imprinted into the chocolate. That robs you of chocolate!"] module.exports = (robot) -> robot.respond /get( dirty)? mitch$/i, (msg) -> msg .http("http://en.wikiquote.org/wiki/Mitch_Hedberg") .header("User-Agent: Mitchbot for Hubot (+https://github.com/github/hubot-scripts)") .get() (err, res, body) -> quotes = parse_html(body, "li") quote = get_quote msg, quotes get_quote = (msg, quotes) -> pottyParm = msg.match[1].replace /^\s+|\s+$/g, "" if msg.match[1] != undefined nodeChildren = _.flatten childern_of_type(quotes[Math.floor(Math.random() * quotes.length)]) quote = (textNode.data for textNode in nodeChildren).join '' if pottyParm == "dirty" msg.send quote else keep_it_clean msg, quote, (body, err) -> msg.send StaticQuotes[Math.floor(Math.random() * StaticQuotes.length)] if err #because potty word just sounds funny msg.send body.getElementsByTagName("CleanText")[0].firstChild.nodeValue.replace /(Explicit)+/g, "potty word" # Helpers parse_html = (html, selector) -> handler = new HtmlParser.DefaultHandler((() ->), ignoreWhitespace: true) parser = new HtmlParser.Parser handler parser.parseComplete html Select handler.dom, selector childern_of_type = (root) -> return [root] if root?.type is "text" if root?.children?.length > 0 return (childern_of_type(child) for child in root.children) get_dom = (xml) -> body = JsDom.jsdom(xml) throw Error("No XML data returned.") if body.getElementsByTagName("FilterReturn")[0].childNodes.length == 0 return body keep_it_clean = (msg, quote, cb) -> msg.http("http://wsf.cdyne.com/ProfanityWS/Profanity.asmx/SimpleProfanityFilter") .query(Text: quote) .get() (err, res, body) -> try body = get_dom body catch err err = "Could not clean potty words." cb(body, err)
167567
# Description: # Allows Hubot to find an awesome Mitch Hedberg quotes # # Dependencies: # "htmlparser": "1.7.6" # "soupselect": "0.2.0" # "jsdom": "0.2.14" # "underscore": "1.3.3" # # Configuration: # None # # Commands: # hubot get mitch - This spits out one of the many awesome Mitch Hedberg quotes from wikiquote.org with filter # hubot get dirty mitch - This spits out one of the many awesome Mitch Hedberg quotes from wikiquote.org without potty mouth filter # # Author: # nickfloyd Select = require("soupselect").select HtmlParser = require "htmlparser" JsDom = require "jsdom" _ = require("underscore") StaticQuotes = [ "A severed foot is the ultimate stocking stuffer.", "I hope the next time I move I get a real easy phone number, something that's real easy to remember. Something like two two two two two two two. I would say \"Sweet.\" And then people would say, \"Mitch, how do I get a hold of you?\" I'd say, \"Just press two for a while and when I answer, you will know you have pressed two enough.", "My friend asked me if I wanted a frozen banana, I said \"No, but I want a regular banana later, so ... yeah\".", "On a traffic light green means 'go' and yellow means 'yield', but on a banana it's just the opposite. Green means 'hold on,' yellow means 'go ahead,' and red means, 'where did you get that banana ?'", "I'm against picketing, but I don't know how to show it.", "I think Bigfoot is blurry, that's the problem. It's not the photographer's fault. Bigfoot is blurry, and that's extra scary to me. There's a large, out-of-focus monster roaming the countryside. Run, he's fuzzy, get out of here.", "One time, this guy handed me a picture of him, he said,\"Here's a picture of me when I was younger.\" Every picture is of you when you were younger. ", "My fake plants died because I did not pretend to water them.", "I walked into Target, but I missed. I think the entrance to Target should have people splattered all around. And, when I finally get in, the guy says, \"Can I help you?\" \"Just practicing.\"", "When I was a boy, I laid in my twin-sized bed and wondered where my brother was.", "Is a hippopotamus a hippopotamus or just a really cool opotamus?", "If I had a dollar for every time I said that, I'd be making money in a very weird way.", "My belt holds up my pants and my pants have belt loops that hold up the belt. What's really goin on down there? Who is the real hero?", "I'm an ice sculptor - last night I made a cube.", "If you have dentures, don't use artificial sweetener, cause you'll get a fake cavity.", "I saw this dude, he was wearing a leather jacket, and at the same time he was eating a hamburger and drinking a glass of milk. I said to him \"Dude, you're a cow. The metamorphosis is complete. Don't fall asleep or I'll tip you over.\"", "A burrito is a sleeping bag for ground beef.", "Here's a thought for sweat shop owners: Air Conditioning. Problem solved.", "I saw a sheet lying on the floor, it must have been a ghost that had passed out... So I kicked it.", "The Kit-Kat candy bar has the name 'Kit-Kat' imprinted into the chocolate. That robs you of chocolate!"] module.exports = (robot) -> robot.respond /get( dirty)? mitch$/i, (msg) -> msg .http("http://en.wikiquote.org/wiki/<NAME>_<NAME>") .header("User-Agent: Mitchbot for Hubot (+https://github.com/github/hubot-scripts)") .get() (err, res, body) -> quotes = parse_html(body, "li") quote = get_quote msg, quotes get_quote = (msg, quotes) -> pottyParm = msg.match[1].replace /^\s+|\s+$/g, "" if msg.match[1] != undefined nodeChildren = _.flatten childern_of_type(quotes[Math.floor(Math.random() * quotes.length)]) quote = (textNode.data for textNode in nodeChildren).join '' if pottyParm == "dirty" msg.send quote else keep_it_clean msg, quote, (body, err) -> msg.send StaticQuotes[Math.floor(Math.random() * StaticQuotes.length)] if err #because potty word just sounds funny msg.send body.getElementsByTagName("CleanText")[0].firstChild.nodeValue.replace /(Explicit)+/g, "potty word" # Helpers parse_html = (html, selector) -> handler = new HtmlParser.DefaultHandler((() ->), ignoreWhitespace: true) parser = new HtmlParser.Parser handler parser.parseComplete html Select handler.dom, selector childern_of_type = (root) -> return [root] if root?.type is "text" if root?.children?.length > 0 return (childern_of_type(child) for child in root.children) get_dom = (xml) -> body = JsDom.jsdom(xml) throw Error("No XML data returned.") if body.getElementsByTagName("FilterReturn")[0].childNodes.length == 0 return body keep_it_clean = (msg, quote, cb) -> msg.http("http://wsf.cdyne.com/ProfanityWS/Profanity.asmx/SimpleProfanityFilter") .query(Text: quote) .get() (err, res, body) -> try body = get_dom body catch err err = "Could not clean potty words." cb(body, err)
true
# Description: # Allows Hubot to find an awesome Mitch Hedberg quotes # # Dependencies: # "htmlparser": "1.7.6" # "soupselect": "0.2.0" # "jsdom": "0.2.14" # "underscore": "1.3.3" # # Configuration: # None # # Commands: # hubot get mitch - This spits out one of the many awesome Mitch Hedberg quotes from wikiquote.org with filter # hubot get dirty mitch - This spits out one of the many awesome Mitch Hedberg quotes from wikiquote.org without potty mouth filter # # Author: # nickfloyd Select = require("soupselect").select HtmlParser = require "htmlparser" JsDom = require "jsdom" _ = require("underscore") StaticQuotes = [ "A severed foot is the ultimate stocking stuffer.", "I hope the next time I move I get a real easy phone number, something that's real easy to remember. Something like two two two two two two two. I would say \"Sweet.\" And then people would say, \"Mitch, how do I get a hold of you?\" I'd say, \"Just press two for a while and when I answer, you will know you have pressed two enough.", "My friend asked me if I wanted a frozen banana, I said \"No, but I want a regular banana later, so ... yeah\".", "On a traffic light green means 'go' and yellow means 'yield', but on a banana it's just the opposite. Green means 'hold on,' yellow means 'go ahead,' and red means, 'where did you get that banana ?'", "I'm against picketing, but I don't know how to show it.", "I think Bigfoot is blurry, that's the problem. It's not the photographer's fault. Bigfoot is blurry, and that's extra scary to me. There's a large, out-of-focus monster roaming the countryside. Run, he's fuzzy, get out of here.", "One time, this guy handed me a picture of him, he said,\"Here's a picture of me when I was younger.\" Every picture is of you when you were younger. ", "My fake plants died because I did not pretend to water them.", "I walked into Target, but I missed. I think the entrance to Target should have people splattered all around. And, when I finally get in, the guy says, \"Can I help you?\" \"Just practicing.\"", "When I was a boy, I laid in my twin-sized bed and wondered where my brother was.", "Is a hippopotamus a hippopotamus or just a really cool opotamus?", "If I had a dollar for every time I said that, I'd be making money in a very weird way.", "My belt holds up my pants and my pants have belt loops that hold up the belt. What's really goin on down there? Who is the real hero?", "I'm an ice sculptor - last night I made a cube.", "If you have dentures, don't use artificial sweetener, cause you'll get a fake cavity.", "I saw this dude, he was wearing a leather jacket, and at the same time he was eating a hamburger and drinking a glass of milk. I said to him \"Dude, you're a cow. The metamorphosis is complete. Don't fall asleep or I'll tip you over.\"", "A burrito is a sleeping bag for ground beef.", "Here's a thought for sweat shop owners: Air Conditioning. Problem solved.", "I saw a sheet lying on the floor, it must have been a ghost that had passed out... So I kicked it.", "The Kit-Kat candy bar has the name 'Kit-Kat' imprinted into the chocolate. That robs you of chocolate!"] module.exports = (robot) -> robot.respond /get( dirty)? mitch$/i, (msg) -> msg .http("http://en.wikiquote.org/wiki/PI:NAME:<NAME>END_PI_PI:NAME:<NAME>END_PI") .header("User-Agent: Mitchbot for Hubot (+https://github.com/github/hubot-scripts)") .get() (err, res, body) -> quotes = parse_html(body, "li") quote = get_quote msg, quotes get_quote = (msg, quotes) -> pottyParm = msg.match[1].replace /^\s+|\s+$/g, "" if msg.match[1] != undefined nodeChildren = _.flatten childern_of_type(quotes[Math.floor(Math.random() * quotes.length)]) quote = (textNode.data for textNode in nodeChildren).join '' if pottyParm == "dirty" msg.send quote else keep_it_clean msg, quote, (body, err) -> msg.send StaticQuotes[Math.floor(Math.random() * StaticQuotes.length)] if err #because potty word just sounds funny msg.send body.getElementsByTagName("CleanText")[0].firstChild.nodeValue.replace /(Explicit)+/g, "potty word" # Helpers parse_html = (html, selector) -> handler = new HtmlParser.DefaultHandler((() ->), ignoreWhitespace: true) parser = new HtmlParser.Parser handler parser.parseComplete html Select handler.dom, selector childern_of_type = (root) -> return [root] if root?.type is "text" if root?.children?.length > 0 return (childern_of_type(child) for child in root.children) get_dom = (xml) -> body = JsDom.jsdom(xml) throw Error("No XML data returned.") if body.getElementsByTagName("FilterReturn")[0].childNodes.length == 0 return body keep_it_clean = (msg, quote, cb) -> msg.http("http://wsf.cdyne.com/ProfanityWS/Profanity.asmx/SimpleProfanityFilter") .query(Text: quote) .get() (err, res, body) -> try body = get_dom body catch err err = "Could not clean potty words." cb(body, err)
[ { "context": "p800_38a__f_3_17 = (T,cb) ->\n key = Buffer.from \"603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4\", 'hex'\n iv = Buffer.from \"000102030405060708090", "end": 182, "score": 0.9996598362922668, "start": 118, "tag": "KEY", "value": "603deb1015ca71be2b73aef0857...
test/files/cfb.iced
samkenxstream/kbpgp
464
{encrypt,decrypt} = require '../../lib/openpgp/cfb' exports.nist_sp800_38a__f_3_17 = (T,cb) -> key = Buffer.from "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", 'hex' iv = Buffer.from "000102030405060708090a0b0c0d0e0f", "hex" pt_raw = [ "6bc1bee22e409f96e93d7e117393172a", "ae2d8a571e03ac9c9eb76fac45af8e51", "30c81c46a35ce411e5fbc1191a0a52ef", "f69f2445df4f9b17ad2b417be66c3710" ] ct_raw = [ "dc7e84bfda79164b7ecd8486985d3860", "39ffed143b28b1c832113c6331e5407b", "df10132415e54b92a13ed0a8267ae2f9", "75a385741ab9cef82031623d55b1e471" ] test = (T, n, pt, ct) -> plaintext = Buffer.concat(Buffer.from(p, 'hex') for p in pt) len = plaintext.length - n plaintext = plaintext[0...len] ciphertext = Buffer.concat(Buffer.from(c, 'hex') for c in ct) ciphertext = ciphertext[0...len] ct_ours = encrypt {key, plaintext, iv} T.equal ct_ours.toString(), ciphertext.toString(), "encryption produced expected result (trunc=#{n})" pt2 = decrypt { key, ciphertext, iv } T.equal pt2.toString(), plaintext.toString(), "decryption produced expected result (trunc=#{n})" # test all various truncations.... for i in [0...16] test T, i, pt_raw, ct_raw cb()
43131
{encrypt,decrypt} = require '../../lib/openpgp/cfb' exports.nist_sp800_38a__f_3_17 = (T,cb) -> key = Buffer.from "<KEY>", 'hex' iv = Buffer.from "000102030405060708090a0b0c0d0e0f", "hex" pt_raw = [ "6bc1bee22e409f96e93d7<KEY>1173931<KEY>a", "ae2d8a571e03ac9c9eb76fac45af8e51", "3<KEY>c<KEY>1c<KEY>6<KEY>3<KEY>ce<KEY>", "f<KEY>" ] ct_raw = [ "dc7e84bfda79164b7ecd8486985d3860", "<KEY>", "df<KEY>8<KEY>", "7<KEY>" ] test = (T, n, pt, ct) -> plaintext = Buffer.concat(Buffer.from(p, 'hex') for p in pt) len = plaintext.length - n plaintext = plaintext[0...len] ciphertext = Buffer.concat(Buffer.from(c, 'hex') for c in ct) ciphertext = ciphertext[0...len] ct_ours = encrypt {key, plaintext, iv} T.equal ct_ours.toString(), ciphertext.toString(), "encryption produced expected result (trunc=#{n})" pt2 = decrypt { key, ciphertext, iv } T.equal pt2.toString(), plaintext.toString(), "decryption produced expected result (trunc=#{n})" # test all various truncations.... for i in [0...16] test T, i, pt_raw, ct_raw cb()
true
{encrypt,decrypt} = require '../../lib/openpgp/cfb' exports.nist_sp800_38a__f_3_17 = (T,cb) -> key = Buffer.from "PI:KEY:<KEY>END_PI", 'hex' iv = Buffer.from "000102030405060708090a0b0c0d0e0f", "hex" pt_raw = [ "6bc1bee22e409f96e93d7PI:KEY:<KEY>END_PI1173931PI:KEY:<KEY>END_PIa", "ae2d8a571e03ac9c9eb76fac45af8e51", "3PI:KEY:<KEY>END_PIcPI:KEY:<KEY>END_PI1cPI:KEY:<KEY>END_PI6PI:KEY:<KEY>END_PI3PI:KEY:<KEY>END_PIcePI:KEY:<KEY>END_PI", "fPI:KEY:<KEY>END_PI" ] ct_raw = [ "dc7e84bfda79164b7ecd8486985d3860", "PI:KEY:<KEY>END_PI", "dfPI:KEY:<KEY>END_PI8PI:KEY:<KEY>END_PI", "7PI:KEY:<KEY>END_PI" ] test = (T, n, pt, ct) -> plaintext = Buffer.concat(Buffer.from(p, 'hex') for p in pt) len = plaintext.length - n plaintext = plaintext[0...len] ciphertext = Buffer.concat(Buffer.from(c, 'hex') for c in ct) ciphertext = ciphertext[0...len] ct_ours = encrypt {key, plaintext, iv} T.equal ct_ours.toString(), ciphertext.toString(), "encryption produced expected result (trunc=#{n})" pt2 = decrypt { key, ciphertext, iv } T.equal pt2.toString(), plaintext.toString(), "decryption produced expected result (trunc=#{n})" # test all various truncations.... for i in [0...16] test T, i, pt_raw, ct_raw cb()
[ { "context": "sloth me - Sends a sloth image URL\n#\n# Author:\n# NickPresta\n\nsloths = [\n 'http://i.imgur.com/p9HSmyR.jpg'\n ", "end": 177, "score": 0.9953927397727966, "start": 167, "tag": "NAME", "value": "NickPresta" } ]
src/scripts/sloth-me.coffee
contolini/hubot-scripts
1,450
# Description: # Sends a sloth image URL # # Dependencies: # None # # Configuration: # None # # Commands: # sloth me - Sends a sloth image URL # # Author: # NickPresta sloths = [ 'http://i.imgur.com/p9HSmyR.jpg' 'http://i.imgur.com/QLy8flr.jpg' 'http://i.imgur.com/7asAJqw.jpg' 'http://i.imgur.com/WHuyNUx.jpg' 'http://i.imgur.com/stZo0zl.png' 'http://i.imgur.com/bLJwgCN.jpg' 'http://i.imgur.com/7MgspTH.jpg' 'http://i.imgur.com/BqJpzvF.jpg' 'http://i.imgur.com/txjUeA1.jpg' 'http://i.imgur.com/cZ6GDFY.jpg' 'http://i.imgur.com/6oZxYI9.jpg' 'http://i.imgur.com/5OHdllr.jpg' 'http://i.imgur.com/M7q1qzi.png' 'http://i.imgur.com/FRrN5tX.jpg' 'http://i.imgur.com/og36bRg.jpg' 'http://i.imgur.com/uSg8rgi.png' 'http://i.imgur.com/MXZ9mFr.jpg' 'http://i.imgur.com/aztmlwT.jpg' 'http://i.imgur.com/lIG1itA.png' 'http://i.imgur.com/RRZyJYF.jpg' 'http://i.imgur.com/VGxvMur.png' 'http://i.imgur.com/egJKThb.jpg' 'http://i.imgur.com/imABby8.jpg' 'http://i.imgur.com/ySbRRiA.jpg' 'http://i.imgur.com/HJ5ixut.jpg' 'http://i.imgur.com/JoKTB9s.jpg' 'http://i.imgur.com/tm5XmVS.jpg' 'http://i.imgur.com/1iiahIU.jpg' 'http://i.imgur.com/KiXxNhN.jpg' 'http://i.imgur.com/QLXBeOX.jpg' 'http://i.imgur.com/epfD9ps.png' 'http://i.imgur.com/C975XnF.jpg' 'http://i.imgur.com/7rz0Bll.jpg' 'http://i.imgur.com/Mtl0pTt.jpg' 'http://i.imgur.com/tBxfiOo.gif' 'http://i.imgur.com/aiXPItB.gif' 'http://i.imgur.com/WKIYCXY.gif' 'http://i.imgur.com/PwOFcmM.gif' 'http://i.imgur.com/gGgVGEn.gif' 'http://i.imgur.com/NAJYZRJ.gif' 'http://i.imgur.com/QppoTRe.gif' 'http://i.imgur.com/DWoZS2y.gif' 'http://i.imgur.com/eafrx63.gif' ] module.exports = (robot) -> robot.hear /sloth me/i, (msg) -> msg.send msg.random sloths
101299
# Description: # Sends a sloth image URL # # Dependencies: # None # # Configuration: # None # # Commands: # sloth me - Sends a sloth image URL # # Author: # <NAME> sloths = [ 'http://i.imgur.com/p9HSmyR.jpg' 'http://i.imgur.com/QLy8flr.jpg' 'http://i.imgur.com/7asAJqw.jpg' 'http://i.imgur.com/WHuyNUx.jpg' 'http://i.imgur.com/stZo0zl.png' 'http://i.imgur.com/bLJwgCN.jpg' 'http://i.imgur.com/7MgspTH.jpg' 'http://i.imgur.com/BqJpzvF.jpg' 'http://i.imgur.com/txjUeA1.jpg' 'http://i.imgur.com/cZ6GDFY.jpg' 'http://i.imgur.com/6oZxYI9.jpg' 'http://i.imgur.com/5OHdllr.jpg' 'http://i.imgur.com/M7q1qzi.png' 'http://i.imgur.com/FRrN5tX.jpg' 'http://i.imgur.com/og36bRg.jpg' 'http://i.imgur.com/uSg8rgi.png' 'http://i.imgur.com/MXZ9mFr.jpg' 'http://i.imgur.com/aztmlwT.jpg' 'http://i.imgur.com/lIG1itA.png' 'http://i.imgur.com/RRZyJYF.jpg' 'http://i.imgur.com/VGxvMur.png' 'http://i.imgur.com/egJKThb.jpg' 'http://i.imgur.com/imABby8.jpg' 'http://i.imgur.com/ySbRRiA.jpg' 'http://i.imgur.com/HJ5ixut.jpg' 'http://i.imgur.com/JoKTB9s.jpg' 'http://i.imgur.com/tm5XmVS.jpg' 'http://i.imgur.com/1iiahIU.jpg' 'http://i.imgur.com/KiXxNhN.jpg' 'http://i.imgur.com/QLXBeOX.jpg' 'http://i.imgur.com/epfD9ps.png' 'http://i.imgur.com/C975XnF.jpg' 'http://i.imgur.com/7rz0Bll.jpg' 'http://i.imgur.com/Mtl0pTt.jpg' 'http://i.imgur.com/tBxfiOo.gif' 'http://i.imgur.com/aiXPItB.gif' 'http://i.imgur.com/WKIYCXY.gif' 'http://i.imgur.com/PwOFcmM.gif' 'http://i.imgur.com/gGgVGEn.gif' 'http://i.imgur.com/NAJYZRJ.gif' 'http://i.imgur.com/QppoTRe.gif' 'http://i.imgur.com/DWoZS2y.gif' 'http://i.imgur.com/eafrx63.gif' ] module.exports = (robot) -> robot.hear /sloth me/i, (msg) -> msg.send msg.random sloths
true
# Description: # Sends a sloth image URL # # Dependencies: # None # # Configuration: # None # # Commands: # sloth me - Sends a sloth image URL # # Author: # PI:NAME:<NAME>END_PI sloths = [ 'http://i.imgur.com/p9HSmyR.jpg' 'http://i.imgur.com/QLy8flr.jpg' 'http://i.imgur.com/7asAJqw.jpg' 'http://i.imgur.com/WHuyNUx.jpg' 'http://i.imgur.com/stZo0zl.png' 'http://i.imgur.com/bLJwgCN.jpg' 'http://i.imgur.com/7MgspTH.jpg' 'http://i.imgur.com/BqJpzvF.jpg' 'http://i.imgur.com/txjUeA1.jpg' 'http://i.imgur.com/cZ6GDFY.jpg' 'http://i.imgur.com/6oZxYI9.jpg' 'http://i.imgur.com/5OHdllr.jpg' 'http://i.imgur.com/M7q1qzi.png' 'http://i.imgur.com/FRrN5tX.jpg' 'http://i.imgur.com/og36bRg.jpg' 'http://i.imgur.com/uSg8rgi.png' 'http://i.imgur.com/MXZ9mFr.jpg' 'http://i.imgur.com/aztmlwT.jpg' 'http://i.imgur.com/lIG1itA.png' 'http://i.imgur.com/RRZyJYF.jpg' 'http://i.imgur.com/VGxvMur.png' 'http://i.imgur.com/egJKThb.jpg' 'http://i.imgur.com/imABby8.jpg' 'http://i.imgur.com/ySbRRiA.jpg' 'http://i.imgur.com/HJ5ixut.jpg' 'http://i.imgur.com/JoKTB9s.jpg' 'http://i.imgur.com/tm5XmVS.jpg' 'http://i.imgur.com/1iiahIU.jpg' 'http://i.imgur.com/KiXxNhN.jpg' 'http://i.imgur.com/QLXBeOX.jpg' 'http://i.imgur.com/epfD9ps.png' 'http://i.imgur.com/C975XnF.jpg' 'http://i.imgur.com/7rz0Bll.jpg' 'http://i.imgur.com/Mtl0pTt.jpg' 'http://i.imgur.com/tBxfiOo.gif' 'http://i.imgur.com/aiXPItB.gif' 'http://i.imgur.com/WKIYCXY.gif' 'http://i.imgur.com/PwOFcmM.gif' 'http://i.imgur.com/gGgVGEn.gif' 'http://i.imgur.com/NAJYZRJ.gif' 'http://i.imgur.com/QppoTRe.gif' 'http://i.imgur.com/DWoZS2y.gif' 'http://i.imgur.com/eafrx63.gif' ] module.exports = (robot) -> robot.hear /sloth me/i, (msg) -> msg.send msg.random sloths
[ { "context": "cape(body.email).trim().toLowerCase()\n\t\tpassword = body.password\n\t\tusername = email.match(/^[^@]*/)\n\t\tif @hasZeroL", "end": 1093, "score": 0.9959627985954285, "start": 1080, "tag": "PASSWORD", "value": "body.password" }, { "context": "ler.registerNewUser {\n\t\...
app/coffee/Features/User/UserRegistrationHandler.coffee
dtu-compute/web-sharelatex
0
sanitize = require('sanitizer') User = require("../../models/User").User UserCreator = require("./UserCreator") AuthenticationManager = require("../Authentication/AuthenticationManager") NewsLetterManager = require("../Newsletter/NewsletterManager") async = require("async") logger = require("logger-sharelatex") crypto = require("crypto") EmailHandler = require("../Email/EmailHandler") OneTimeTokenHandler = require "../Security/OneTimeTokenHandler" Analytics = require "../Analytics/AnalyticsManager" settings = require "settings-sharelatex" module.exports = UserRegistrationHandler = validateEmail : (email) -> re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\ ".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA -Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ return re.test(email) hasZeroLengths : (props) -> hasZeroLength = false props.forEach (prop) -> if prop.length == 0 hasZeroLength = true return hasZeroLength _registrationRequestIsValid : (body, callback)-> email = sanitize.escape(body.email).trim().toLowerCase() password = body.password username = email.match(/^[^@]*/) if @hasZeroLengths([password, email]) return false else if !@validateEmail(email) return false else return true _createNewUserIfRequired: (user, userDetails, callback)-> if !user? userDetails.holdingAccount = false UserCreator.createNewUser {holdingAccount:false, email:userDetails.email, first_name:userDetails.first_name, last_name:userDetails.last_name}, callback else callback null, user registerNewUser: (userDetails, callback)-> self = @ requestIsValid = @_registrationRequestIsValid userDetails if !requestIsValid return callback(new Error("request is not valid")) userDetails.email = userDetails.email?.trim()?.toLowerCase() User.findOne email:userDetails.email, (err, user)-> if err? return callback err if user?.holdingAccount == false return callback(new Error("EmailAlreadyRegistered"), user) self._createNewUserIfRequired user, userDetails, (err, user)-> if err? return callback(err) async.series [ (cb)-> User.update {_id: user._id}, {"$set":{holdingAccount:false}}, cb (cb)-> AuthenticationManager.setUserPassword user._id, userDetails.password, cb (cb)-> NewsLetterManager.subscribe user, -> cb() #this can be slow, just fire it off ], (err)-> logger.log user: user, "registered" Analytics.recordEvent user._id, "user-registered" callback(err, user) registerNewUserAndSendActivationEmail: (email, callback = (error, user, setNewPasswordUrl) ->) -> logger.log {email}, "registering new user" UserRegistrationHandler.registerNewUser { email: email password: crypto.randomBytes(32).toString("hex") }, (err, user)-> if err? and err?.message != "EmailAlreadyRegistered" return callback(err) if err?.message == "EmailAlreadyRegistered" logger.log {email}, "user already exists, resending welcome email" ONE_WEEK = 7 * 24 * 60 * 60 # seconds OneTimeTokenHandler.getNewToken user._id, { expiresIn: ONE_WEEK }, (err, token)-> return callback(err) if err? setNewPasswordUrl = "#{settings.siteUrl}/user/activate?token=#{token}&user_id=#{user._id}" EmailHandler.sendEmail "registered", { to: user.email setNewPasswordUrl: setNewPasswordUrl }, () -> callback null, user, setNewPasswordUrl
149297
sanitize = require('sanitizer') User = require("../../models/User").User UserCreator = require("./UserCreator") AuthenticationManager = require("../Authentication/AuthenticationManager") NewsLetterManager = require("../Newsletter/NewsletterManager") async = require("async") logger = require("logger-sharelatex") crypto = require("crypto") EmailHandler = require("../Email/EmailHandler") OneTimeTokenHandler = require "../Security/OneTimeTokenHandler" Analytics = require "../Analytics/AnalyticsManager" settings = require "settings-sharelatex" module.exports = UserRegistrationHandler = validateEmail : (email) -> re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\ ".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA -Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ return re.test(email) hasZeroLengths : (props) -> hasZeroLength = false props.forEach (prop) -> if prop.length == 0 hasZeroLength = true return hasZeroLength _registrationRequestIsValid : (body, callback)-> email = sanitize.escape(body.email).trim().toLowerCase() password = <PASSWORD> username = email.match(/^[^@]*/) if @hasZeroLengths([password, email]) return false else if !@validateEmail(email) return false else return true _createNewUserIfRequired: (user, userDetails, callback)-> if !user? userDetails.holdingAccount = false UserCreator.createNewUser {holdingAccount:false, email:userDetails.email, first_name:userDetails.first_name, last_name:userDetails.last_name}, callback else callback null, user registerNewUser: (userDetails, callback)-> self = @ requestIsValid = @_registrationRequestIsValid userDetails if !requestIsValid return callback(new Error("request is not valid")) userDetails.email = userDetails.email?.trim()?.toLowerCase() User.findOne email:userDetails.email, (err, user)-> if err? return callback err if user?.holdingAccount == false return callback(new Error("EmailAlreadyRegistered"), user) self._createNewUserIfRequired user, userDetails, (err, user)-> if err? return callback(err) async.series [ (cb)-> User.update {_id: user._id}, {"$set":{holdingAccount:false}}, cb (cb)-> AuthenticationManager.setUserPassword user._id, userDetails.password, cb (cb)-> NewsLetterManager.subscribe user, -> cb() #this can be slow, just fire it off ], (err)-> logger.log user: user, "registered" Analytics.recordEvent user._id, "user-registered" callback(err, user) registerNewUserAndSendActivationEmail: (email, callback = (error, user, setNewPasswordUrl) ->) -> logger.log {email}, "registering new user" UserRegistrationHandler.registerNewUser { email: email password: <PASSWORD>("hex") }, (err, user)-> if err? and err?.message != "EmailAlreadyRegistered" return callback(err) if err?.message == "EmailAlreadyRegistered" logger.log {email}, "user already exists, resending welcome email" ONE_WEEK = 7 * 24 * 60 * 60 # seconds OneTimeTokenHandler.getNewToken user._id, { expiresIn: ONE_WEEK }, (err, token)-> return callback(err) if err? setNewPasswordUrl = "#{settings.siteUrl}/user/activate?token=#{token}&user_id=#{user._id}" EmailHandler.sendEmail "registered", { to: user.email setNewPasswordUrl: setNewPasswordUrl }, () -> callback null, user, setNewPasswordUrl
true
sanitize = require('sanitizer') User = require("../../models/User").User UserCreator = require("./UserCreator") AuthenticationManager = require("../Authentication/AuthenticationManager") NewsLetterManager = require("../Newsletter/NewsletterManager") async = require("async") logger = require("logger-sharelatex") crypto = require("crypto") EmailHandler = require("../Email/EmailHandler") OneTimeTokenHandler = require "../Security/OneTimeTokenHandler" Analytics = require "../Analytics/AnalyticsManager" settings = require "settings-sharelatex" module.exports = UserRegistrationHandler = validateEmail : (email) -> re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\ ".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA -Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ return re.test(email) hasZeroLengths : (props) -> hasZeroLength = false props.forEach (prop) -> if prop.length == 0 hasZeroLength = true return hasZeroLength _registrationRequestIsValid : (body, callback)-> email = sanitize.escape(body.email).trim().toLowerCase() password = PI:PASSWORD:<PASSWORD>END_PI username = email.match(/^[^@]*/) if @hasZeroLengths([password, email]) return false else if !@validateEmail(email) return false else return true _createNewUserIfRequired: (user, userDetails, callback)-> if !user? userDetails.holdingAccount = false UserCreator.createNewUser {holdingAccount:false, email:userDetails.email, first_name:userDetails.first_name, last_name:userDetails.last_name}, callback else callback null, user registerNewUser: (userDetails, callback)-> self = @ requestIsValid = @_registrationRequestIsValid userDetails if !requestIsValid return callback(new Error("request is not valid")) userDetails.email = userDetails.email?.trim()?.toLowerCase() User.findOne email:userDetails.email, (err, user)-> if err? return callback err if user?.holdingAccount == false return callback(new Error("EmailAlreadyRegistered"), user) self._createNewUserIfRequired user, userDetails, (err, user)-> if err? return callback(err) async.series [ (cb)-> User.update {_id: user._id}, {"$set":{holdingAccount:false}}, cb (cb)-> AuthenticationManager.setUserPassword user._id, userDetails.password, cb (cb)-> NewsLetterManager.subscribe user, -> cb() #this can be slow, just fire it off ], (err)-> logger.log user: user, "registered" Analytics.recordEvent user._id, "user-registered" callback(err, user) registerNewUserAndSendActivationEmail: (email, callback = (error, user, setNewPasswordUrl) ->) -> logger.log {email}, "registering new user" UserRegistrationHandler.registerNewUser { email: email password: PI:PASSWORD:<PASSWORD>END_PI("hex") }, (err, user)-> if err? and err?.message != "EmailAlreadyRegistered" return callback(err) if err?.message == "EmailAlreadyRegistered" logger.log {email}, "user already exists, resending welcome email" ONE_WEEK = 7 * 24 * 60 * 60 # seconds OneTimeTokenHandler.getNewToken user._id, { expiresIn: ONE_WEEK }, (err, token)-> return callback(err) if err? setNewPasswordUrl = "#{settings.siteUrl}/user/activate?token=#{token}&user_id=#{user._id}" EmailHandler.sendEmail "registered", { to: user.email setNewPasswordUrl: setNewPasswordUrl }, () -> callback null, user, setNewPasswordUrl
[ { "context": "###\n\tCopyright 2013 David Pearson.\n\tBSD License.\n###\n\ngelim=require \"./gelim\"\nexpor", "end": 33, "score": 0.999845564365387, "start": 20, "tag": "NAME", "value": "David Pearson" } ]
src/index.coffee
dpearson/linalgebra
1
### Copyright 2013 David Pearson. BSD License. ### gelim=require "./gelim" exports.gelim=gelim.gelim exports.gjelim=gelim.gjelim solve=require "./solve" exports.backsub=solve.backsub exports.solve=solve.solve ops=require "./matrix" exports.add=ops.add exports.multiplyScalar=ops.multiplyScalar exports.multiply=ops.multiply exports.trace=ops.trace exports.transpose=ops.transpose exports.equals=ops.equals
36189
### Copyright 2013 <NAME>. BSD License. ### gelim=require "./gelim" exports.gelim=gelim.gelim exports.gjelim=gelim.gjelim solve=require "./solve" exports.backsub=solve.backsub exports.solve=solve.solve ops=require "./matrix" exports.add=ops.add exports.multiplyScalar=ops.multiplyScalar exports.multiply=ops.multiply exports.trace=ops.trace exports.transpose=ops.transpose exports.equals=ops.equals
true
### Copyright 2013 PI:NAME:<NAME>END_PI. BSD License. ### gelim=require "./gelim" exports.gelim=gelim.gelim exports.gjelim=gelim.gjelim solve=require "./solve" exports.backsub=solve.backsub exports.solve=solve.solve ops=require "./matrix" exports.add=ops.add exports.multiplyScalar=ops.multiplyScalar exports.multiply=ops.multiply exports.trace=ops.trace exports.transpose=ops.transpose exports.equals=ops.equals
[ { "context": " await @krb5.addprinc\n principal: \"nikita@#{krb5.realm}\"\n password: 'nikita123-1'\n {$sta", "end": 1078, "score": 0.8588367104530334, "start": 1059, "tag": "EMAIL", "value": "nikita@#{krb5.realm" }, { "context": "ipal: \"nikita@#{krb5....
packages/krb5/test/ktutil/add.coffee
shivaylamba/meilisearch-gatsby-plugin-guide
31
nikita = require '@nikitajs/core/lib' {tags, config, krb5} = require '../test' they = require('mocha-they')(config) return unless tags.krb5_ktadd describe 'krb5.kutil.add', -> describe 'schema', -> it 'principal, keyta and password must be provided', -> nikita krb5: admin: krb5 , -> @krb5.ktutil.add {} .should.be.rejectedWith code: 'NIKITA_SCHEMA_VALIDATION_CONFIG' message: [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'multiple errors were found in the configuration of action `krb5.ktutil.add`:' '#/required config must have required property \'keytab\';' '#/required config must have required property \'password\';' '#/required config must have required property \'principal\'.' ].join ' ' describe 'action', -> they 'create a new keytab', ({ssh}) -> nikita $ssh: ssh krb5: admin: krb5 $tmpdir: true , ({metadata: {tmpdir}}) -> await @krb5.addprinc principal: "nikita@#{krb5.realm}" password: 'nikita123-1' {$status} = await @krb5.ktutil.add principal: "nikita@#{krb5.realm}" keytab: "#{tmpdir}/nikita.keytab" password: 'nikita123-1' $status.should.be.true() {$status} = await @krb5.ktutil.add principal: "nikita@#{krb5.realm}" keytab: "#{tmpdir}/nikita.keytab" password: 'nikita123-1' $status.should.be.false() they 'detect kvno', ({ssh}) -> nikita $ssh: ssh krb5: admin: krb5 $tmpdir: true , ({metadata: {tmpdir}}) -> await @krb5.addprinc principal: "nikita@#{krb5.realm}" password: 'nikita123-1' await @krb5.ktutil.add principal: "nikita@#{krb5.realm}" keytab: "#{tmpdir}/nikita_1.keytab" password: 'nikita123-1' await @krb5.execute command: """ change_password -pw nikita123-2 nikita@#{krb5.realm} """ {$status} = await @krb5.ktutil.add principal: "nikita@#{krb5.realm}" keytab: "#{tmpdir}/nikita_1.keytab" password: 'nikita123-2' $status.should.be.true() {$status} = await @krb5.ktutil.add principal: "nikita@#{krb5.realm}" keytab: "#{tmpdir}/nikita_1.keytab" password: 'nikita123-2' $status.should.be.false() they 'change permission', ({ssh}) -> nikita $ssh: ssh krb5: admin: krb5 $tmpdir: true , ({metadata: {tmpdir}}) -> await @krb5.addprinc principal: "nikita@#{krb5.realm}" password: 'nikita123-1' await @krb5.ktutil.add principal: "nikita@#{krb5.realm}" keytab: "#{tmpdir}/nikita_1.keytab" password: 'nikita123-1' mode: 0o0755 {$status} = await @krb5.ktutil.add principal: "nikita@#{krb5.realm}" keytab: "#{tmpdir}/nikita_1.keytab" password: 'nikita123-1' mode: 0o0707 $status.should.be.true()
208523
nikita = require '@nikitajs/core/lib' {tags, config, krb5} = require '../test' they = require('mocha-they')(config) return unless tags.krb5_ktadd describe 'krb5.kutil.add', -> describe 'schema', -> it 'principal, keyta and password must be provided', -> nikita krb5: admin: krb5 , -> @krb5.ktutil.add {} .should.be.rejectedWith code: 'NIKITA_SCHEMA_VALIDATION_CONFIG' message: [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'multiple errors were found in the configuration of action `krb5.ktutil.add`:' '#/required config must have required property \'keytab\';' '#/required config must have required property \'password\';' '#/required config must have required property \'principal\'.' ].join ' ' describe 'action', -> they 'create a new keytab', ({ssh}) -> nikita $ssh: ssh krb5: admin: krb5 $tmpdir: true , ({metadata: {tmpdir}}) -> await @krb5.addprinc principal: "<EMAIL>}" password: '<PASSWORD>' {$status} = await @krb5.ktutil.add principal: "<EMAIL>@#{k<EMAIL>}" keytab: "#{tmpdir}/nikita.keytab" password: '<PASSWORD>' $status.should.be.true() {$status} = await @krb5.ktutil.add principal: "<EMAIL>}" keytab: "#{tmpdir}/nikita.keytab" password: '<PASSWORD>' $status.should.be.false() they 'detect kvno', ({ssh}) -> nikita $ssh: ssh krb5: admin: krb5 $tmpdir: true , ({metadata: {tmpdir}}) -> await @krb5.addprinc principal: "<EMAIL>@#{k<EMAIL>}" password: '<EMAIL>123-1' await @krb5.ktutil.add principal: "nik<EMAIL>@#{krb5.realm}" keytab: "#{tmpdir}/nikita_1.keytab" password: '<PASSWORD>' await @krb5.execute command: """ change_password -pw <PASSWORD>-2 nikita@#{krb5.realm} """ {$status} = await @krb5.ktutil.add principal: "nik<EMAIL>@#{krb5.realm}" keytab: "#{tmpdir}/nikita_1.keytab" password: '<PASSWORD>' $status.should.be.true() {$status} = await @krb5.ktutil.add principal: "nik<EMAIL>@#{krb5.realm}" keytab: "#{tmpdir}/nikita_1.keytab" password: '<PASSWORD>' $status.should.be.false() they 'change permission', ({ssh}) -> nikita $ssh: ssh krb5: admin: krb5 $tmpdir: true , ({metadata: {tmpdir}}) -> await @krb5.addprinc principal: "nik<EMAIL>@#{k<EMAIL>}" password: '<PASSWORD>' await @krb5.ktutil.add principal: "nik<EMAIL>@#{krb<EMAIL>}" keytab: "#{tmpdir}/nikita_1.keytab" password: '<PASSWORD>' mode: 0o0755 {$status} = await @krb5.ktutil.add principal: "nik<EMAIL>@#{k<EMAIL>}" keytab: "#{tmpdir}/nikita_1.keytab" password: '<PASSWORD>' mode: 0o0707 $status.should.be.true()
true
nikita = require '@nikitajs/core/lib' {tags, config, krb5} = require '../test' they = require('mocha-they')(config) return unless tags.krb5_ktadd describe 'krb5.kutil.add', -> describe 'schema', -> it 'principal, keyta and password must be provided', -> nikita krb5: admin: krb5 , -> @krb5.ktutil.add {} .should.be.rejectedWith code: 'NIKITA_SCHEMA_VALIDATION_CONFIG' message: [ 'NIKITA_SCHEMA_VALIDATION_CONFIG:' 'multiple errors were found in the configuration of action `krb5.ktutil.add`:' '#/required config must have required property \'keytab\';' '#/required config must have required property \'password\';' '#/required config must have required property \'principal\'.' ].join ' ' describe 'action', -> they 'create a new keytab', ({ssh}) -> nikita $ssh: ssh krb5: admin: krb5 $tmpdir: true , ({metadata: {tmpdir}}) -> await @krb5.addprinc principal: "PI:EMAIL:<EMAIL>END_PI}" password: 'PI:PASSWORD:<PASSWORD>END_PI' {$status} = await @krb5.ktutil.add principal: "PI:EMAIL:<EMAIL>END_PI@#{kPI:EMAIL:<EMAIL>END_PI}" keytab: "#{tmpdir}/nikita.keytab" password: 'PI:PASSWORD:<PASSWORD>END_PI' $status.should.be.true() {$status} = await @krb5.ktutil.add principal: "PI:EMAIL:<EMAIL>END_PI}" keytab: "#{tmpdir}/nikita.keytab" password: 'PI:PASSWORD:<PASSWORD>END_PI' $status.should.be.false() they 'detect kvno', ({ssh}) -> nikita $ssh: ssh krb5: admin: krb5 $tmpdir: true , ({metadata: {tmpdir}}) -> await @krb5.addprinc principal: "PI:EMAIL:<EMAIL>END_PI@#{kPI:EMAIL:<EMAIL>END_PI}" password: 'PI:PASSWORD:<EMAIL>END_PI123-1' await @krb5.ktutil.add principal: "nikPI:EMAIL:<EMAIL>END_PI@#{krb5.realm}" keytab: "#{tmpdir}/nikita_1.keytab" password: 'PI:PASSWORD:<PASSWORD>END_PI' await @krb5.execute command: """ change_password -pw PI:PASSWORD:<PASSWORD>END_PI-2 nikita@#{krb5.realm} """ {$status} = await @krb5.ktutil.add principal: "nikPI:EMAIL:<EMAIL>END_PI@#{krb5.realm}" keytab: "#{tmpdir}/nikita_1.keytab" password: 'PI:PASSWORD:<PASSWORD>END_PI' $status.should.be.true() {$status} = await @krb5.ktutil.add principal: "nikPI:EMAIL:<EMAIL>END_PI@#{krb5.realm}" keytab: "#{tmpdir}/nikita_1.keytab" password: 'PI:PASSWORD:<PASSWORD>END_PI' $status.should.be.false() they 'change permission', ({ssh}) -> nikita $ssh: ssh krb5: admin: krb5 $tmpdir: true , ({metadata: {tmpdir}}) -> await @krb5.addprinc principal: "nikPI:EMAIL:<EMAIL>END_PI@#{kPI:EMAIL:<EMAIL>END_PI}" password: 'PI:PASSWORD:<PASSWORD>END_PI' await @krb5.ktutil.add principal: "nikPI:EMAIL:<EMAIL>END_PI@#{krbPI:EMAIL:<EMAIL>END_PI}" keytab: "#{tmpdir}/nikita_1.keytab" password: 'PI:PASSWORD:<PASSWORD>END_PI' mode: 0o0755 {$status} = await @krb5.ktutil.add principal: "nikPI:EMAIL:<EMAIL>END_PI@#{kPI:EMAIL:<EMAIL>END_PI}" keytab: "#{tmpdir}/nikita_1.keytab" password: 'PI:PASSWORD:<PASSWORD>END_PI' mode: 0o0707 $status.should.be.true()
[ { "context": "Check.js 0.2.0 (Beta)\n# CommonJS module \n# @author tommcgurl ( Tom McGurl ) \ncheck = \n\t# Return an object \n\t# ", "end": 62, "score": 0.9995367527008057, "start": 53, "tag": "USERNAME", "value": "tommcgurl" }, { "context": ".0 (Beta)\n# CommonJS module \n# @author...
check.coffee
tommcgurl/check
0
# Check.js 0.2.0 (Beta) # CommonJS module # @author tommcgurl ( Tom McGurl ) check = # Return an object # @param {Object} The object to attempt accessing properties on # @param {Splat: String} n number of strings, each once representing # a property to access on the parent # @param a fallback value to be returned if the object isn't valid # @return Object or fallback or defaultFallback useWithFallback: (obj , suspects..., fallback)-> # return if the first argument isn't an object return fallback if typeof obj != 'object' for suspect in suspects return fallback unless typeof suspect == 'string' && obj[suspect]? obj = obj[suspect] return obj # Return an object # @param {Object} The object to attempt accessing properties on # @param {Splat: String} n number of strings, each once representing # a property to access on the parent # @return Object or defaultFallback use: (obj, suspects...)-> # Call the function with '...' so it passes the splat rather # than the an array return @useWithFallback(obj,suspects..., @defaultFallback) # Return an object # @param {Object} The object to attempt accessing properties on # @param {Splat: String} n number of strings, each once representing # a property to access on the parent # @return {Boolean} true if object exists false if not check: (obj, suspects...)-> return !!@useWithFallback(obj, suspects..., @defaultFallback) # Sets the default fallback for the check object # @param Fallback value to be set setDefaultFallback: (fallback)-> @defaultFallback = fallback defaultFallback: false #export as CJS module if module?.exports? module.exports = check else return check
111731
# Check.js 0.2.0 (Beta) # CommonJS module # @author tommcgurl ( <NAME> ) check = # Return an object # @param {Object} The object to attempt accessing properties on # @param {Splat: String} n number of strings, each once representing # a property to access on the parent # @param a fallback value to be returned if the object isn't valid # @return Object or fallback or defaultFallback useWithFallback: (obj , suspects..., fallback)-> # return if the first argument isn't an object return fallback if typeof obj != 'object' for suspect in suspects return fallback unless typeof suspect == 'string' && obj[suspect]? obj = obj[suspect] return obj # Return an object # @param {Object} The object to attempt accessing properties on # @param {Splat: String} n number of strings, each once representing # a property to access on the parent # @return Object or defaultFallback use: (obj, suspects...)-> # Call the function with '...' so it passes the splat rather # than the an array return @useWithFallback(obj,suspects..., @defaultFallback) # Return an object # @param {Object} The object to attempt accessing properties on # @param {Splat: String} n number of strings, each once representing # a property to access on the parent # @return {Boolean} true if object exists false if not check: (obj, suspects...)-> return !!@useWithFallback(obj, suspects..., @defaultFallback) # Sets the default fallback for the check object # @param Fallback value to be set setDefaultFallback: (fallback)-> @defaultFallback = fallback defaultFallback: false #export as CJS module if module?.exports? module.exports = check else return check
true
# Check.js 0.2.0 (Beta) # CommonJS module # @author tommcgurl ( PI:NAME:<NAME>END_PI ) check = # Return an object # @param {Object} The object to attempt accessing properties on # @param {Splat: String} n number of strings, each once representing # a property to access on the parent # @param a fallback value to be returned if the object isn't valid # @return Object or fallback or defaultFallback useWithFallback: (obj , suspects..., fallback)-> # return if the first argument isn't an object return fallback if typeof obj != 'object' for suspect in suspects return fallback unless typeof suspect == 'string' && obj[suspect]? obj = obj[suspect] return obj # Return an object # @param {Object} The object to attempt accessing properties on # @param {Splat: String} n number of strings, each once representing # a property to access on the parent # @return Object or defaultFallback use: (obj, suspects...)-> # Call the function with '...' so it passes the splat rather # than the an array return @useWithFallback(obj,suspects..., @defaultFallback) # Return an object # @param {Object} The object to attempt accessing properties on # @param {Splat: String} n number of strings, each once representing # a property to access on the parent # @return {Boolean} true if object exists false if not check: (obj, suspects...)-> return !!@useWithFallback(obj, suspects..., @defaultFallback) # Sets the default fallback for the check object # @param Fallback value to be set setDefaultFallback: (fallback)-> @defaultFallback = fallback defaultFallback: false #export as CJS module if module?.exports? module.exports = check else return check
[ { "context": "unt.validate\n email: \"invalidMail@\"\n password: \"Short\"\n firstName: \"John\"\n lastName: null\n", "end": 242, "score": 0.9994170665740967, "start": 237, "tag": "PASSWORD", "value": "Short" }, { "context": " \"invalidMail@\"\n password: \"Short\"\n firstName:...
example/validationExample.coffee
dbartholomae/node-validation-codes
0
requirejs = require 'requirejs' requirejs.config baseUrl: '../' account = requirejs 'example/validators/account' # Will write ['EmailNotAnEmail', 'PasswordTooShort'] console.log account.validate email: "invalidMail@" password: "Short" firstName: "John" lastName: null
190989
requirejs = require 'requirejs' requirejs.config baseUrl: '../' account = requirejs 'example/validators/account' # Will write ['EmailNotAnEmail', 'PasswordTooShort'] console.log account.validate email: "invalidMail@" password: "<PASSWORD>" firstName: "<NAME>" lastName: null
true
requirejs = require 'requirejs' requirejs.config baseUrl: '../' account = requirejs 'example/validators/account' # Will write ['EmailNotAnEmail', 'PasswordTooShort'] console.log account.validate email: "invalidMail@" password: "PI:PASSWORD:<PASSWORD>END_PI" firstName: "PI:NAME:<NAME>END_PI" lastName: null
[ { "context": "r key, value of sample.counters\n nice_key = I18n.t 'navigator', key\n\n if your_classificatio", "end": 1280, "score": 0.47360900044441223, "start": 1279, "tag": "KEY", "value": "1" }, { "context": "key, value of sample.counters\n nice_key = I18n.t 'navig...
interactive/app/controllers/interactive/my_galaxies.coffee
murraycu/Galaxy-Zoo
16
Spine = require('spine') Dialog = require 'lib/dialog' User = require 'zooniverse/lib/models/user' SubjectViewer = require 'ubret/lib/controllers/SubjectViewer' BaseController = require 'ubret/lib/controllers/BaseController' InteractiveSubject = require 'ubret/lib/models/InteractiveSubject' class MyGalaxies extends Spine.Controller events: 'click .galaxy': 'popupViewer' constructor: -> super @headingText = $('#heading_text') @action_title = "<h2>#{ I18n.t('navigator.my_galaxies') }</h2>" User.bind 'sign-in', => if User.current?.user_group_id InteractiveSubject.fetch({limit: 10, user: true}).onSuccess => @samples = InteractiveSubject.lastFetch render: => if User.current.user_group_id fetcher = InteractiveSubject.fetch({limit: 10, user: true}) fetcher.onSuccess => @samples = InteractiveSubject.lastFetch @html require('views/interactive/my_galaxies')(@) for sample in @samples @generateChart sample @headingText.html @action_title $('[data-link="my_galaxies"]').addClass 'pressed' formatData: (sample) -> feature_counts = [] nice_key = '' your_classification = sample.classification for key, value of sample.counters nice_key = I18n.t 'navigator', key if your_classification == key selected = true else selected = false feature_counts.push { 'key': key, 'label': nice_key, 'value': value, 'selected': selected } feature_counts generateChart: (sample) -> counts = @formatData sample data = { key: 'Galaxy Features', values: counts } chart = d3.select('[data-id="' + sample.zooniverse_id+ '"] svg') .append('g') .attr('width', 265) .attr('height', 100) x = d3.scale.linear() .domain([0, d3.max(data.values, (d) -> d.value)]) .range([1, 120]) color = d3.scale.ordinal() .range(['#1e7797', '#ff9c00']) chart.selectAll('rect') .data(data.values) .enter().append('rect') .attr('y', ((d,i) -> i * 22)) .attr('x', 85) .attr('height', 20) .style('fill', ((d, i) -> if d.selected '#ff9c00' else '#1e7797' )) .on("mouseover", ((d) -> d3.select(@).classed('hovered', true) )) .on("mouseout", ((d) -> d3.select(@).classed('hovered', false) )) .transition().duration(500) .attr('width', ((d) -> x d.value)) chart.selectAll('text.label') .data(data.values).enter() .append('text') .attr('class','label') .attr('y', ((d,i) -> i * 22)) .attr('x', 80) .attr('dy', '1.3em') .attr('text-anchor', 'end') .text((d, i) -> d.label) chart.selectAll('text.value') .data(data.values).enter() .append('text') .attr('class','value') .attr('y', ((d,i) -> i * 22)) .attr('x', ((d) -> x d.value)) .attr('dx', 89) .attr('dy', '1.25em') .text((d) -> d.value) popupViewer: (e) => galaxy_id = $(e.currentTarget).data('id') data = [] subject = _.find @samples, (sample) => sample.zooniverse_id == galaxy_id data.push subject d = new Dialog { template: 'views/interactive/dialog', closeButton: true, quickHide: true } d.show() subject_viewer = new SubjectViewer({el: '.subject-viewer'}) subject_viewer.receiveData data module.exports = MyGalaxies
98560
Spine = require('spine') Dialog = require 'lib/dialog' User = require 'zooniverse/lib/models/user' SubjectViewer = require 'ubret/lib/controllers/SubjectViewer' BaseController = require 'ubret/lib/controllers/BaseController' InteractiveSubject = require 'ubret/lib/models/InteractiveSubject' class MyGalaxies extends Spine.Controller events: 'click .galaxy': 'popupViewer' constructor: -> super @headingText = $('#heading_text') @action_title = "<h2>#{ I18n.t('navigator.my_galaxies') }</h2>" User.bind 'sign-in', => if User.current?.user_group_id InteractiveSubject.fetch({limit: 10, user: true}).onSuccess => @samples = InteractiveSubject.lastFetch render: => if User.current.user_group_id fetcher = InteractiveSubject.fetch({limit: 10, user: true}) fetcher.onSuccess => @samples = InteractiveSubject.lastFetch @html require('views/interactive/my_galaxies')(@) for sample in @samples @generateChart sample @headingText.html @action_title $('[data-link="my_galaxies"]').addClass 'pressed' formatData: (sample) -> feature_counts = [] nice_key = '' your_classification = sample.classification for key, value of sample.counters nice_key = I<KEY>8<KEY>.<KEY> '<KEY>', key if your_classification == key selected = true else selected = false feature_counts.push { 'key': key, 'label': nice_key, 'value': value, 'selected': selected } feature_counts generateChart: (sample) -> counts = @formatData sample data = { key: 'Galaxy <KEY>', values: counts } chart = d3.select('[data-id="' + sample.zooniverse_id+ '"] svg') .append('g') .attr('width', 265) .attr('height', 100) x = d3.scale.linear() .domain([0, d3.max(data.values, (d) -> d.value)]) .range([1, 120]) color = d3.scale.ordinal() .range(['#1e7797', '#ff9c00']) chart.selectAll('rect') .data(data.values) .enter().append('rect') .attr('y', ((d,i) -> i * 22)) .attr('x', 85) .attr('height', 20) .style('fill', ((d, i) -> if d.selected '#ff9c00' else '#1e7797' )) .on("mouseover", ((d) -> d3.select(@).classed('hovered', true) )) .on("mouseout", ((d) -> d3.select(@).classed('hovered', false) )) .transition().duration(500) .attr('width', ((d) -> x d.value)) chart.selectAll('text.label') .data(data.values).enter() .append('text') .attr('class','label') .attr('y', ((d,i) -> i * 22)) .attr('x', 80) .attr('dy', '1.3em') .attr('text-anchor', 'end') .text((d, i) -> d.label) chart.selectAll('text.value') .data(data.values).enter() .append('text') .attr('class','value') .attr('y', ((d,i) -> i * 22)) .attr('x', ((d) -> x d.value)) .attr('dx', 89) .attr('dy', '1.25em') .text((d) -> d.value) popupViewer: (e) => galaxy_id = $(e.currentTarget).data('id') data = [] subject = _.find @samples, (sample) => sample.zooniverse_id == galaxy_id data.push subject d = new Dialog { template: 'views/interactive/dialog', closeButton: true, quickHide: true } d.show() subject_viewer = new SubjectViewer({el: '.subject-viewer'}) subject_viewer.receiveData data module.exports = MyGalaxies
true
Spine = require('spine') Dialog = require 'lib/dialog' User = require 'zooniverse/lib/models/user' SubjectViewer = require 'ubret/lib/controllers/SubjectViewer' BaseController = require 'ubret/lib/controllers/BaseController' InteractiveSubject = require 'ubret/lib/models/InteractiveSubject' class MyGalaxies extends Spine.Controller events: 'click .galaxy': 'popupViewer' constructor: -> super @headingText = $('#heading_text') @action_title = "<h2>#{ I18n.t('navigator.my_galaxies') }</h2>" User.bind 'sign-in', => if User.current?.user_group_id InteractiveSubject.fetch({limit: 10, user: true}).onSuccess => @samples = InteractiveSubject.lastFetch render: => if User.current.user_group_id fetcher = InteractiveSubject.fetch({limit: 10, user: true}) fetcher.onSuccess => @samples = InteractiveSubject.lastFetch @html require('views/interactive/my_galaxies')(@) for sample in @samples @generateChart sample @headingText.html @action_title $('[data-link="my_galaxies"]').addClass 'pressed' formatData: (sample) -> feature_counts = [] nice_key = '' your_classification = sample.classification for key, value of sample.counters nice_key = IPI:KEY:<KEY>END_PI8PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI 'PI:KEY:<KEY>END_PI', key if your_classification == key selected = true else selected = false feature_counts.push { 'key': key, 'label': nice_key, 'value': value, 'selected': selected } feature_counts generateChart: (sample) -> counts = @formatData sample data = { key: 'Galaxy PI:KEY:<KEY>END_PI', values: counts } chart = d3.select('[data-id="' + sample.zooniverse_id+ '"] svg') .append('g') .attr('width', 265) .attr('height', 100) x = d3.scale.linear() .domain([0, d3.max(data.values, (d) -> d.value)]) .range([1, 120]) color = d3.scale.ordinal() .range(['#1e7797', '#ff9c00']) chart.selectAll('rect') .data(data.values) .enter().append('rect') .attr('y', ((d,i) -> i * 22)) .attr('x', 85) .attr('height', 20) .style('fill', ((d, i) -> if d.selected '#ff9c00' else '#1e7797' )) .on("mouseover", ((d) -> d3.select(@).classed('hovered', true) )) .on("mouseout", ((d) -> d3.select(@).classed('hovered', false) )) .transition().duration(500) .attr('width', ((d) -> x d.value)) chart.selectAll('text.label') .data(data.values).enter() .append('text') .attr('class','label') .attr('y', ((d,i) -> i * 22)) .attr('x', 80) .attr('dy', '1.3em') .attr('text-anchor', 'end') .text((d, i) -> d.label) chart.selectAll('text.value') .data(data.values).enter() .append('text') .attr('class','value') .attr('y', ((d,i) -> i * 22)) .attr('x', ((d) -> x d.value)) .attr('dx', 89) .attr('dy', '1.25em') .text((d) -> d.value) popupViewer: (e) => galaxy_id = $(e.currentTarget).data('id') data = [] subject = _.find @samples, (sample) => sample.zooniverse_id == galaxy_id data.push subject d = new Dialog { template: 'views/interactive/dialog', closeButton: true, quickHide: true } d.show() subject_viewer = new SubjectViewer({el: '.subject-viewer'}) subject_viewer.receiveData data module.exports = MyGalaxies
[ { "context": "ient\n settings handler in client\n\n copyright mark hahn 2013\n MIT license\n https://github.com/mark-", "end": 93, "score": 0.9998272061347961, "start": 84, "tag": "NAME", "value": "mark hahn" }, { "context": " hahn 2013\n MIT license\n https://githu...
src/client/multibox-client.coffee
mark-hahn/bace
1
### file: src/client/multibox-client settings handler in client copyright mark hahn 2013 MIT license https://github.com/mark-hahn/bace/ ### bace = (window.bace ?= {}) multibox = (bace.multibox ?= {}) cmdbox = (bace.cmdbox ?= {}) dirbox = (bace.dirbox ?= {}) edit = (bace.edit ?= {}) {render,div,img,label,input,button,text,textarea} = teacup multibox.modeSelect = (mode, src, ml, w, h) -> selBrdrW = 2 render -> div {id:mode, class:'modeIcon', \ style: "margin-left:#{ml}px; float:left; width:#{w + 2*selBrdrW}px; height:#{h + 2*selBrdrW}px"}, -> img {src, style:"position:absolute; left:#{selBrdrW}px; top:#{selBrdrW}px; width:#{w}px; height:#{h}px"} bace.currentMultiboxMode = null multibox.init = ($pageHdr) -> $multiBox = $ '#multiBox', $pageHdr $modeSelBtns = $ '.modeIcon', $pageHdr multibox.setMode = (mode) -> $tgt = $ '#'+mode, $pageHdr $modeSelBtns.removeClass('modeIconSel' ).addClass('modeIconNotSel') $tgt .removeClass('modeIconNotSel').addClass('modeIconSel' ) bace.currentMultiboxMode = mode $multiBox.focus().select() $modeSelBtns.click -> multibox.setMode $(@).attr 'id' $multiBox.keydown (e) -> # console.log e.which switch e.which when 27 edit.leavingMultibox e.which when 13 switch bace.currentMultiboxMode when 'cmdMode' cmdbox.enter $multiBox.val() when 'dirMode' # console.log '$multiBox.keydown dirMode', e.which dirbox.enter $multiBox.val() when 67 if e.ctrlKey switch bace.currentMultiboxMode when 'cmdMode' then cmdbox.ctrl_c() multibox.setMode 'dirMode' setTimeout (-> $multiBox.focus()), 100
157811
### file: src/client/multibox-client settings handler in client copyright <NAME> 2013 MIT license https://github.com/mark-hahn/bace/ ### bace = (window.bace ?= {}) multibox = (bace.multibox ?= {}) cmdbox = (bace.cmdbox ?= {}) dirbox = (bace.dirbox ?= {}) edit = (bace.edit ?= {}) {render,div,img,label,input,button,text,textarea} = teacup multibox.modeSelect = (mode, src, ml, w, h) -> selBrdrW = 2 render -> div {id:mode, class:'modeIcon', \ style: "margin-left:#{ml}px; float:left; width:#{w + 2*selBrdrW}px; height:#{h + 2*selBrdrW}px"}, -> img {src, style:"position:absolute; left:#{selBrdrW}px; top:#{selBrdrW}px; width:#{w}px; height:#{h}px"} bace.currentMultiboxMode = null multibox.init = ($pageHdr) -> $multiBox = $ '#multiBox', $pageHdr $modeSelBtns = $ '.modeIcon', $pageHdr multibox.setMode = (mode) -> $tgt = $ '#'+mode, $pageHdr $modeSelBtns.removeClass('modeIconSel' ).addClass('modeIconNotSel') $tgt .removeClass('modeIconNotSel').addClass('modeIconSel' ) bace.currentMultiboxMode = mode $multiBox.focus().select() $modeSelBtns.click -> multibox.setMode $(@).attr 'id' $multiBox.keydown (e) -> # console.log e.which switch e.which when 27 edit.leavingMultibox e.which when 13 switch bace.currentMultiboxMode when 'cmdMode' cmdbox.enter $multiBox.val() when 'dirMode' # console.log '$multiBox.keydown dirMode', e.which dirbox.enter $multiBox.val() when 67 if e.ctrlKey switch bace.currentMultiboxMode when 'cmdMode' then cmdbox.ctrl_c() multibox.setMode 'dirMode' setTimeout (-> $multiBox.focus()), 100
true
### file: src/client/multibox-client settings handler in client copyright PI:NAME:<NAME>END_PI 2013 MIT license https://github.com/mark-hahn/bace/ ### bace = (window.bace ?= {}) multibox = (bace.multibox ?= {}) cmdbox = (bace.cmdbox ?= {}) dirbox = (bace.dirbox ?= {}) edit = (bace.edit ?= {}) {render,div,img,label,input,button,text,textarea} = teacup multibox.modeSelect = (mode, src, ml, w, h) -> selBrdrW = 2 render -> div {id:mode, class:'modeIcon', \ style: "margin-left:#{ml}px; float:left; width:#{w + 2*selBrdrW}px; height:#{h + 2*selBrdrW}px"}, -> img {src, style:"position:absolute; left:#{selBrdrW}px; top:#{selBrdrW}px; width:#{w}px; height:#{h}px"} bace.currentMultiboxMode = null multibox.init = ($pageHdr) -> $multiBox = $ '#multiBox', $pageHdr $modeSelBtns = $ '.modeIcon', $pageHdr multibox.setMode = (mode) -> $tgt = $ '#'+mode, $pageHdr $modeSelBtns.removeClass('modeIconSel' ).addClass('modeIconNotSel') $tgt .removeClass('modeIconNotSel').addClass('modeIconSel' ) bace.currentMultiboxMode = mode $multiBox.focus().select() $modeSelBtns.click -> multibox.setMode $(@).attr 'id' $multiBox.keydown (e) -> # console.log e.which switch e.which when 27 edit.leavingMultibox e.which when 13 switch bace.currentMultiboxMode when 'cmdMode' cmdbox.enter $multiBox.val() when 'dirMode' # console.log '$multiBox.keydown dirMode', e.which dirbox.enter $multiBox.val() when 67 if e.ctrlKey switch bace.currentMultiboxMode when 'cmdMode' then cmdbox.ctrl_c() multibox.setMode 'dirMode' setTimeout (-> $multiBox.focus()), 100
[ { "context": "###\nindex.coffee\nCopyright (C) 2015 ender xu <xuender@gmail.com>\n\nDistributed under terms of t", "end": 44, "score": 0.9997034668922424, "start": 36, "tag": "NAME", "value": "ender xu" }, { "context": "###\nindex.coffee\nCopyright (C) 2015 ender xu <xuender@gmail.co...
ma/index.coffee
xuender/mgoAdmin
0
### index.coffee Copyright (C) 2015 ender xu <xuender@gmail.com> Distributed under terms of the MIT license. ### angular.module('ma', [ 'ngRoute' 'ui.bootstrap' 'LocalStorageModule' 'ngTable' ]).config(['$routeProvider', ($routeProvider)-> $routeProvider. when('/about', templateUrl: 'partials/about.html' controller: 'AboutCtrl' ).when('/collection/:db/:collection', templateUrl: 'partials/collection.html?1' controller: 'CollectionCtrl' ).otherwise({ redirectTo: '/about' }) ])
96324
### index.coffee Copyright (C) 2015 <NAME> <<EMAIL>> Distributed under terms of the MIT license. ### angular.module('ma', [ 'ngRoute' 'ui.bootstrap' 'LocalStorageModule' 'ngTable' ]).config(['$routeProvider', ($routeProvider)-> $routeProvider. when('/about', templateUrl: 'partials/about.html' controller: 'AboutCtrl' ).when('/collection/:db/:collection', templateUrl: 'partials/collection.html?1' controller: 'CollectionCtrl' ).otherwise({ redirectTo: '/about' }) ])
true
### index.coffee Copyright (C) 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> Distributed under terms of the MIT license. ### angular.module('ma', [ 'ngRoute' 'ui.bootstrap' 'LocalStorageModule' 'ngTable' ]).config(['$routeProvider', ($routeProvider)-> $routeProvider. when('/about', templateUrl: 'partials/about.html' controller: 'AboutCtrl' ).when('/collection/:db/:collection', templateUrl: 'partials/collection.html?1' controller: 'CollectionCtrl' ).otherwise({ redirectTo: '/about' }) ])
[ { "context": "eventSourcing - messaging', ->\n\n customer = id: 'customer_123', name: 'Dominik'\n registration = id: 'registrat", "end": 78, "score": 0.9808618426322937, "start": 66, "tag": "USERNAME", "value": "customer_123" }, { "context": "ing', ->\n\n customer = id: 'customer_...
tests/infrastructure/messaging.tests.coffee
meteor-space/cqrs
0
describe 'Space.eventSourcing - messaging', -> customer = id: 'customer_123', name: 'Dominik' registration = id: 'registration_123' generatedEventsForCustomerRegistration = -> [ new Test.RegistrationInitiated({ sourceId: registration.id version: 1 timestamp: new Date() customerId: customer.id customerName: customer.name }) new Test.CustomerCreated({ sourceId: customer.id version: 1 timestamp: new Date() customerName: customer.name meta: { customerRegistrationId: registration.id } }) new Test.WelcomeEmailTriggered({ sourceId: registration.id version: 2 timestamp: new Date() customerId: customer.id meta: { customerRegistrationId: registration.id } }) # This is just visible in the app that runs the code # since it is directly published via the event store # instead of saved to the DB as part of a commit! new Test.WelcomeEmailSent({ sourceId: '999' version: 1 timestamp: new Date() email: "Hello #{customer.name}" customerId: customer.id meta: { customerRegistrationId: registration.id } }) new Test.RegistrationCompleted({ sourceId: registration.id version: 3 timestamp: new Date() meta: { customerRegistrationId: registration.id } }) ] it 'handles messages within one app correctly', -> Test.App.test(Test.Customer) .given( new Test.RegisterCustomer { targetId: registration.id customerId: customer.id customerName: customer.name } ) .expect(generatedEventsForCustomerRegistration()) ''' it 'supports distributed messaging via a shared commits collection', (test, done) -> SecondApp = Space.Application.extend { requiredModules: ['Space.eventSourcing'] configuration: { appId: 'SecondApp' } afterInitialize: -> # Aggregate all published events on the second app @publishedEvents = [] @eventBus.onPublish (event) => @publishedEvents.push event } secondApp = new SecondApp() secondApp.reset() secondApp.start() try expectedEvents = null Test.test(Test.Customer) .given( new Test.RegisterCustomer { targetId: registration.id customerId: customer.id customerName: customer.name } ) .expect(-> expectedEvents = generatedEventsForCustomerRegistration() return expectedEvents ) # Remove the event that is only visible to the other app # because it is directly published on its event bus! expectedEvents.splice(3,1) expect(secondApp.publishedEvents).toMatch expectedEvents finally secondApp.stop() '''
111733
describe 'Space.eventSourcing - messaging', -> customer = id: 'customer_123', name: '<NAME>' registration = id: 'registration_123' generatedEventsForCustomerRegistration = -> [ new Test.RegistrationInitiated({ sourceId: registration.id version: 1 timestamp: new Date() customerId: customer.id customerName: customer.name }) new Test.CustomerCreated({ sourceId: customer.id version: 1 timestamp: new Date() customerName: customer.name meta: { customerRegistrationId: registration.id } }) new Test.WelcomeEmailTriggered({ sourceId: registration.id version: 2 timestamp: new Date() customerId: customer.id meta: { customerRegistrationId: registration.id } }) # This is just visible in the app that runs the code # since it is directly published via the event store # instead of saved to the DB as part of a commit! new Test.WelcomeEmailSent({ sourceId: '999' version: 1 timestamp: new Date() email: "Hello #{customer.name}" customerId: customer.id meta: { customerRegistrationId: registration.id } }) new Test.RegistrationCompleted({ sourceId: registration.id version: 3 timestamp: new Date() meta: { customerRegistrationId: registration.id } }) ] it 'handles messages within one app correctly', -> Test.App.test(Test.Customer) .given( new Test.RegisterCustomer { targetId: registration.id customerId: customer.id customerName: customer.name } ) .expect(generatedEventsForCustomerRegistration()) ''' it 'supports distributed messaging via a shared commits collection', (test, done) -> SecondApp = Space.Application.extend { requiredModules: ['Space.eventSourcing'] configuration: { appId: 'SecondApp' } afterInitialize: -> # Aggregate all published events on the second app @publishedEvents = [] @eventBus.onPublish (event) => @publishedEvents.push event } secondApp = new SecondApp() secondApp.reset() secondApp.start() try expectedEvents = null Test.test(Test.Customer) .given( new Test.RegisterCustomer { targetId: registration.id customerId: customer.id customerName: <NAME> } ) .expect(-> expectedEvents = generatedEventsForCustomerRegistration() return expectedEvents ) # Remove the event that is only visible to the other app # because it is directly published on its event bus! expectedEvents.splice(3,1) expect(secondApp.publishedEvents).toMatch expectedEvents finally secondApp.stop() '''
true
describe 'Space.eventSourcing - messaging', -> customer = id: 'customer_123', name: 'PI:NAME:<NAME>END_PI' registration = id: 'registration_123' generatedEventsForCustomerRegistration = -> [ new Test.RegistrationInitiated({ sourceId: registration.id version: 1 timestamp: new Date() customerId: customer.id customerName: customer.name }) new Test.CustomerCreated({ sourceId: customer.id version: 1 timestamp: new Date() customerName: customer.name meta: { customerRegistrationId: registration.id } }) new Test.WelcomeEmailTriggered({ sourceId: registration.id version: 2 timestamp: new Date() customerId: customer.id meta: { customerRegistrationId: registration.id } }) # This is just visible in the app that runs the code # since it is directly published via the event store # instead of saved to the DB as part of a commit! new Test.WelcomeEmailSent({ sourceId: '999' version: 1 timestamp: new Date() email: "Hello #{customer.name}" customerId: customer.id meta: { customerRegistrationId: registration.id } }) new Test.RegistrationCompleted({ sourceId: registration.id version: 3 timestamp: new Date() meta: { customerRegistrationId: registration.id } }) ] it 'handles messages within one app correctly', -> Test.App.test(Test.Customer) .given( new Test.RegisterCustomer { targetId: registration.id customerId: customer.id customerName: customer.name } ) .expect(generatedEventsForCustomerRegistration()) ''' it 'supports distributed messaging via a shared commits collection', (test, done) -> SecondApp = Space.Application.extend { requiredModules: ['Space.eventSourcing'] configuration: { appId: 'SecondApp' } afterInitialize: -> # Aggregate all published events on the second app @publishedEvents = [] @eventBus.onPublish (event) => @publishedEvents.push event } secondApp = new SecondApp() secondApp.reset() secondApp.start() try expectedEvents = null Test.test(Test.Customer) .given( new Test.RegisterCustomer { targetId: registration.id customerId: customer.id customerName: PI:NAME:<NAME>END_PI } ) .expect(-> expectedEvents = generatedEventsForCustomerRegistration() return expectedEvents ) # Remove the event that is only visible to the other app # because it is directly published on its event bus! expectedEvents.splice(3,1) expect(secondApp.publishedEvents).toMatch expectedEvents finally secondApp.stop() '''
[ { "context": "tent: activa el link del menu de la pagina.\n@autor Ronny Cabrera\n###\nyOSON.AppCore.addModule \"activeMenu\", (Sb) ->", "end": 71, "score": 0.9998650550842285, "start": 58, "tag": "NAME", "value": "Ronny Cabrera" } ]
frontend/resources/coffee/modules/all/activeMenu.coffee
ronnyfly2/openvios
0
### Content: activa el link del menu de la pagina. @autor Ronny Cabrera ### yOSON.AppCore.addModule "activeMenu", (Sb) -> defaults = webView : '.container' navLink : 'aside nav li a' st = {} dom = {} catchDom = (st)-> dom.webView = $(st.webView) dom.navLink = $(st.navLink) return suscribeEvents = -> events.getLink() return events = getLink:()-> page = dom.webView.data('page') log page linkActive = dom.navLink.data('link') $('nav li a[data-link="' + page + '"]').addClass 'actived' return functions = {} initialize = (opts) -> st = $.extend({}, defaults, opts) catchDom(st) suscribeEvents() return return { init: initialize } ,[]
85609
### Content: activa el link del menu de la pagina. @autor <NAME> ### yOSON.AppCore.addModule "activeMenu", (Sb) -> defaults = webView : '.container' navLink : 'aside nav li a' st = {} dom = {} catchDom = (st)-> dom.webView = $(st.webView) dom.navLink = $(st.navLink) return suscribeEvents = -> events.getLink() return events = getLink:()-> page = dom.webView.data('page') log page linkActive = dom.navLink.data('link') $('nav li a[data-link="' + page + '"]').addClass 'actived' return functions = {} initialize = (opts) -> st = $.extend({}, defaults, opts) catchDom(st) suscribeEvents() return return { init: initialize } ,[]
true
### Content: activa el link del menu de la pagina. @autor PI:NAME:<NAME>END_PI ### yOSON.AppCore.addModule "activeMenu", (Sb) -> defaults = webView : '.container' navLink : 'aside nav li a' st = {} dom = {} catchDom = (st)-> dom.webView = $(st.webView) dom.navLink = $(st.navLink) return suscribeEvents = -> events.getLink() return events = getLink:()-> page = dom.webView.data('page') log page linkActive = dom.navLink.data('link') $('nav li a[data-link="' + page + '"]').addClass 'actived' return functions = {} initialize = (opts) -> st = $.extend({}, defaults, opts) catchDom(st) suscribeEvents() return return { init: initialize } ,[]
[ { "context": "idate 'title', presence: true\n\t@storageKey: 'todos-batman'\n\n\t@classAccessor 'active', ->\n\t\t@get('all').filt", "end": 1973, "score": 0.6355152130126953, "start": 1967, "tag": "KEY", "value": "batman" } ]
labs/architecture-examples/batman/js/app.coffee
whegreen/todomvc
1
class Alfred extends Batman.App @root 'todos#all' @route '/completed', 'todos#completed' @route '/active', 'todos#active' class Alfred.TodosController extends Batman.Controller constructor: -> super @set 'newTodo', new Alfred.Todo(completed: false) all: -> @set 'currentTodos', Alfred.Todo.get('all') completed: -> @set 'currentTodos', Alfred.Todo.get('completed') @render source: 'todos/all' active: -> @set 'currentTodos', Alfred.Todo.get('active') @render source: 'todos/all' createTodo: -> @get('newTodo').save (err, todo) => if err throw err unless err instanceof Batman.ErrorsSet else @set 'newTodo', new Alfred.Todo(completed: false, title: "") todoDoneChanged: (node, event, context) -> todo = context.get('todo') todo.save (err) -> throw err if err && !err instanceof Batman.ErrorsSet destroyTodo: (node, event, context) -> todo = context.get('todo') todo.destroy (err) -> throw err if err toggleAll: (node, context) -> Alfred.Todo.get('all').forEach (todo) -> todo.set('completed', !!node.checked) todo.save (err) -> throw err if err && !err instanceof Batman.ErrorsSet clearCompleted: -> Alfred.Todo.get('completed').forEach (todo) -> todo.destroy (err) -> throw err if err toggleEditing: (node, event, context) -> todo = context.get('todo') editing = todo.set('editing', !todo.get('editing')) if editing input = document.getElementById("todo-input-#{todo.get('id')}") input.focus() else if todo.get('title')?.length > 0 todo.save (err, todo) -> throw err if err && !err instanceof Batman.ErrorsSet else todo.destroy (err, todo) -> throw err if err disableEditingUponSubmit: (node, event, context) -> if Batman.DOM.events.isEnter(event) @toggleEditing(node, event, context) class Alfred.Todo extends Batman.Model @encode 'title', 'completed' @persist Batman.LocalStorage @validate 'title', presence: true @storageKey: 'todos-batman' @classAccessor 'active', -> @get('all').filter (todo) -> !todo.get('completed') @classAccessor 'completed', -> @get('all').filter (todo) -> todo.get('completed') @wrapAccessor 'title', (core) -> set: (key, value) -> core.set.call(@, key, value?.trim()) window.Alfred = Alfred Alfred.run()
176519
class Alfred extends Batman.App @root 'todos#all' @route '/completed', 'todos#completed' @route '/active', 'todos#active' class Alfred.TodosController extends Batman.Controller constructor: -> super @set 'newTodo', new Alfred.Todo(completed: false) all: -> @set 'currentTodos', Alfred.Todo.get('all') completed: -> @set 'currentTodos', Alfred.Todo.get('completed') @render source: 'todos/all' active: -> @set 'currentTodos', Alfred.Todo.get('active') @render source: 'todos/all' createTodo: -> @get('newTodo').save (err, todo) => if err throw err unless err instanceof Batman.ErrorsSet else @set 'newTodo', new Alfred.Todo(completed: false, title: "") todoDoneChanged: (node, event, context) -> todo = context.get('todo') todo.save (err) -> throw err if err && !err instanceof Batman.ErrorsSet destroyTodo: (node, event, context) -> todo = context.get('todo') todo.destroy (err) -> throw err if err toggleAll: (node, context) -> Alfred.Todo.get('all').forEach (todo) -> todo.set('completed', !!node.checked) todo.save (err) -> throw err if err && !err instanceof Batman.ErrorsSet clearCompleted: -> Alfred.Todo.get('completed').forEach (todo) -> todo.destroy (err) -> throw err if err toggleEditing: (node, event, context) -> todo = context.get('todo') editing = todo.set('editing', !todo.get('editing')) if editing input = document.getElementById("todo-input-#{todo.get('id')}") input.focus() else if todo.get('title')?.length > 0 todo.save (err, todo) -> throw err if err && !err instanceof Batman.ErrorsSet else todo.destroy (err, todo) -> throw err if err disableEditingUponSubmit: (node, event, context) -> if Batman.DOM.events.isEnter(event) @toggleEditing(node, event, context) class Alfred.Todo extends Batman.Model @encode 'title', 'completed' @persist Batman.LocalStorage @validate 'title', presence: true @storageKey: 'todos-<KEY>' @classAccessor 'active', -> @get('all').filter (todo) -> !todo.get('completed') @classAccessor 'completed', -> @get('all').filter (todo) -> todo.get('completed') @wrapAccessor 'title', (core) -> set: (key, value) -> core.set.call(@, key, value?.trim()) window.Alfred = Alfred Alfred.run()
true
class Alfred extends Batman.App @root 'todos#all' @route '/completed', 'todos#completed' @route '/active', 'todos#active' class Alfred.TodosController extends Batman.Controller constructor: -> super @set 'newTodo', new Alfred.Todo(completed: false) all: -> @set 'currentTodos', Alfred.Todo.get('all') completed: -> @set 'currentTodos', Alfred.Todo.get('completed') @render source: 'todos/all' active: -> @set 'currentTodos', Alfred.Todo.get('active') @render source: 'todos/all' createTodo: -> @get('newTodo').save (err, todo) => if err throw err unless err instanceof Batman.ErrorsSet else @set 'newTodo', new Alfred.Todo(completed: false, title: "") todoDoneChanged: (node, event, context) -> todo = context.get('todo') todo.save (err) -> throw err if err && !err instanceof Batman.ErrorsSet destroyTodo: (node, event, context) -> todo = context.get('todo') todo.destroy (err) -> throw err if err toggleAll: (node, context) -> Alfred.Todo.get('all').forEach (todo) -> todo.set('completed', !!node.checked) todo.save (err) -> throw err if err && !err instanceof Batman.ErrorsSet clearCompleted: -> Alfred.Todo.get('completed').forEach (todo) -> todo.destroy (err) -> throw err if err toggleEditing: (node, event, context) -> todo = context.get('todo') editing = todo.set('editing', !todo.get('editing')) if editing input = document.getElementById("todo-input-#{todo.get('id')}") input.focus() else if todo.get('title')?.length > 0 todo.save (err, todo) -> throw err if err && !err instanceof Batman.ErrorsSet else todo.destroy (err, todo) -> throw err if err disableEditingUponSubmit: (node, event, context) -> if Batman.DOM.events.isEnter(event) @toggleEditing(node, event, context) class Alfred.Todo extends Batman.Model @encode 'title', 'completed' @persist Batman.LocalStorage @validate 'title', presence: true @storageKey: 'todos-PI:KEY:<KEY>END_PI' @classAccessor 'active', -> @get('all').filter (todo) -> !todo.get('completed') @classAccessor 'completed', -> @get('all').filter (todo) -> todo.get('completed') @wrapAccessor 'title', (core) -> set: (key, value) -> core.set.call(@, key, value?.trim()) window.Alfred = Alfred Alfred.run()
[ { "context": ".caseInsensitive', false)\n editor.setText('CAL')\n editor.setCursorBufferPosition([0, 3])\n", "end": 2325, "score": 0.9033557772636414, "start": 2322, "tag": "NAME", "value": "CAL" }, { "context": "ttings\", ->\n runs ->\n editor.setText('calb...
spec/provider-spec.coffee
bitride/atom-autocomplete-ctags
13
path = require 'path' fs = require 'fs-plus' temp = require 'temp' describe "AutocompleteCtags", -> [editor, provider, directory] = [] getCompletions = -> cursor = editor.getLastCursor() start = cursor.getBeginningOfCurrentWordBufferPosition() end = cursor.getBufferPosition() prefix = editor.getTextInRange([start, end]) request = editor: editor bufferPosition: end scopeDescriptor: cursor.getScopeDescriptor() prefix: prefix provider.getSuggestions(request) beforeEach -> atom.config.set('autocomplete-ctags.minimumPrefixLength', 3) atom.config.set('autocomplete-ctags.caseInsensitive', true) atom.config.set('autocomplete-ctags.useSnippers', false) atom.config.set('autocomplete-ctags.useFuzzy', false) atom.project.setPaths([ temp.mkdirSync("other-dir-") temp.mkdirSync('atom-autocomplete-ctags') ]) directory = atom.project.getDirectories()[1] fs.copySync(path.join(__dirname, 'fixtures', 'js'), atom.project.getPaths()[1]) waitsForPromise -> atom.packages.activatePackage('autocomplete-ctags').then (pack) -> provider = pack.mainModule.provide() waitsFor -> provider.tagsFiles.length > 0 describe "js files", -> beforeEach -> waitsForPromise -> atom.workspace.open(directory.resolve('new.js')).then (_editor) -> editor = _editor it "return tag completions", -> editor.setText('c') waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 0 ) runs -> editor.setText('cal') editor.setCursorBufferPosition([0, 3]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 1 [completion] = completions expect(completion.text.length).toBeGreaterThan 0 expect(completion.type).toBe 'function' ) it "caseInsensitive settings", -> runs -> editor.setText('CAL') editor.setCursorBufferPosition([0, 3]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 1 ) runs -> atom.config.set('autocomplete-ctags.caseInsensitive', false) editor.setText('CAL') editor.setCursorBufferPosition([0, 3]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 0 ) it 'useSnippers settings', -> expect(provider.snippers).toBeNull() atom.config.set('autocomplete-ctags.useSnippers', true) expect(provider.snippers.constructor.name).toEqual('Snippers') it "useFuzzy settings", -> runs -> editor.setText('calbe') editor.setCursorBufferPosition([0, 5]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 0 ) runs -> atom.config.set('autocomplete-ctags.useFuzzy', true) waitsFor -> provider.tagsFiles[0].getCachedTags().length > 0 runs -> editor.setText('calbe') editor.setCursorBufferPosition([0, 5]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 1 )
50956
path = require 'path' fs = require 'fs-plus' temp = require 'temp' describe "AutocompleteCtags", -> [editor, provider, directory] = [] getCompletions = -> cursor = editor.getLastCursor() start = cursor.getBeginningOfCurrentWordBufferPosition() end = cursor.getBufferPosition() prefix = editor.getTextInRange([start, end]) request = editor: editor bufferPosition: end scopeDescriptor: cursor.getScopeDescriptor() prefix: prefix provider.getSuggestions(request) beforeEach -> atom.config.set('autocomplete-ctags.minimumPrefixLength', 3) atom.config.set('autocomplete-ctags.caseInsensitive', true) atom.config.set('autocomplete-ctags.useSnippers', false) atom.config.set('autocomplete-ctags.useFuzzy', false) atom.project.setPaths([ temp.mkdirSync("other-dir-") temp.mkdirSync('atom-autocomplete-ctags') ]) directory = atom.project.getDirectories()[1] fs.copySync(path.join(__dirname, 'fixtures', 'js'), atom.project.getPaths()[1]) waitsForPromise -> atom.packages.activatePackage('autocomplete-ctags').then (pack) -> provider = pack.mainModule.provide() waitsFor -> provider.tagsFiles.length > 0 describe "js files", -> beforeEach -> waitsForPromise -> atom.workspace.open(directory.resolve('new.js')).then (_editor) -> editor = _editor it "return tag completions", -> editor.setText('c') waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 0 ) runs -> editor.setText('cal') editor.setCursorBufferPosition([0, 3]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 1 [completion] = completions expect(completion.text.length).toBeGreaterThan 0 expect(completion.type).toBe 'function' ) it "caseInsensitive settings", -> runs -> editor.setText('CAL') editor.setCursorBufferPosition([0, 3]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 1 ) runs -> atom.config.set('autocomplete-ctags.caseInsensitive', false) editor.setText('<NAME>') editor.setCursorBufferPosition([0, 3]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 0 ) it 'useSnippers settings', -> expect(provider.snippers).toBeNull() atom.config.set('autocomplete-ctags.useSnippers', true) expect(provider.snippers.constructor.name).toEqual('Snippers') it "useFuzzy settings", -> runs -> editor.setText('<NAME>') editor.setCursorBufferPosition([0, 5]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 0 ) runs -> atom.config.set('autocomplete-ctags.useFuzzy', true) waitsFor -> provider.tagsFiles[0].getCachedTags().length > 0 runs -> editor.setText('<NAME>') editor.setCursorBufferPosition([0, 5]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 1 )
true
path = require 'path' fs = require 'fs-plus' temp = require 'temp' describe "AutocompleteCtags", -> [editor, provider, directory] = [] getCompletions = -> cursor = editor.getLastCursor() start = cursor.getBeginningOfCurrentWordBufferPosition() end = cursor.getBufferPosition() prefix = editor.getTextInRange([start, end]) request = editor: editor bufferPosition: end scopeDescriptor: cursor.getScopeDescriptor() prefix: prefix provider.getSuggestions(request) beforeEach -> atom.config.set('autocomplete-ctags.minimumPrefixLength', 3) atom.config.set('autocomplete-ctags.caseInsensitive', true) atom.config.set('autocomplete-ctags.useSnippers', false) atom.config.set('autocomplete-ctags.useFuzzy', false) atom.project.setPaths([ temp.mkdirSync("other-dir-") temp.mkdirSync('atom-autocomplete-ctags') ]) directory = atom.project.getDirectories()[1] fs.copySync(path.join(__dirname, 'fixtures', 'js'), atom.project.getPaths()[1]) waitsForPromise -> atom.packages.activatePackage('autocomplete-ctags').then (pack) -> provider = pack.mainModule.provide() waitsFor -> provider.tagsFiles.length > 0 describe "js files", -> beforeEach -> waitsForPromise -> atom.workspace.open(directory.resolve('new.js')).then (_editor) -> editor = _editor it "return tag completions", -> editor.setText('c') waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 0 ) runs -> editor.setText('cal') editor.setCursorBufferPosition([0, 3]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 1 [completion] = completions expect(completion.text.length).toBeGreaterThan 0 expect(completion.type).toBe 'function' ) it "caseInsensitive settings", -> runs -> editor.setText('CAL') editor.setCursorBufferPosition([0, 3]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 1 ) runs -> atom.config.set('autocomplete-ctags.caseInsensitive', false) editor.setText('PI:NAME:<NAME>END_PI') editor.setCursorBufferPosition([0, 3]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 0 ) it 'useSnippers settings', -> expect(provider.snippers).toBeNull() atom.config.set('autocomplete-ctags.useSnippers', true) expect(provider.snippers.constructor.name).toEqual('Snippers') it "useFuzzy settings", -> runs -> editor.setText('PI:NAME:<NAME>END_PI') editor.setCursorBufferPosition([0, 5]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 0 ) runs -> atom.config.set('autocomplete-ctags.useFuzzy', true) waitsFor -> provider.tagsFiles[0].getCachedTags().length > 0 runs -> editor.setText('PI:NAME:<NAME>END_PI') editor.setCursorBufferPosition([0, 5]) waitsForPromise -> getCompletions().then((completions) -> expect(completions).toHaveLength 1 )
[ { "context": "\n\n\tgetSaveData: (data, save_data) ->\n\t\tdata = data[@name()]\n\t\tif CUI.util.isEmpty(data)\n\t\t\treturn save_dat", "end": 2152, "score": 0.9558122754096985, "start": 2147, "tag": "USERNAME", "value": "@name" }, { "context": "f CUI.util.isEmpty(data.gazId)\n\t\t\t...
src/webfrontend/CustomDataTypeGazetteer.coffee
programmfabrik/easydb-custom-data-type-gazetteer
0
class CustomDataTypeGazetteer extends CustomDataType getCustomDataTypeName: -> "custom:base.custom-data-type-gazetteer.gazetteer" getCustomDataTypeNameLocalized: -> $$("custom.data.type.gazetteer.name") getCustomDataOptionsInDatamodelInfo: (custom_settings) -> return [] supportsStandard: -> true renderSearchInput: (data, opts={}) -> return new SearchToken( column: @ data: data fields: opts.fields ).getInput().DOM getFieldNamesForSearch: -> @__getFieldNames() getFieldNamesForSuggest: -> @__getFieldNames() renderEditorInput: (data) -> initData = @__initData(data) content = CUI.dom.div() waitBlock = new CUI.WaitBlock(element: content) setContent = => [searchInput, displayOutput] = @__initForm(initData) searchInput.start() displayOutput.start() CUI.dom.append(content, searchInput) CUI.dom.append(content, displayOutput) waitBlock.destroy() waitBlock.show() @__fillMissingData(initData).done(setContent) return content renderTableOutput: (data, _, opts) -> initData = @__initData(data) content = @__renderOutput( data: initData onlyText: true ) return content renderDetailOutput: (data, _, opts) -> initData = @__initData(data) content = CUI.dom.div() waitBlock = new CUI.WaitBlock(element: content) setContent = => outputFieldElement = @__renderOutput(data: initData) CUI.dom.replace(content, outputFieldElement) waitBlock.destroy() if CUI.Map.isValidPosition(initData.position) and opts.detail plugins = opts.detail.getPlugins() for plugin in plugins if plugin instanceof MapDetailPlugin mapPlugin = plugin break if mapPlugin mapPlugin.addMarker(position: initData.position, iconName: initData.iconName, iconColor: "#6786ad") waitBlock.show() @__fillMissingData(initData).done(setContent) CUI.Events.listen type: "map-detail-click-location" node: content call: (_, info) => if info.data?.position == initData.position CUI.dom.scrollIntoView(content) return content renderFieldAsGroup: -> return false getSaveData: (data, save_data) -> data = data[@name()] if CUI.util.isEmpty(data) return save_data[@name()] = null if CUI.util.isEmpty(data.gazId) return save_data[@name()] = null if data.notFound return throw new InvalidSaveDataException() return save_data[@name()] = ez5.GazetteerUtil.getSaveDataObject(data) getQueryFieldBadge: (data) => if data["#{@name()}:unset"] value = $$("text.column.badge.without") else value = data[@name()] name: @nameLocalized() value: value getSearchFilter: (data, key=@name()) -> if data[key+":unset"] filter = type: "in" fields: [ @fullName()+".displayName" ] in: [ null ] filter._unnest = true filter._unset_filter = true return filter filter = super(data, key) if filter return filter if CUI.util.isEmpty(data[key]) return val = data[key] [str, phrase] = Search.getPhrase(val) switch data[key+":type"] when "token", "fulltext", undefined filter = type: "match" mode: data[key+":mode"] fields: @getFieldNamesForSearch() string: str phrase: phrase when "field" filter = type: "in" fields: @getFieldNamesForSearch() in: [ str ] filter __getFieldNames: -> return [ @fullName()+".gazId" @fullName()+".displayName" ] __initForm: (formData) -> searchData = q: "" resultsContainer = "results" loadingContainer = "loading" noResultsContainer = "no_results" loadingLabel = new LocaLabel(loca_key: "autocompletion.loading", padded: true) noResultsLabel = new LocaLabel(loca_key: "custom.data.type.gazetteer.search.no-results", padded: true) searchField = new CUI.Input name: "q" hidden: true placeholder: $$("custom.data.type.gazetteer.search.placeholder") maximize_horizontal: true data: searchData onDataChanged: => CUI.scheduleCallback ms: 200 call: search autocompletionPopup = new AutocompletionPopup element: searchField onHide: => autocompletionPopup.hide() autocompletionPopup.addContainer(resultsContainer) autocompletionPopup.addContainer(loadingContainer) autocompletionPopup.addContainer(noResultsContainer) outputDiv = CUI.dom.div() outputField = new CUI.DataFieldProxy name: "displayName" hidden: true element: outputDiv onDelete = => searchField.show() outputField.hide() cleanData() searchField.reload() CUI.Events.trigger node: searchField type: "editor-changed" showOutputField = => card = @__renderOutput( data: formData editor: true onDelete: onDelete onModify: => id = formData.gazId onDelete() searchData.q = id searchField.reload() search() ) CUI.dom.replace(outputDiv, card) outputField.show() cleanData = => delete formData.displayName delete formData.gazId delete formData.otherNames delete formData.types delete formData.position delete formData.iconName setData = (object) => searchData.q = "" ez5.GazetteerUtil.setObjectData(formData, object) searchXHR = null search = => searchXHR?.abort() autocompletionPopup.emptyContainer(resultsContainer) autocompletionPopup.emptyContainer(loadingContainer) autocompletionPopup.emptyContainer(noResultsContainer) if searchData.q.length == 0 # Trigger search when it is not empty. return autocompletionPopup.getContainer(loadingContainer).replace(loadingLabel) autocompletionPopup.show() searchXHR = new CUI.XHR method: "GET" url: ez5.GazetteerUtil.SEARCH_API_URL + CUI.encodeUrlData(searchData) searchXHR.start().done((data) => autocompletionPopup.emptyContainer(loadingContainer) if data.result?.length == 0 autocompletionPopup.getContainer(noResultsContainer).replace(noResultsLabel) return for object in data.result do(object) => item = autocompletionPopup.appendItem(resultsContainer, @__renderAutocompleteCard(object) ) CUI.Events.listen type: "click" node: item call: (ev) => ev.stopPropagation() if object setData(object) else cleanData() searchField.hide() showOutputField() autocompletionPopup.hide() CUI.Events.trigger node: searchField type: "editor-changed" return CUI.Events.trigger type: "content-resize" node: autocompletionPopup ) if CUI.util.isEmpty(formData) or formData.notFound or not formData.gazId searchField.show() else showOutputField() [searchField, outputField] __initData: (data) -> if not data[@name()] initData = {} data[@name()] = initData else initData = data[@name()] initData __renderOutput: (opts) -> formData = opts.data if formData.notFound return new CUI.EmptyLabel(text: $$("custom.data.type.gazetteer.preview.id-not-found"), class: "ez-label-invalid") if formData.gazId return @__renderCard(opts) else return new CUI.EmptyLabel(text: $$("custom.data.type.gazetteer.preview.empty-label")) __renderAutocompleteCard: (data) -> object = {} ez5.GazetteerUtil.setObjectData(object, data) @__renderCard( data: object small: true ) __renderCard: (_opts) -> opts = CUI.Element.readOpts(_opts, "CustomDataTypeGazetteer.__renderCard", data: check: "PlainObject" mandatory: true editor: check: Boolean default: false small: check: Boolean default: false onlyText: check: Boolean default: false onDelete: check: Function onModify: check: Function ) {data, editor, small, onDelete, onModify, onlyText} = opts content = [ new CUI.Label(text: data.displayName, appearance: "title", multiline: true) ] if onlyText return content[0] link = ez5.GazetteerUtil.PLACE_URL + data.gazId menuItems = [ new LocaButtonHref loca_key: "custom.data.type.gazetteer.link.button" href: link target: "_blank" ] if not small if CUI.Map.isValidPosition(data.position) menuItems.push( new LocaButton loca_key: "custom.data.type.gazetteer.preview.button" onClick: => previewPopover = new CUI.Popover element: menuButton placement: "sw" pane: @__buildPreviewMap(data.position, data.iconName) onHide: => previewPopover.destroy() previewPopover.show() ) if editor menuItems.push( new LocaButton loca_key: "custom.data.type.gazetteer.delete.button" onClick: => onDelete?() ) menuItems.push( new LocaButton loca_key: "custom.data.type.gazetteer.modify.button" onClick: => onModify?() ) menuButton = new LocaButton loca_key: "custom.data.type.gazetteer.menu.button" icon: "ellipsis_v" icon_right: false appearance: "flat" menu: items: menuItems if data.types types = [] for type in data.types types.push $$("custom.data.type.gazetteer.types.#{type}.text") content.push new CUI.Label(text: types.join(", "), appearance: "secondary") if not CUI.util.isEmpty(data.otherNames) and ez5.session.config.base.system.gazetteer_plugin_settings?.show_alternative_names otherNameLabels = [] showingMore = false showMoreLessButton = new CUI.Button text: "" appearance: "link" size: "mini" onClick: => if showingMore showLess() else showMore() showingMore = not showingMore CUI.dom.hideElement(showMoreLessButton) showLess = () -> for label in otherNameLabels CUI.dom.hideElement(label) for level in [0..3] by 1 if not otherNameLabels[level] continue CUI.dom.showElement(otherNameLabels[level]) if otherNameLabels.length > 4 showMoreLessButton.setText($$("custom.data.type.gazetteer.types.card.show-more-button")) CUI.dom.showElement(showMoreLessButton) return showMore = () -> for label in otherNameLabels CUI.dom.showElement(label) showMoreLessButton.setText($$("custom.data.type.gazetteer.types.card.show-less-button")) return otherNames = data.otherNames.map((otherName) -> otherName.title) for otherName in otherNames otherNameLabels.push(new CUI.Label(text: otherName, appearance: "secondary")) showLess() verticalListContent = if small then otherNameLabels else otherNameLabels.concat([showMoreLessButton]) verticalList = new CUI.VerticalList(content: verticalListContent) content.push(verticalList) if not CUI.util.isEmpty(data.position) and ez5.session.config.base.system.gazetteer_plugin_settings?.show_lat_lng content.push(new CUI.Label(text: $$("custom.data.type.gazetteer.types.latitude_longitude.text", data.position), appearance: "secondary")) list = new CUI.VerticalList(content: content) if small return list else plugin = ez5.pluginManager.getPlugin("custom-data-type-gazetteer") previewImage = new Image(36, 36) previewImage.src = plugin.getBaseURL() + plugin.getWebfrontend().logo return new CUI.HorizontalLayout( class: "ez5-field-object ez5-custom-data-type-gazetteer-card" left: content: previewImage center: content: list right: content: menuButton ) __buildPreviewMap: (position, iconName) -> return new CUI.MapInput.defaults.mapClass( selectedMarkerPosition: position selectedMarkerOptions: iconName: iconName iconColor: "#6786ad" centerPosition: position clickable: false zoom: 10 ) # This is the case that the ID is in the data but it was not found before. __fillMissingData: (data) -> if data.gazId and (not data.displayName or not data.types) deferred = new CUI.Deferred() ez5.GazetteerUtil.searchById(data.gazId).done((dataFound) => ez5.GazetteerUtil.setObjectData(data, dataFound) ).fail( => data.notFound = true ).always(deferred.resolve) return deferred.promise() else return CUI.resolvedPromise() isPluginSupported: (plugin) -> if plugin instanceof MapDetailPlugin return true return false CustomDataType.register(CustomDataTypeGazetteer)
106784
class CustomDataTypeGazetteer extends CustomDataType getCustomDataTypeName: -> "custom:base.custom-data-type-gazetteer.gazetteer" getCustomDataTypeNameLocalized: -> $$("custom.data.type.gazetteer.name") getCustomDataOptionsInDatamodelInfo: (custom_settings) -> return [] supportsStandard: -> true renderSearchInput: (data, opts={}) -> return new SearchToken( column: @ data: data fields: opts.fields ).getInput().DOM getFieldNamesForSearch: -> @__getFieldNames() getFieldNamesForSuggest: -> @__getFieldNames() renderEditorInput: (data) -> initData = @__initData(data) content = CUI.dom.div() waitBlock = new CUI.WaitBlock(element: content) setContent = => [searchInput, displayOutput] = @__initForm(initData) searchInput.start() displayOutput.start() CUI.dom.append(content, searchInput) CUI.dom.append(content, displayOutput) waitBlock.destroy() waitBlock.show() @__fillMissingData(initData).done(setContent) return content renderTableOutput: (data, _, opts) -> initData = @__initData(data) content = @__renderOutput( data: initData onlyText: true ) return content renderDetailOutput: (data, _, opts) -> initData = @__initData(data) content = CUI.dom.div() waitBlock = new CUI.WaitBlock(element: content) setContent = => outputFieldElement = @__renderOutput(data: initData) CUI.dom.replace(content, outputFieldElement) waitBlock.destroy() if CUI.Map.isValidPosition(initData.position) and opts.detail plugins = opts.detail.getPlugins() for plugin in plugins if plugin instanceof MapDetailPlugin mapPlugin = plugin break if mapPlugin mapPlugin.addMarker(position: initData.position, iconName: initData.iconName, iconColor: "#6786ad") waitBlock.show() @__fillMissingData(initData).done(setContent) CUI.Events.listen type: "map-detail-click-location" node: content call: (_, info) => if info.data?.position == initData.position CUI.dom.scrollIntoView(content) return content renderFieldAsGroup: -> return false getSaveData: (data, save_data) -> data = data[@name()] if CUI.util.isEmpty(data) return save_data[@name()] = null if CUI.util.isEmpty(data.gazId) return save_data[@name()] = null if data.notFound return throw new InvalidSaveDataException() return save_data[@name()] = ez5.GazetteerUtil.getSaveDataObject(data) getQueryFieldBadge: (data) => if data["#{@name()}:unset"] value = $$("text.column.badge.without") else value = data[@name()] name: @nameLocalized() value: value getSearchFilter: (data, key=@name()) -> if data[key+":unset"] filter = type: "in" fields: [ @fullName()+".displayName" ] in: [ null ] filter._unnest = true filter._unset_filter = true return filter filter = super(data, key) if filter return filter if CUI.util.isEmpty(data[key]) return val = data[key] [str, phrase] = Search.getPhrase(val) switch data[key+":type"] when "token", "fulltext", undefined filter = type: "match" mode: data[key+":mode"] fields: @getFieldNamesForSearch() string: str phrase: phrase when "field" filter = type: "in" fields: @getFieldNamesForSearch() in: [ str ] filter __getFieldNames: -> return [ @fullName()+".gazId" @fullName()+".displayName" ] __initForm: (formData) -> searchData = q: "" resultsContainer = "results" loadingContainer = "loading" noResultsContainer = "no_results" loadingLabel = new LocaLabel(loca_key: "autocompletion.loading", padded: true) noResultsLabel = new LocaLabel(loca_key: "custom.data.type.gazetteer.search.no-results", padded: true) searchField = new CUI.Input name: "q" hidden: true placeholder: $$("custom.data.type.gazetteer.search.placeholder") maximize_horizontal: true data: searchData onDataChanged: => CUI.scheduleCallback ms: 200 call: search autocompletionPopup = new AutocompletionPopup element: searchField onHide: => autocompletionPopup.hide() autocompletionPopup.addContainer(resultsContainer) autocompletionPopup.addContainer(loadingContainer) autocompletionPopup.addContainer(noResultsContainer) outputDiv = CUI.dom.div() outputField = new CUI.DataFieldProxy name: "displayName" hidden: true element: outputDiv onDelete = => searchField.show() outputField.hide() cleanData() searchField.reload() CUI.Events.trigger node: searchField type: "editor-changed" showOutputField = => card = @__renderOutput( data: formData editor: true onDelete: onDelete onModify: => id = formData.gazId onDelete() searchData.q = id searchField.reload() search() ) CUI.dom.replace(outputDiv, card) outputField.show() cleanData = => delete formData.displayName delete formData.gazId delete formData.otherNames delete formData.types delete formData.position delete formData.iconName setData = (object) => searchData.q = "" ez5.GazetteerUtil.setObjectData(formData, object) searchXHR = null search = => searchXHR?.abort() autocompletionPopup.emptyContainer(resultsContainer) autocompletionPopup.emptyContainer(loadingContainer) autocompletionPopup.emptyContainer(noResultsContainer) if searchData.q.length == 0 # Trigger search when it is not empty. return autocompletionPopup.getContainer(loadingContainer).replace(loadingLabel) autocompletionPopup.show() searchXHR = new CUI.XHR method: "GET" url: ez5.GazetteerUtil.SEARCH_API_URL + CUI.encodeUrlData(searchData) searchXHR.start().done((data) => autocompletionPopup.emptyContainer(loadingContainer) if data.result?.length == 0 autocompletionPopup.getContainer(noResultsContainer).replace(noResultsLabel) return for object in data.result do(object) => item = autocompletionPopup.appendItem(resultsContainer, @__renderAutocompleteCard(object) ) CUI.Events.listen type: "click" node: item call: (ev) => ev.stopPropagation() if object setData(object) else cleanData() searchField.hide() showOutputField() autocompletionPopup.hide() CUI.Events.trigger node: searchField type: "editor-changed" return CUI.Events.trigger type: "content-resize" node: autocompletionPopup ) if CUI.util.isEmpty(formData) or formData.notFound or not formData.gazId searchField.show() else showOutputField() [searchField, outputField] __initData: (data) -> if not data[@name()] initData = {} data[@name()] = initData else initData = data[@name()] initData __renderOutput: (opts) -> formData = opts.data if formData.notFound return new CUI.EmptyLabel(text: $$("custom.data.type.gazetteer.preview.id-not-found"), class: "ez-label-invalid") if formData.gazId return @__renderCard(opts) else return new CUI.EmptyLabel(text: $$("custom.data.type.gazetteer.preview.empty-label")) __renderAutocompleteCard: (data) -> object = {} ez5.GazetteerUtil.setObjectData(object, data) @__renderCard( data: object small: true ) __renderCard: (_opts) -> opts = CUI.Element.readOpts(_opts, "CustomDataTypeGazetteer.__renderCard", data: check: "PlainObject" mandatory: true editor: check: Boolean default: false small: check: Boolean default: false onlyText: check: Boolean default: false onDelete: check: Function onModify: check: Function ) {data, editor, small, onDelete, onModify, onlyText} = opts content = [ new CUI.Label(text: data.displayName, appearance: "title", multiline: true) ] if onlyText return content[0] link = ez5.GazetteerUtil.PLACE_URL + data.gazId menuItems = [ new LocaButtonHref loca_key: "custom<KEY>.data<KEY>.type<KEY>.gazetteer.<KEY>" href: link target: "_blank" ] if not small if CUI.Map.isValidPosition(data.position) menuItems.push( new LocaButton loca_key: "custom.<KEY>etteer.preview.button" onClick: => previewPopover = new CUI.Popover element: menuButton placement: "sw" pane: @__buildPreviewMap(data.position, data.iconName) onHide: => previewPopover.destroy() previewPopover.show() ) if editor menuItems.push( new LocaButton loca_key: "custom.<KEY>azetteer<KEY>.delete.<KEY>" onClick: => onDelete?() ) menuItems.push( new LocaButton loca_key: "custom.<KEY>type<KEY>.gazetteer<KEY>.modify.<KEY>" onClick: => onModify?() ) menuButton = new LocaButton loca_key: "custom.<KEY>etteer.<KEY>" icon: "ellipsis_v" icon_right: false appearance: "flat" menu: items: menuItems if data.types types = [] for type in data.types types.push $$("custom.data.type.gazetteer.types.#{type}.text") content.push new CUI.Label(text: types.join(", "), appearance: "secondary") if not CUI.util.isEmpty(data.otherNames) and ez5.session.config.base.system.gazetteer_plugin_settings?.show_alternative_names otherNameLabels = [] showingMore = false showMoreLessButton = new CUI.Button text: "" appearance: "link" size: "mini" onClick: => if showingMore showLess() else showMore() showingMore = not showingMore CUI.dom.hideElement(showMoreLessButton) showLess = () -> for label in otherNameLabels CUI.dom.hideElement(label) for level in [0..3] by 1 if not otherNameLabels[level] continue CUI.dom.showElement(otherNameLabels[level]) if otherNameLabels.length > 4 showMoreLessButton.setText($$("custom.data.type.gazetteer.types.card.show-more-button")) CUI.dom.showElement(showMoreLessButton) return showMore = () -> for label in otherNameLabels CUI.dom.showElement(label) showMoreLessButton.setText($$("custom.data.type.gazetteer.types.card.show-less-button")) return otherNames = data.otherNames.map((otherName) -> otherName.title) for otherName in otherNames otherNameLabels.push(new CUI.Label(text: otherName, appearance: "secondary")) showLess() verticalListContent = if small then otherNameLabels else otherNameLabels.concat([showMoreLessButton]) verticalList = new CUI.VerticalList(content: verticalListContent) content.push(verticalList) if not CUI.util.isEmpty(data.position) and ez5.session.config.base.system.gazetteer_plugin_settings?.show_lat_lng content.push(new CUI.Label(text: $$("custom.data.type.gazetteer.types.latitude_longitude.text", data.position), appearance: "secondary")) list = new CUI.VerticalList(content: content) if small return list else plugin = ez5.pluginManager.getPlugin("custom-data-type-gazetteer") previewImage = new Image(36, 36) previewImage.src = plugin.getBaseURL() + plugin.getWebfrontend().logo return new CUI.HorizontalLayout( class: "ez5-field-object ez5-custom-data-type-gazetteer-card" left: content: previewImage center: content: list right: content: menuButton ) __buildPreviewMap: (position, iconName) -> return new CUI.MapInput.defaults.mapClass( selectedMarkerPosition: position selectedMarkerOptions: iconName: iconName iconColor: "#6786ad" centerPosition: position clickable: false zoom: 10 ) # This is the case that the ID is in the data but it was not found before. __fillMissingData: (data) -> if data.gazId and (not data.displayName or not data.types) deferred = new CUI.Deferred() ez5.GazetteerUtil.searchById(data.gazId).done((dataFound) => ez5.GazetteerUtil.setObjectData(data, dataFound) ).fail( => data.notFound = true ).always(deferred.resolve) return deferred.promise() else return CUI.resolvedPromise() isPluginSupported: (plugin) -> if plugin instanceof MapDetailPlugin return true return false CustomDataType.register(CustomDataTypeGazetteer)
true
class CustomDataTypeGazetteer extends CustomDataType getCustomDataTypeName: -> "custom:base.custom-data-type-gazetteer.gazetteer" getCustomDataTypeNameLocalized: -> $$("custom.data.type.gazetteer.name") getCustomDataOptionsInDatamodelInfo: (custom_settings) -> return [] supportsStandard: -> true renderSearchInput: (data, opts={}) -> return new SearchToken( column: @ data: data fields: opts.fields ).getInput().DOM getFieldNamesForSearch: -> @__getFieldNames() getFieldNamesForSuggest: -> @__getFieldNames() renderEditorInput: (data) -> initData = @__initData(data) content = CUI.dom.div() waitBlock = new CUI.WaitBlock(element: content) setContent = => [searchInput, displayOutput] = @__initForm(initData) searchInput.start() displayOutput.start() CUI.dom.append(content, searchInput) CUI.dom.append(content, displayOutput) waitBlock.destroy() waitBlock.show() @__fillMissingData(initData).done(setContent) return content renderTableOutput: (data, _, opts) -> initData = @__initData(data) content = @__renderOutput( data: initData onlyText: true ) return content renderDetailOutput: (data, _, opts) -> initData = @__initData(data) content = CUI.dom.div() waitBlock = new CUI.WaitBlock(element: content) setContent = => outputFieldElement = @__renderOutput(data: initData) CUI.dom.replace(content, outputFieldElement) waitBlock.destroy() if CUI.Map.isValidPosition(initData.position) and opts.detail plugins = opts.detail.getPlugins() for plugin in plugins if plugin instanceof MapDetailPlugin mapPlugin = plugin break if mapPlugin mapPlugin.addMarker(position: initData.position, iconName: initData.iconName, iconColor: "#6786ad") waitBlock.show() @__fillMissingData(initData).done(setContent) CUI.Events.listen type: "map-detail-click-location" node: content call: (_, info) => if info.data?.position == initData.position CUI.dom.scrollIntoView(content) return content renderFieldAsGroup: -> return false getSaveData: (data, save_data) -> data = data[@name()] if CUI.util.isEmpty(data) return save_data[@name()] = null if CUI.util.isEmpty(data.gazId) return save_data[@name()] = null if data.notFound return throw new InvalidSaveDataException() return save_data[@name()] = ez5.GazetteerUtil.getSaveDataObject(data) getQueryFieldBadge: (data) => if data["#{@name()}:unset"] value = $$("text.column.badge.without") else value = data[@name()] name: @nameLocalized() value: value getSearchFilter: (data, key=@name()) -> if data[key+":unset"] filter = type: "in" fields: [ @fullName()+".displayName" ] in: [ null ] filter._unnest = true filter._unset_filter = true return filter filter = super(data, key) if filter return filter if CUI.util.isEmpty(data[key]) return val = data[key] [str, phrase] = Search.getPhrase(val) switch data[key+":type"] when "token", "fulltext", undefined filter = type: "match" mode: data[key+":mode"] fields: @getFieldNamesForSearch() string: str phrase: phrase when "field" filter = type: "in" fields: @getFieldNamesForSearch() in: [ str ] filter __getFieldNames: -> return [ @fullName()+".gazId" @fullName()+".displayName" ] __initForm: (formData) -> searchData = q: "" resultsContainer = "results" loadingContainer = "loading" noResultsContainer = "no_results" loadingLabel = new LocaLabel(loca_key: "autocompletion.loading", padded: true) noResultsLabel = new LocaLabel(loca_key: "custom.data.type.gazetteer.search.no-results", padded: true) searchField = new CUI.Input name: "q" hidden: true placeholder: $$("custom.data.type.gazetteer.search.placeholder") maximize_horizontal: true data: searchData onDataChanged: => CUI.scheduleCallback ms: 200 call: search autocompletionPopup = new AutocompletionPopup element: searchField onHide: => autocompletionPopup.hide() autocompletionPopup.addContainer(resultsContainer) autocompletionPopup.addContainer(loadingContainer) autocompletionPopup.addContainer(noResultsContainer) outputDiv = CUI.dom.div() outputField = new CUI.DataFieldProxy name: "displayName" hidden: true element: outputDiv onDelete = => searchField.show() outputField.hide() cleanData() searchField.reload() CUI.Events.trigger node: searchField type: "editor-changed" showOutputField = => card = @__renderOutput( data: formData editor: true onDelete: onDelete onModify: => id = formData.gazId onDelete() searchData.q = id searchField.reload() search() ) CUI.dom.replace(outputDiv, card) outputField.show() cleanData = => delete formData.displayName delete formData.gazId delete formData.otherNames delete formData.types delete formData.position delete formData.iconName setData = (object) => searchData.q = "" ez5.GazetteerUtil.setObjectData(formData, object) searchXHR = null search = => searchXHR?.abort() autocompletionPopup.emptyContainer(resultsContainer) autocompletionPopup.emptyContainer(loadingContainer) autocompletionPopup.emptyContainer(noResultsContainer) if searchData.q.length == 0 # Trigger search when it is not empty. return autocompletionPopup.getContainer(loadingContainer).replace(loadingLabel) autocompletionPopup.show() searchXHR = new CUI.XHR method: "GET" url: ez5.GazetteerUtil.SEARCH_API_URL + CUI.encodeUrlData(searchData) searchXHR.start().done((data) => autocompletionPopup.emptyContainer(loadingContainer) if data.result?.length == 0 autocompletionPopup.getContainer(noResultsContainer).replace(noResultsLabel) return for object in data.result do(object) => item = autocompletionPopup.appendItem(resultsContainer, @__renderAutocompleteCard(object) ) CUI.Events.listen type: "click" node: item call: (ev) => ev.stopPropagation() if object setData(object) else cleanData() searchField.hide() showOutputField() autocompletionPopup.hide() CUI.Events.trigger node: searchField type: "editor-changed" return CUI.Events.trigger type: "content-resize" node: autocompletionPopup ) if CUI.util.isEmpty(formData) or formData.notFound or not formData.gazId searchField.show() else showOutputField() [searchField, outputField] __initData: (data) -> if not data[@name()] initData = {} data[@name()] = initData else initData = data[@name()] initData __renderOutput: (opts) -> formData = opts.data if formData.notFound return new CUI.EmptyLabel(text: $$("custom.data.type.gazetteer.preview.id-not-found"), class: "ez-label-invalid") if formData.gazId return @__renderCard(opts) else return new CUI.EmptyLabel(text: $$("custom.data.type.gazetteer.preview.empty-label")) __renderAutocompleteCard: (data) -> object = {} ez5.GazetteerUtil.setObjectData(object, data) @__renderCard( data: object small: true ) __renderCard: (_opts) -> opts = CUI.Element.readOpts(_opts, "CustomDataTypeGazetteer.__renderCard", data: check: "PlainObject" mandatory: true editor: check: Boolean default: false small: check: Boolean default: false onlyText: check: Boolean default: false onDelete: check: Function onModify: check: Function ) {data, editor, small, onDelete, onModify, onlyText} = opts content = [ new CUI.Label(text: data.displayName, appearance: "title", multiline: true) ] if onlyText return content[0] link = ez5.GazetteerUtil.PLACE_URL + data.gazId menuItems = [ new LocaButtonHref loca_key: "customPI:KEY:<KEY>END_PI.dataPI:KEY:<KEY>END_PI.typePI:KEY:<KEY>END_PI.gazetteer.PI:KEY:<KEY>END_PI" href: link target: "_blank" ] if not small if CUI.Map.isValidPosition(data.position) menuItems.push( new LocaButton loca_key: "custom.PI:KEY:<KEY>END_PIetteer.preview.button" onClick: => previewPopover = new CUI.Popover element: menuButton placement: "sw" pane: @__buildPreviewMap(data.position, data.iconName) onHide: => previewPopover.destroy() previewPopover.show() ) if editor menuItems.push( new LocaButton loca_key: "custom.PI:KEY:<KEY>END_PIazetteerPI:KEY:<KEY>END_PI.delete.PI:KEY:<KEY>END_PI" onClick: => onDelete?() ) menuItems.push( new LocaButton loca_key: "custom.PI:KEY:<KEY>END_PItypePI:KEY:<KEY>END_PI.gazetteerPI:KEY:<KEY>END_PI.modify.PI:KEY:<KEY>END_PI" onClick: => onModify?() ) menuButton = new LocaButton loca_key: "custom.PI:KEY:<KEY>END_PIetteer.PI:KEY:<KEY>END_PI" icon: "ellipsis_v" icon_right: false appearance: "flat" menu: items: menuItems if data.types types = [] for type in data.types types.push $$("custom.data.type.gazetteer.types.#{type}.text") content.push new CUI.Label(text: types.join(", "), appearance: "secondary") if not CUI.util.isEmpty(data.otherNames) and ez5.session.config.base.system.gazetteer_plugin_settings?.show_alternative_names otherNameLabels = [] showingMore = false showMoreLessButton = new CUI.Button text: "" appearance: "link" size: "mini" onClick: => if showingMore showLess() else showMore() showingMore = not showingMore CUI.dom.hideElement(showMoreLessButton) showLess = () -> for label in otherNameLabels CUI.dom.hideElement(label) for level in [0..3] by 1 if not otherNameLabels[level] continue CUI.dom.showElement(otherNameLabels[level]) if otherNameLabels.length > 4 showMoreLessButton.setText($$("custom.data.type.gazetteer.types.card.show-more-button")) CUI.dom.showElement(showMoreLessButton) return showMore = () -> for label in otherNameLabels CUI.dom.showElement(label) showMoreLessButton.setText($$("custom.data.type.gazetteer.types.card.show-less-button")) return otherNames = data.otherNames.map((otherName) -> otherName.title) for otherName in otherNames otherNameLabels.push(new CUI.Label(text: otherName, appearance: "secondary")) showLess() verticalListContent = if small then otherNameLabels else otherNameLabels.concat([showMoreLessButton]) verticalList = new CUI.VerticalList(content: verticalListContent) content.push(verticalList) if not CUI.util.isEmpty(data.position) and ez5.session.config.base.system.gazetteer_plugin_settings?.show_lat_lng content.push(new CUI.Label(text: $$("custom.data.type.gazetteer.types.latitude_longitude.text", data.position), appearance: "secondary")) list = new CUI.VerticalList(content: content) if small return list else plugin = ez5.pluginManager.getPlugin("custom-data-type-gazetteer") previewImage = new Image(36, 36) previewImage.src = plugin.getBaseURL() + plugin.getWebfrontend().logo return new CUI.HorizontalLayout( class: "ez5-field-object ez5-custom-data-type-gazetteer-card" left: content: previewImage center: content: list right: content: menuButton ) __buildPreviewMap: (position, iconName) -> return new CUI.MapInput.defaults.mapClass( selectedMarkerPosition: position selectedMarkerOptions: iconName: iconName iconColor: "#6786ad" centerPosition: position clickable: false zoom: 10 ) # This is the case that the ID is in the data but it was not found before. __fillMissingData: (data) -> if data.gazId and (not data.displayName or not data.types) deferred = new CUI.Deferred() ez5.GazetteerUtil.searchById(data.gazId).done((dataFound) => ez5.GazetteerUtil.setObjectData(data, dataFound) ).fail( => data.notFound = true ).always(deferred.resolve) return deferred.promise() else return CUI.resolvedPromise() isPluginSupported: (plugin) -> if plugin instanceof MapDetailPlugin return true return false CustomDataType.register(CustomDataTypeGazetteer)
[ { "context": "# LogAll(@gui)\n\nclass @SampleApp\n fullname = \"Sample Application\"\n description = \"Oh ... you just rea", "end": 7517, "score": 0.6902454495429993, "start": 7511, "tag": "NAME", "value": "Sample" }, { "context": " ... you just read app description.\"\n @fulln...
app/assets/javascripts/sa.js.coffee
CoffeeDesktop/coffeedesktop-rails
0
#Warning: This code contains ugly this #Warning: You have been warned about this #= require gui #= require glue #= require localstorage #= require usecase class Templates main: -> "<div id='tabs'> <ul> <li><a href='#tabs-1'>About</a></li> <li><a href='#tabs-2'>Desktop Icons</a></li> <li><a href='#tabs-3'>Notifications</a></li> <li><a href='#tabs-4'>Child windows</a></li> </ul> <div id='tabs-1'> <p>Hi, Welcome to sample application.</p> <p>You can find here some examples what you can do with CoffeeDesktop!</p> <p>Checkout other tabs!... NOW!</p> <p>shoo...shoo go to other tabs and checkout cool features!</p> </div> <div id='tabs-2'> <p>You can create awesome links with coffeedesktop ... just put objects in cart</p> <p>This is example:</p> <img src='/assets/icons/app.png' desktop_object_options='' desktop_object_run='sa link' desktop_object_fullname='SA Show hidden' desktop_object_icon='app.png' class=' i_wanna_be_a_desktop_object sa_drag_button'>DRAG THIS ON DESKTOP PLIZ </div> <div id='tabs-3'> <p>You can do shiny awesome notifications with CoffeeDesktop... just puting json to CoffeeDesktop.notes.add(json) and have fun <p style='text-align:center'><button class='notify_try_button'>TRY ME</button></p> <p>Also there is notifications about network errors</p> <p style='text-align:center'><button class='notify_error_try_button'>Send Something stupid</button></p> </div> <div id='tabs-4'> <p>You can open child windows for application <p style='text-align:center'><button class='child_try_button'>TRY ME</button></p> <p>Also application can control child windows</p> <p style='text-align:center'><button class='close_all_childs_try_button'>Close all child windows</button></p> <p>You Can even update child windows content<p> <p style='text-align:center'><button class='update_first_child_try_button'>Update First child</button></p> </div> </div>" secret: -> "YAY ... you just found secret link <img src='http://25.media.tumblr.com/tumblr_m9a3bqANob1retw4jo1_500.gif'>" link: -> "Yay you are amazing... you just tested creating desktop icons <img src='http://images.wikia.com/creepypasta/images/3/38/Adventure-time-with-finn-and-jake.jpg'>" childwindow: -> "This is childwindow" updated_child: -> "<h1>I WAS UPDATED!</h1><br> The bindings still works <p style='text-align:center'><button class='updated_child_try_button'>Update First child</button></p>" class Backend constructor: () -> stupidPost: -> $.post("/coffeedesktop/stupid_post" ); class LocalStorage extends @LocalStorageClass class UseCase extends @UseCaseClass constructor: (@gui) -> @windows = [] registerWindow: (id) -> @windows.push(id) closeAllChildWindows: => while @windows.length >0 @gui.closeWindow(@windows[0]) removeWindow: (window) => if (@windows.indexOf(window)) > -1 @windows.splice(@windows.indexOf(window), 1) updateFirstChildWindow: -> @gui.updateChild(@windows[0]) exitSignal: -> @gui.closeMainWindow() start: (args) => switch when /secret/i.test(args) options = { title: 'Secret undiscovered', text: 'Someone here discover secret! :D<br> He or She must love adventures!', image: 'http://img-cache.cdn.gaiaonline.com/cfc29eb51f1f53134577339fb5af37e9/http://i1063.photobucket.com/albums/t501/TedBenic/Icons/Avatars/CAR_ATM_FINN2.jpg' } CoffeeDesktop.notes.addNote(options) @gui.createWindow("Sample Application (secret)","secret") when /link/i.test(args) @gui.createWindow("Sample Application link","link") else @gui.createWindow("Sample Application","main") class Gui extends @GuiClass constructor: (@templates) -> createWindow: (title=false,template="main") => rand=UUIDjs.randomUI48() id=UUIDjs.randomUI48() if !id #if undefined just throw sth random div_id = id+"-"+rand $.newWindow({id:div_id,title:title,width:500,height:350}) $.updateWindowContent(div_id,@templates[template]()) if template == "main" | template == "secret" @div_id = div_id @element = $("##{@div_id}") $("##{div_id} .window-closeButton").click( => @exitApp() @closeAllChildWindows() ) else @registerWindow(div_id) $("##{div_id} .window-closeButton").click( =>@removeWindow(div_id)) @setBindings(template,div_id) closeWindow: (id) -> console.log "closing window #{id}" $.closeWindow(id) @removeWindow(id) updateChild: (id) -> $.updateWindowContent(id,@templates.updated_child()) @setBindings('updated_child',id) setBindings: (template,div_id) -> if template == "main" $( "##{div_id} #tabs" ).tabs() $( "##{div_id} .sa_drag_button" ).button() $( "##{div_id} .notify_try_button").click( => options = { title: 'Woohoo! You did it!', text: 'You just clicked notification testing button!', image: 'http://24.media.tumblr.com/avatar_cebb9d5a6d1d_128.png' } CoffeeDesktop.notes.addNote(options) $("##{div_id} .window-titleBar-content")[0].innerHTML = "Changed Title too" $("##{div_id} .window-titleBar-content").trigger('contentchanged'); ) $( "##{div_id} .notify_error_try_button").click( => @sendStupidPost()) $( "##{div_id} .child_try_button").click( => @openChildWindow()) $( "##{div_id} .close_all_childs_try_button").click( => @closeAllChildWindows()) $( "##{div_id} .update_first_child_try_button").click( => @updateFirstChildWindow()) $( "##{div_id} .sa_drag_button" ).draggable( helper: "clone", revert: "invalid", appendTo: 'body' start: -> $(this).css("z-index", 999999999) ) else if template == "updated_child" $( "##{div_id} .updated_child_try_button").click( => options = { title: 'child window', text: 'Woohoo bindings still works', image: 'http://24.media.tumblr.com/avatar_cebb9d5a6d1d_128.png' } CoffeeDesktop.notes.addNote(options) ) closeMainWindow: -> $("##{@div_id} .window-closeButton").click() openChildWindow: -> @createWindow("Child window","childwindow") #aop events sendStupidPost: -> registerWindow: (id) -> closeAllChildWindows: -> updateFirstChildWindow: -> removeWindow: (id) -> exitApp: -> class Glue extends @GlueClass constructor: (@useCase, @gui, @storage, @app, @backend) -> After(@gui, 'registerWindow', (id) => @useCase.registerWindow(id)) After(@gui, 'closeAllChildWindows', => @useCase.closeAllChildWindows()) After(@gui, 'updateFirstChildWindow', => @useCase.updateFirstChildWindow()) After(@gui, 'removeWindow', (id) => @useCase.removeWindow(id)) After(@gui, 'sendStupidPost', => @backend.stupidPost()) # this is only once shortcut because it's stupid to do stupid post over usecase After(@gui, 'exitApp', => @app.exitApp()) After(@app, 'exitSignal', => @useCase.exitSignal()) # LogAll(@useCase) # LogAll(@gui) class @SampleApp fullname = "Sample Application" description = "Oh ... you just read app description." @fullname = fullname @description = description exitSignal: -> exitApp: -> CoffeeDesktop.processKill(@id) getDivID: -> @gui.div_id constructor: (@id, args) -> console.log("OH COOL ... I have just recived new shining fucks to take") if args @fullname = fullname @description = description templates = new Templates() backend = new Backend() @gui = new Gui(templates) useCase = new UseCase(@gui) localStorage = new LocalStorage("CoffeeDesktop") #probably this under this line is temporary this because this isnt on the path of truth glue = new Glue(useCase, @gui, localStorage,this,backend) # ^ this this is this ugly this useCase.start(args) window.sa = {} window.sa.UseCase = UseCase window.sa.Gui = Gui window.sa.Templates = Templates window.sa.SampleApp = SampleApp window.CoffeeDesktop.appAdd('sa',@SampleApp, '{"Im not a secret button":"sa secret"}')
5582
#Warning: This code contains ugly this #Warning: You have been warned about this #= require gui #= require glue #= require localstorage #= require usecase class Templates main: -> "<div id='tabs'> <ul> <li><a href='#tabs-1'>About</a></li> <li><a href='#tabs-2'>Desktop Icons</a></li> <li><a href='#tabs-3'>Notifications</a></li> <li><a href='#tabs-4'>Child windows</a></li> </ul> <div id='tabs-1'> <p>Hi, Welcome to sample application.</p> <p>You can find here some examples what you can do with CoffeeDesktop!</p> <p>Checkout other tabs!... NOW!</p> <p>shoo...shoo go to other tabs and checkout cool features!</p> </div> <div id='tabs-2'> <p>You can create awesome links with coffeedesktop ... just put objects in cart</p> <p>This is example:</p> <img src='/assets/icons/app.png' desktop_object_options='' desktop_object_run='sa link' desktop_object_fullname='SA Show hidden' desktop_object_icon='app.png' class=' i_wanna_be_a_desktop_object sa_drag_button'>DRAG THIS ON DESKTOP PLIZ </div> <div id='tabs-3'> <p>You can do shiny awesome notifications with CoffeeDesktop... just puting json to CoffeeDesktop.notes.add(json) and have fun <p style='text-align:center'><button class='notify_try_button'>TRY ME</button></p> <p>Also there is notifications about network errors</p> <p style='text-align:center'><button class='notify_error_try_button'>Send Something stupid</button></p> </div> <div id='tabs-4'> <p>You can open child windows for application <p style='text-align:center'><button class='child_try_button'>TRY ME</button></p> <p>Also application can control child windows</p> <p style='text-align:center'><button class='close_all_childs_try_button'>Close all child windows</button></p> <p>You Can even update child windows content<p> <p style='text-align:center'><button class='update_first_child_try_button'>Update First child</button></p> </div> </div>" secret: -> "YAY ... you just found secret link <img src='http://25.media.tumblr.com/tumblr_m9a3bqANob1retw4jo1_500.gif'>" link: -> "Yay you are amazing... you just tested creating desktop icons <img src='http://images.wikia.com/creepypasta/images/3/38/Adventure-time-with-finn-and-jake.jpg'>" childwindow: -> "This is childwindow" updated_child: -> "<h1>I WAS UPDATED!</h1><br> The bindings still works <p style='text-align:center'><button class='updated_child_try_button'>Update First child</button></p>" class Backend constructor: () -> stupidPost: -> $.post("/coffeedesktop/stupid_post" ); class LocalStorage extends @LocalStorageClass class UseCase extends @UseCaseClass constructor: (@gui) -> @windows = [] registerWindow: (id) -> @windows.push(id) closeAllChildWindows: => while @windows.length >0 @gui.closeWindow(@windows[0]) removeWindow: (window) => if (@windows.indexOf(window)) > -1 @windows.splice(@windows.indexOf(window), 1) updateFirstChildWindow: -> @gui.updateChild(@windows[0]) exitSignal: -> @gui.closeMainWindow() start: (args) => switch when /secret/i.test(args) options = { title: 'Secret undiscovered', text: 'Someone here discover secret! :D<br> He or She must love adventures!', image: 'http://img-cache.cdn.gaiaonline.com/cfc29eb51f1f53134577339fb5af37e9/http://i1063.photobucket.com/albums/t501/TedBenic/Icons/Avatars/CAR_ATM_FINN2.jpg' } CoffeeDesktop.notes.addNote(options) @gui.createWindow("Sample Application (secret)","secret") when /link/i.test(args) @gui.createWindow("Sample Application link","link") else @gui.createWindow("Sample Application","main") class Gui extends @GuiClass constructor: (@templates) -> createWindow: (title=false,template="main") => rand=UUIDjs.randomUI48() id=UUIDjs.randomUI48() if !id #if undefined just throw sth random div_id = id+"-"+rand $.newWindow({id:div_id,title:title,width:500,height:350}) $.updateWindowContent(div_id,@templates[template]()) if template == "main" | template == "secret" @div_id = div_id @element = $("##{@div_id}") $("##{div_id} .window-closeButton").click( => @exitApp() @closeAllChildWindows() ) else @registerWindow(div_id) $("##{div_id} .window-closeButton").click( =>@removeWindow(div_id)) @setBindings(template,div_id) closeWindow: (id) -> console.log "closing window #{id}" $.closeWindow(id) @removeWindow(id) updateChild: (id) -> $.updateWindowContent(id,@templates.updated_child()) @setBindings('updated_child',id) setBindings: (template,div_id) -> if template == "main" $( "##{div_id} #tabs" ).tabs() $( "##{div_id} .sa_drag_button" ).button() $( "##{div_id} .notify_try_button").click( => options = { title: 'Woohoo! You did it!', text: 'You just clicked notification testing button!', image: 'http://24.media.tumblr.com/avatar_cebb9d5a6d1d_128.png' } CoffeeDesktop.notes.addNote(options) $("##{div_id} .window-titleBar-content")[0].innerHTML = "Changed Title too" $("##{div_id} .window-titleBar-content").trigger('contentchanged'); ) $( "##{div_id} .notify_error_try_button").click( => @sendStupidPost()) $( "##{div_id} .child_try_button").click( => @openChildWindow()) $( "##{div_id} .close_all_childs_try_button").click( => @closeAllChildWindows()) $( "##{div_id} .update_first_child_try_button").click( => @updateFirstChildWindow()) $( "##{div_id} .sa_drag_button" ).draggable( helper: "clone", revert: "invalid", appendTo: 'body' start: -> $(this).css("z-index", 999999999) ) else if template == "updated_child" $( "##{div_id} .updated_child_try_button").click( => options = { title: 'child window', text: 'Woohoo bindings still works', image: 'http://24.media.tumblr.com/avatar_cebb9d5a6d1d_128.png' } CoffeeDesktop.notes.addNote(options) ) closeMainWindow: -> $("##{@div_id} .window-closeButton").click() openChildWindow: -> @createWindow("Child window","childwindow") #aop events sendStupidPost: -> registerWindow: (id) -> closeAllChildWindows: -> updateFirstChildWindow: -> removeWindow: (id) -> exitApp: -> class Glue extends @GlueClass constructor: (@useCase, @gui, @storage, @app, @backend) -> After(@gui, 'registerWindow', (id) => @useCase.registerWindow(id)) After(@gui, 'closeAllChildWindows', => @useCase.closeAllChildWindows()) After(@gui, 'updateFirstChildWindow', => @useCase.updateFirstChildWindow()) After(@gui, 'removeWindow', (id) => @useCase.removeWindow(id)) After(@gui, 'sendStupidPost', => @backend.stupidPost()) # this is only once shortcut because it's stupid to do stupid post over usecase After(@gui, 'exitApp', => @app.exitApp()) After(@app, 'exitSignal', => @useCase.exitSignal()) # LogAll(@useCase) # LogAll(@gui) class @SampleApp fullname = "<NAME> Application" description = "Oh ... you just read app description." @fullname = <NAME> @description = description exitSignal: -> exitApp: -> CoffeeDesktop.processKill(@id) getDivID: -> @gui.div_id constructor: (@id, args) -> console.log("OH COOL ... I have just recived new shining fucks to take") if args @fullname = <NAME> @description = description templates = new Templates() backend = new Backend() @gui = new Gui(templates) useCase = new UseCase(@gui) localStorage = new LocalStorage("CoffeeDesktop") #probably this under this line is temporary this because this isnt on the path of truth glue = new Glue(useCase, @gui, localStorage,this,backend) # ^ this this is this ugly this useCase.start(args) window.sa = {} window.sa.UseCase = UseCase window.sa.Gui = Gui window.sa.Templates = Templates window.sa.SampleApp = SampleApp window.CoffeeDesktop.appAdd('sa',@SampleApp, '{"Im not a secret button":"sa secret"}')
true
#Warning: This code contains ugly this #Warning: You have been warned about this #= require gui #= require glue #= require localstorage #= require usecase class Templates main: -> "<div id='tabs'> <ul> <li><a href='#tabs-1'>About</a></li> <li><a href='#tabs-2'>Desktop Icons</a></li> <li><a href='#tabs-3'>Notifications</a></li> <li><a href='#tabs-4'>Child windows</a></li> </ul> <div id='tabs-1'> <p>Hi, Welcome to sample application.</p> <p>You can find here some examples what you can do with CoffeeDesktop!</p> <p>Checkout other tabs!... NOW!</p> <p>shoo...shoo go to other tabs and checkout cool features!</p> </div> <div id='tabs-2'> <p>You can create awesome links with coffeedesktop ... just put objects in cart</p> <p>This is example:</p> <img src='/assets/icons/app.png' desktop_object_options='' desktop_object_run='sa link' desktop_object_fullname='SA Show hidden' desktop_object_icon='app.png' class=' i_wanna_be_a_desktop_object sa_drag_button'>DRAG THIS ON DESKTOP PLIZ </div> <div id='tabs-3'> <p>You can do shiny awesome notifications with CoffeeDesktop... just puting json to CoffeeDesktop.notes.add(json) and have fun <p style='text-align:center'><button class='notify_try_button'>TRY ME</button></p> <p>Also there is notifications about network errors</p> <p style='text-align:center'><button class='notify_error_try_button'>Send Something stupid</button></p> </div> <div id='tabs-4'> <p>You can open child windows for application <p style='text-align:center'><button class='child_try_button'>TRY ME</button></p> <p>Also application can control child windows</p> <p style='text-align:center'><button class='close_all_childs_try_button'>Close all child windows</button></p> <p>You Can even update child windows content<p> <p style='text-align:center'><button class='update_first_child_try_button'>Update First child</button></p> </div> </div>" secret: -> "YAY ... you just found secret link <img src='http://25.media.tumblr.com/tumblr_m9a3bqANob1retw4jo1_500.gif'>" link: -> "Yay you are amazing... you just tested creating desktop icons <img src='http://images.wikia.com/creepypasta/images/3/38/Adventure-time-with-finn-and-jake.jpg'>" childwindow: -> "This is childwindow" updated_child: -> "<h1>I WAS UPDATED!</h1><br> The bindings still works <p style='text-align:center'><button class='updated_child_try_button'>Update First child</button></p>" class Backend constructor: () -> stupidPost: -> $.post("/coffeedesktop/stupid_post" ); class LocalStorage extends @LocalStorageClass class UseCase extends @UseCaseClass constructor: (@gui) -> @windows = [] registerWindow: (id) -> @windows.push(id) closeAllChildWindows: => while @windows.length >0 @gui.closeWindow(@windows[0]) removeWindow: (window) => if (@windows.indexOf(window)) > -1 @windows.splice(@windows.indexOf(window), 1) updateFirstChildWindow: -> @gui.updateChild(@windows[0]) exitSignal: -> @gui.closeMainWindow() start: (args) => switch when /secret/i.test(args) options = { title: 'Secret undiscovered', text: 'Someone here discover secret! :D<br> He or She must love adventures!', image: 'http://img-cache.cdn.gaiaonline.com/cfc29eb51f1f53134577339fb5af37e9/http://i1063.photobucket.com/albums/t501/TedBenic/Icons/Avatars/CAR_ATM_FINN2.jpg' } CoffeeDesktop.notes.addNote(options) @gui.createWindow("Sample Application (secret)","secret") when /link/i.test(args) @gui.createWindow("Sample Application link","link") else @gui.createWindow("Sample Application","main") class Gui extends @GuiClass constructor: (@templates) -> createWindow: (title=false,template="main") => rand=UUIDjs.randomUI48() id=UUIDjs.randomUI48() if !id #if undefined just throw sth random div_id = id+"-"+rand $.newWindow({id:div_id,title:title,width:500,height:350}) $.updateWindowContent(div_id,@templates[template]()) if template == "main" | template == "secret" @div_id = div_id @element = $("##{@div_id}") $("##{div_id} .window-closeButton").click( => @exitApp() @closeAllChildWindows() ) else @registerWindow(div_id) $("##{div_id} .window-closeButton").click( =>@removeWindow(div_id)) @setBindings(template,div_id) closeWindow: (id) -> console.log "closing window #{id}" $.closeWindow(id) @removeWindow(id) updateChild: (id) -> $.updateWindowContent(id,@templates.updated_child()) @setBindings('updated_child',id) setBindings: (template,div_id) -> if template == "main" $( "##{div_id} #tabs" ).tabs() $( "##{div_id} .sa_drag_button" ).button() $( "##{div_id} .notify_try_button").click( => options = { title: 'Woohoo! You did it!', text: 'You just clicked notification testing button!', image: 'http://24.media.tumblr.com/avatar_cebb9d5a6d1d_128.png' } CoffeeDesktop.notes.addNote(options) $("##{div_id} .window-titleBar-content")[0].innerHTML = "Changed Title too" $("##{div_id} .window-titleBar-content").trigger('contentchanged'); ) $( "##{div_id} .notify_error_try_button").click( => @sendStupidPost()) $( "##{div_id} .child_try_button").click( => @openChildWindow()) $( "##{div_id} .close_all_childs_try_button").click( => @closeAllChildWindows()) $( "##{div_id} .update_first_child_try_button").click( => @updateFirstChildWindow()) $( "##{div_id} .sa_drag_button" ).draggable( helper: "clone", revert: "invalid", appendTo: 'body' start: -> $(this).css("z-index", 999999999) ) else if template == "updated_child" $( "##{div_id} .updated_child_try_button").click( => options = { title: 'child window', text: 'Woohoo bindings still works', image: 'http://24.media.tumblr.com/avatar_cebb9d5a6d1d_128.png' } CoffeeDesktop.notes.addNote(options) ) closeMainWindow: -> $("##{@div_id} .window-closeButton").click() openChildWindow: -> @createWindow("Child window","childwindow") #aop events sendStupidPost: -> registerWindow: (id) -> closeAllChildWindows: -> updateFirstChildWindow: -> removeWindow: (id) -> exitApp: -> class Glue extends @GlueClass constructor: (@useCase, @gui, @storage, @app, @backend) -> After(@gui, 'registerWindow', (id) => @useCase.registerWindow(id)) After(@gui, 'closeAllChildWindows', => @useCase.closeAllChildWindows()) After(@gui, 'updateFirstChildWindow', => @useCase.updateFirstChildWindow()) After(@gui, 'removeWindow', (id) => @useCase.removeWindow(id)) After(@gui, 'sendStupidPost', => @backend.stupidPost()) # this is only once shortcut because it's stupid to do stupid post over usecase After(@gui, 'exitApp', => @app.exitApp()) After(@app, 'exitSignal', => @useCase.exitSignal()) # LogAll(@useCase) # LogAll(@gui) class @SampleApp fullname = "PI:NAME:<NAME>END_PI Application" description = "Oh ... you just read app description." @fullname = PI:NAME:<NAME>END_PI @description = description exitSignal: -> exitApp: -> CoffeeDesktop.processKill(@id) getDivID: -> @gui.div_id constructor: (@id, args) -> console.log("OH COOL ... I have just recived new shining fucks to take") if args @fullname = PI:NAME:<NAME>END_PI @description = description templates = new Templates() backend = new Backend() @gui = new Gui(templates) useCase = new UseCase(@gui) localStorage = new LocalStorage("CoffeeDesktop") #probably this under this line is temporary this because this isnt on the path of truth glue = new Glue(useCase, @gui, localStorage,this,backend) # ^ this this is this ugly this useCase.start(args) window.sa = {} window.sa.UseCase = UseCase window.sa.Gui = Gui window.sa.Templates = Templates window.sa.SampleApp = SampleApp window.CoffeeDesktop.appAdd('sa',@SampleApp, '{"Im not a secret button":"sa secret"}')
[ { "context": "thubUrl: (url) ->\n return true if url.indexOf('git@github.com') is 0\n\n try\n {host} = parseUrl(url)\n ", "end": 6241, "score": 0.9998226165771484, "start": 6227, "tag": "EMAIL", "value": "git@github.com" }, { "context": "loudUrl: (url) ->\n return tr...
lib/bitbucket-file.coffee
mark-adams/open-on-bitbucket
9
Shell = require 'shell' {Range} = require 'atom' parseUrl = require('url').parse formatUrl = require('url').format module.exports = class BitbucketFile # Public @fromPath: (filePath) -> new BitbucketFile(filePath) # Internal constructor: (@filePath) -> [rootDir] = atom.project.relativizePath(@filePath) if rootDir? rootDirIndex = atom.project.getPaths().indexOf(rootDir) @repo = atom.project.getRepositories()[rootDirIndex] # Public open: (lineRange) -> if @isOpenable() @openUrlInBrowser(@blobUrl() + @getLineRangeSuffix(lineRange)) else @reportValidationErrors() # Public openOnMaster: (lineRange) -> if @isOpenable() @openUrlInBrowser(@blobUrlForMaster() + @getLineRangeSuffix(lineRange)) else @reportValidationErrors() # Public blame: (lineRange) -> if @isOpenable(true) @openUrlInBrowser(@blameUrl() + @getLineRangeSuffix(lineRange)) else @reportValidationErrors(true) history: -> if @isOpenable(true) @openUrlInBrowser(@historyUrl()) else @reportValidationErrors(true) copyUrl: (lineRange) -> if @isOpenable() atom.clipboard.write(@shaUrl() + @getLineRangeSuffix(lineRange)) else @reportValidationErrors() openBranchCompare: -> if @isOpenable() @openUrlInBrowser(@branchCompareUrl()) else @reportValidationErrors() openIssues: -> if @isOpenable(true) @openUrlInBrowser(@issuesUrl()) else @reportValidationErrors(true) openRepository: -> if @isOpenable() @openUrlInBrowser(@bitbucketRepoUrl()) else @reportValidationErrors() getLineRangeSuffix: (lineRange) -> if lineRange and atom.config.get('open-on-bitbucket.includeLineNumbersInUrls') lineRange = Range.fromObject(lineRange) startRow = lineRange.start.row + 1 endRow = lineRange.end.row + 1 if startRow is endRow if @isBitbucketCloudUrl(@gitUrl()) then "#cl-#{startRow}" else "##{startRow}" else if @isBitbucketCloudUrl(@gitUrl()) then "#cl-#{startRow}:#{endRow}" else "##{startRow}-#{endRow}" else '' # Public isOpenable: (disallowStash = false) -> @validationErrors(disallowStash).length is 0 # Public validationErrors: (disallowStash) -> unless @repo return ["No repository found for path: #{@filePath}."] unless @gitUrl() return ["No URL defined for remote: #{@remoteName()}"] unless @bitbucketRepoUrl() return ["Remote URL is not hosted on Bitbucket: #{@gitUrl()}"] if (disallowStash and @isStashUrl(@gitUrl())) return ["This feature is only available when hosting repositories on Bitbucket (bitbucket.org)"] [] # Internal reportValidationErrors: (disallowStash = false) -> message = @validationErrors(disallowStash).join('\n') atom.notifications.addWarning(message) # Internal openUrlInBrowser: (url) -> Shell.openExternal url # Internal blobUrl: -> baseUrl = @bitbucketRepoUrl() if @isBitbucketCloudUrl(baseUrl) "#{baseUrl}/src/#{@remoteBranchName()}/#{@encodeSegments(@repoRelativePath())}" else "#{baseUrl}/browse/#{@encodeSegments(@repoRelativePath())}?at=#{@remoteBranchName()}" # Internal blobUrlForMaster: -> baseUrl = @bitbucketRepoUrl() if @isBitbucketCloudUrl(baseUrl) "#{baseUrl}/src/master/#{@encodeSegments(@repoRelativePath())}" else "#{baseUrl}/browse/#{@encodeSegments(@repoRelativePath())}?at=master" # Internal shaUrl: -> baseUrl = @bitbucketRepoUrl() if @isBitbucketCloudUrl(baseUrl) "#{baseUrl}/src/#{@encodeSegments(@sha())}/#{@encodeSegments(@repoRelativePath())}" else "#{baseUrl}/browse/#{@encodeSegments(@repoRelativePath())}?at=#{@encodeSegments(@sha())}" # Internal blameUrl: -> "#{@bitbucketRepoUrl()}/annotate/#{@encodeSegments(@branchName())}/#{@encodeSegments(@repoRelativePath())}" # Internal historyUrl: -> "#{@bitbucketRepoUrl()}/history-node/#{@encodeSegments(@branchName())}/#{@encodeSegments(@repoRelativePath())}" # Internal issuesUrl: -> "#{@bitbucketRepoUrl()}/issues" # Internal branchCompareUrl: -> baseUrl = @bitbucketRepoUrl() if @isBitbucketCloudUrl(baseUrl) "#{baseUrl}/branch/#{@encodeSegments(@branchName())}" else "#{baseUrl}/compare/commits?sourceBranch=#{@encodeSegments(@branchName())}" encodeSegments: (segments='') -> segments = segments.split('/') segments = segments.map (segment) -> encodeURIComponent(segment) segments.join('/') # Internal gitUrl: -> remoteOrBestGuess = @remoteName() ? 'origin' @repo.getConfigValue("remote.#{remoteOrBestGuess}.url", @filePath) # Internal bitbucketRepoUrl: -> url = @gitUrl() if @isGithubUrl(url) return else if @isBitbucketCloudUrl(url) return @bitbucketCloudRepoUrl(url) else return @stashRepoUrlRepoUrl(url) # Internal bitbucketCloudRepoUrl: (url) -> if url.match /https?:\/\/[^\/]+\// # e.g., https://bitbucket.org/foo/bar.git or http://bitbucket.org/foo/bar.git url = url.replace(/\.git$/, '') else if url.match /^git[^@]*@[^:]+:/ # e.g., git@bitbucket.org:foo/bar.git url = url.replace /^git[^@]*@([^:]+):(.+)$/, (match, host, repoPath) -> repoPath = repoPath.replace(/^\/+/, '') # replace leading slashes "http://#{host}/#{repoPath}".replace(/\.git$/, '') else if url.match /ssh:\/\/git@([^\/]+)\// # e.g., ssh://git@bitbucket.org/foo/bar.git url = "http://#{url.substring(10).replace(/\.git$/, '')}" else if url.match /^git:\/\/[^\/]+\// # e.g., git://bitbucket.org/foo/bar.git url = "http#{url.substring(3).replace(/\.git$/, '')}" url = url.replace(/\.git$/, '') url = url.replace(/\/+$/, '') return url # Internal stashRepoUrlRepoUrl: (url) -> urlObj = parseUrl(@bitbucketCloudRepoUrl(url)) urlObj.host = urlObj.hostname urlObj.auth = null [match, proj, repo] = urlObj.pathname.match /(?:\/scm)?\/(.+)\/(.+)/ urlObj.pathname = "/projects/#{proj}/repos/#{repo}" return formatUrl(urlObj) # Internal isGithubUrl: (url) -> return true if url.indexOf('git@github.com') is 0 try {host} = parseUrl(url) host is 'github.com' # Internal isBitbucketCloudUrl: (url) -> return true if url.indexOf('git@bitbucket.org') is 0 try {host} = parseUrl(url) host is 'bitbucket.org' # Internal isStashUrl: (url) -> return not (@isGithubUrl(url) or @isBitbucketCloudUrl(url)) # Internal repoRelativePath: -> @repo.getRepo(@filePath).relativize(@filePath) # Internal remoteName: -> shortBranch = @repo.getShortHead(@filePath) return null unless shortBranch branchRemote = @repo.getConfigValue("branch.#{shortBranch}.remote", @filePath) return null unless branchRemote?.length > 0 branchRemote # Internal sha: -> @repo.getReferenceTarget('HEAD', @filePath) # Internal branchName: -> shortBranch = @repo.getShortHead(@filePath) return null unless shortBranch branchMerge = @repo.getConfigValue("branch.#{shortBranch}.merge", @filePath) return shortBranch unless branchMerge?.length > 11 return shortBranch unless branchMerge.indexOf('refs/heads/') is 0 branchMerge.substring(11) # Internal remoteBranchName: -> if @remoteName()? @encodeSegments(@branchName()) else 'master'
119303
Shell = require 'shell' {Range} = require 'atom' parseUrl = require('url').parse formatUrl = require('url').format module.exports = class BitbucketFile # Public @fromPath: (filePath) -> new BitbucketFile(filePath) # Internal constructor: (@filePath) -> [rootDir] = atom.project.relativizePath(@filePath) if rootDir? rootDirIndex = atom.project.getPaths().indexOf(rootDir) @repo = atom.project.getRepositories()[rootDirIndex] # Public open: (lineRange) -> if @isOpenable() @openUrlInBrowser(@blobUrl() + @getLineRangeSuffix(lineRange)) else @reportValidationErrors() # Public openOnMaster: (lineRange) -> if @isOpenable() @openUrlInBrowser(@blobUrlForMaster() + @getLineRangeSuffix(lineRange)) else @reportValidationErrors() # Public blame: (lineRange) -> if @isOpenable(true) @openUrlInBrowser(@blameUrl() + @getLineRangeSuffix(lineRange)) else @reportValidationErrors(true) history: -> if @isOpenable(true) @openUrlInBrowser(@historyUrl()) else @reportValidationErrors(true) copyUrl: (lineRange) -> if @isOpenable() atom.clipboard.write(@shaUrl() + @getLineRangeSuffix(lineRange)) else @reportValidationErrors() openBranchCompare: -> if @isOpenable() @openUrlInBrowser(@branchCompareUrl()) else @reportValidationErrors() openIssues: -> if @isOpenable(true) @openUrlInBrowser(@issuesUrl()) else @reportValidationErrors(true) openRepository: -> if @isOpenable() @openUrlInBrowser(@bitbucketRepoUrl()) else @reportValidationErrors() getLineRangeSuffix: (lineRange) -> if lineRange and atom.config.get('open-on-bitbucket.includeLineNumbersInUrls') lineRange = Range.fromObject(lineRange) startRow = lineRange.start.row + 1 endRow = lineRange.end.row + 1 if startRow is endRow if @isBitbucketCloudUrl(@gitUrl()) then "#cl-#{startRow}" else "##{startRow}" else if @isBitbucketCloudUrl(@gitUrl()) then "#cl-#{startRow}:#{endRow}" else "##{startRow}-#{endRow}" else '' # Public isOpenable: (disallowStash = false) -> @validationErrors(disallowStash).length is 0 # Public validationErrors: (disallowStash) -> unless @repo return ["No repository found for path: #{@filePath}."] unless @gitUrl() return ["No URL defined for remote: #{@remoteName()}"] unless @bitbucketRepoUrl() return ["Remote URL is not hosted on Bitbucket: #{@gitUrl()}"] if (disallowStash and @isStashUrl(@gitUrl())) return ["This feature is only available when hosting repositories on Bitbucket (bitbucket.org)"] [] # Internal reportValidationErrors: (disallowStash = false) -> message = @validationErrors(disallowStash).join('\n') atom.notifications.addWarning(message) # Internal openUrlInBrowser: (url) -> Shell.openExternal url # Internal blobUrl: -> baseUrl = @bitbucketRepoUrl() if @isBitbucketCloudUrl(baseUrl) "#{baseUrl}/src/#{@remoteBranchName()}/#{@encodeSegments(@repoRelativePath())}" else "#{baseUrl}/browse/#{@encodeSegments(@repoRelativePath())}?at=#{@remoteBranchName()}" # Internal blobUrlForMaster: -> baseUrl = @bitbucketRepoUrl() if @isBitbucketCloudUrl(baseUrl) "#{baseUrl}/src/master/#{@encodeSegments(@repoRelativePath())}" else "#{baseUrl}/browse/#{@encodeSegments(@repoRelativePath())}?at=master" # Internal shaUrl: -> baseUrl = @bitbucketRepoUrl() if @isBitbucketCloudUrl(baseUrl) "#{baseUrl}/src/#{@encodeSegments(@sha())}/#{@encodeSegments(@repoRelativePath())}" else "#{baseUrl}/browse/#{@encodeSegments(@repoRelativePath())}?at=#{@encodeSegments(@sha())}" # Internal blameUrl: -> "#{@bitbucketRepoUrl()}/annotate/#{@encodeSegments(@branchName())}/#{@encodeSegments(@repoRelativePath())}" # Internal historyUrl: -> "#{@bitbucketRepoUrl()}/history-node/#{@encodeSegments(@branchName())}/#{@encodeSegments(@repoRelativePath())}" # Internal issuesUrl: -> "#{@bitbucketRepoUrl()}/issues" # Internal branchCompareUrl: -> baseUrl = @bitbucketRepoUrl() if @isBitbucketCloudUrl(baseUrl) "#{baseUrl}/branch/#{@encodeSegments(@branchName())}" else "#{baseUrl}/compare/commits?sourceBranch=#{@encodeSegments(@branchName())}" encodeSegments: (segments='') -> segments = segments.split('/') segments = segments.map (segment) -> encodeURIComponent(segment) segments.join('/') # Internal gitUrl: -> remoteOrBestGuess = @remoteName() ? 'origin' @repo.getConfigValue("remote.#{remoteOrBestGuess}.url", @filePath) # Internal bitbucketRepoUrl: -> url = @gitUrl() if @isGithubUrl(url) return else if @isBitbucketCloudUrl(url) return @bitbucketCloudRepoUrl(url) else return @stashRepoUrlRepoUrl(url) # Internal bitbucketCloudRepoUrl: (url) -> if url.match /https?:\/\/[^\/]+\// # e.g., https://bitbucket.org/foo/bar.git or http://bitbucket.org/foo/bar.git url = url.replace(/\.git$/, '') else if url.match /^git[^@]*@[^:]+:/ # e.g., git@bitbucket.org:foo/bar.git url = url.replace /^git[^@]*@([^:]+):(.+)$/, (match, host, repoPath) -> repoPath = repoPath.replace(/^\/+/, '') # replace leading slashes "http://#{host}/#{repoPath}".replace(/\.git$/, '') else if url.match /ssh:\/\/git@([^\/]+)\// # e.g., ssh://git@bitbucket.org/foo/bar.git url = "http://#{url.substring(10).replace(/\.git$/, '')}" else if url.match /^git:\/\/[^\/]+\// # e.g., git://bitbucket.org/foo/bar.git url = "http#{url.substring(3).replace(/\.git$/, '')}" url = url.replace(/\.git$/, '') url = url.replace(/\/+$/, '') return url # Internal stashRepoUrlRepoUrl: (url) -> urlObj = parseUrl(@bitbucketCloudRepoUrl(url)) urlObj.host = urlObj.hostname urlObj.auth = null [match, proj, repo] = urlObj.pathname.match /(?:\/scm)?\/(.+)\/(.+)/ urlObj.pathname = "/projects/#{proj}/repos/#{repo}" return formatUrl(urlObj) # Internal isGithubUrl: (url) -> return true if url.indexOf('<EMAIL>') is 0 try {host} = parseUrl(url) host is 'github.com' # Internal isBitbucketCloudUrl: (url) -> return true if url.indexOf('<EMAIL>') is 0 try {host} = parseUrl(url) host is 'bitbucket.org' # Internal isStashUrl: (url) -> return not (@isGithubUrl(url) or @isBitbucketCloudUrl(url)) # Internal repoRelativePath: -> @repo.getRepo(@filePath).relativize(@filePath) # Internal remoteName: -> shortBranch = @repo.getShortHead(@filePath) return null unless shortBranch branchRemote = @repo.getConfigValue("branch.#{shortBranch}.remote", @filePath) return null unless branchRemote?.length > 0 branchRemote # Internal sha: -> @repo.getReferenceTarget('HEAD', @filePath) # Internal branchName: -> shortBranch = @repo.getShortHead(@filePath) return null unless shortBranch branchMerge = @repo.getConfigValue("branch.#{shortBranch}.merge", @filePath) return shortBranch unless branchMerge?.length > 11 return shortBranch unless branchMerge.indexOf('refs/heads/') is 0 branchMerge.substring(11) # Internal remoteBranchName: -> if @remoteName()? @encodeSegments(@branchName()) else 'master'
true
Shell = require 'shell' {Range} = require 'atom' parseUrl = require('url').parse formatUrl = require('url').format module.exports = class BitbucketFile # Public @fromPath: (filePath) -> new BitbucketFile(filePath) # Internal constructor: (@filePath) -> [rootDir] = atom.project.relativizePath(@filePath) if rootDir? rootDirIndex = atom.project.getPaths().indexOf(rootDir) @repo = atom.project.getRepositories()[rootDirIndex] # Public open: (lineRange) -> if @isOpenable() @openUrlInBrowser(@blobUrl() + @getLineRangeSuffix(lineRange)) else @reportValidationErrors() # Public openOnMaster: (lineRange) -> if @isOpenable() @openUrlInBrowser(@blobUrlForMaster() + @getLineRangeSuffix(lineRange)) else @reportValidationErrors() # Public blame: (lineRange) -> if @isOpenable(true) @openUrlInBrowser(@blameUrl() + @getLineRangeSuffix(lineRange)) else @reportValidationErrors(true) history: -> if @isOpenable(true) @openUrlInBrowser(@historyUrl()) else @reportValidationErrors(true) copyUrl: (lineRange) -> if @isOpenable() atom.clipboard.write(@shaUrl() + @getLineRangeSuffix(lineRange)) else @reportValidationErrors() openBranchCompare: -> if @isOpenable() @openUrlInBrowser(@branchCompareUrl()) else @reportValidationErrors() openIssues: -> if @isOpenable(true) @openUrlInBrowser(@issuesUrl()) else @reportValidationErrors(true) openRepository: -> if @isOpenable() @openUrlInBrowser(@bitbucketRepoUrl()) else @reportValidationErrors() getLineRangeSuffix: (lineRange) -> if lineRange and atom.config.get('open-on-bitbucket.includeLineNumbersInUrls') lineRange = Range.fromObject(lineRange) startRow = lineRange.start.row + 1 endRow = lineRange.end.row + 1 if startRow is endRow if @isBitbucketCloudUrl(@gitUrl()) then "#cl-#{startRow}" else "##{startRow}" else if @isBitbucketCloudUrl(@gitUrl()) then "#cl-#{startRow}:#{endRow}" else "##{startRow}-#{endRow}" else '' # Public isOpenable: (disallowStash = false) -> @validationErrors(disallowStash).length is 0 # Public validationErrors: (disallowStash) -> unless @repo return ["No repository found for path: #{@filePath}."] unless @gitUrl() return ["No URL defined for remote: #{@remoteName()}"] unless @bitbucketRepoUrl() return ["Remote URL is not hosted on Bitbucket: #{@gitUrl()}"] if (disallowStash and @isStashUrl(@gitUrl())) return ["This feature is only available when hosting repositories on Bitbucket (bitbucket.org)"] [] # Internal reportValidationErrors: (disallowStash = false) -> message = @validationErrors(disallowStash).join('\n') atom.notifications.addWarning(message) # Internal openUrlInBrowser: (url) -> Shell.openExternal url # Internal blobUrl: -> baseUrl = @bitbucketRepoUrl() if @isBitbucketCloudUrl(baseUrl) "#{baseUrl}/src/#{@remoteBranchName()}/#{@encodeSegments(@repoRelativePath())}" else "#{baseUrl}/browse/#{@encodeSegments(@repoRelativePath())}?at=#{@remoteBranchName()}" # Internal blobUrlForMaster: -> baseUrl = @bitbucketRepoUrl() if @isBitbucketCloudUrl(baseUrl) "#{baseUrl}/src/master/#{@encodeSegments(@repoRelativePath())}" else "#{baseUrl}/browse/#{@encodeSegments(@repoRelativePath())}?at=master" # Internal shaUrl: -> baseUrl = @bitbucketRepoUrl() if @isBitbucketCloudUrl(baseUrl) "#{baseUrl}/src/#{@encodeSegments(@sha())}/#{@encodeSegments(@repoRelativePath())}" else "#{baseUrl}/browse/#{@encodeSegments(@repoRelativePath())}?at=#{@encodeSegments(@sha())}" # Internal blameUrl: -> "#{@bitbucketRepoUrl()}/annotate/#{@encodeSegments(@branchName())}/#{@encodeSegments(@repoRelativePath())}" # Internal historyUrl: -> "#{@bitbucketRepoUrl()}/history-node/#{@encodeSegments(@branchName())}/#{@encodeSegments(@repoRelativePath())}" # Internal issuesUrl: -> "#{@bitbucketRepoUrl()}/issues" # Internal branchCompareUrl: -> baseUrl = @bitbucketRepoUrl() if @isBitbucketCloudUrl(baseUrl) "#{baseUrl}/branch/#{@encodeSegments(@branchName())}" else "#{baseUrl}/compare/commits?sourceBranch=#{@encodeSegments(@branchName())}" encodeSegments: (segments='') -> segments = segments.split('/') segments = segments.map (segment) -> encodeURIComponent(segment) segments.join('/') # Internal gitUrl: -> remoteOrBestGuess = @remoteName() ? 'origin' @repo.getConfigValue("remote.#{remoteOrBestGuess}.url", @filePath) # Internal bitbucketRepoUrl: -> url = @gitUrl() if @isGithubUrl(url) return else if @isBitbucketCloudUrl(url) return @bitbucketCloudRepoUrl(url) else return @stashRepoUrlRepoUrl(url) # Internal bitbucketCloudRepoUrl: (url) -> if url.match /https?:\/\/[^\/]+\// # e.g., https://bitbucket.org/foo/bar.git or http://bitbucket.org/foo/bar.git url = url.replace(/\.git$/, '') else if url.match /^git[^@]*@[^:]+:/ # e.g., git@bitbucket.org:foo/bar.git url = url.replace /^git[^@]*@([^:]+):(.+)$/, (match, host, repoPath) -> repoPath = repoPath.replace(/^\/+/, '') # replace leading slashes "http://#{host}/#{repoPath}".replace(/\.git$/, '') else if url.match /ssh:\/\/git@([^\/]+)\// # e.g., ssh://git@bitbucket.org/foo/bar.git url = "http://#{url.substring(10).replace(/\.git$/, '')}" else if url.match /^git:\/\/[^\/]+\// # e.g., git://bitbucket.org/foo/bar.git url = "http#{url.substring(3).replace(/\.git$/, '')}" url = url.replace(/\.git$/, '') url = url.replace(/\/+$/, '') return url # Internal stashRepoUrlRepoUrl: (url) -> urlObj = parseUrl(@bitbucketCloudRepoUrl(url)) urlObj.host = urlObj.hostname urlObj.auth = null [match, proj, repo] = urlObj.pathname.match /(?:\/scm)?\/(.+)\/(.+)/ urlObj.pathname = "/projects/#{proj}/repos/#{repo}" return formatUrl(urlObj) # Internal isGithubUrl: (url) -> return true if url.indexOf('PI:EMAIL:<EMAIL>END_PI') is 0 try {host} = parseUrl(url) host is 'github.com' # Internal isBitbucketCloudUrl: (url) -> return true if url.indexOf('PI:EMAIL:<EMAIL>END_PI') is 0 try {host} = parseUrl(url) host is 'bitbucket.org' # Internal isStashUrl: (url) -> return not (@isGithubUrl(url) or @isBitbucketCloudUrl(url)) # Internal repoRelativePath: -> @repo.getRepo(@filePath).relativize(@filePath) # Internal remoteName: -> shortBranch = @repo.getShortHead(@filePath) return null unless shortBranch branchRemote = @repo.getConfigValue("branch.#{shortBranch}.remote", @filePath) return null unless branchRemote?.length > 0 branchRemote # Internal sha: -> @repo.getReferenceTarget('HEAD', @filePath) # Internal branchName: -> shortBranch = @repo.getShortHead(@filePath) return null unless shortBranch branchMerge = @repo.getConfigValue("branch.#{shortBranch}.merge", @filePath) return shortBranch unless branchMerge?.length > 11 return shortBranch unless branchMerge.indexOf('refs/heads/') is 0 branchMerge.substring(11) # Internal remoteBranchName: -> if @remoteName()? @encodeSegments(@branchName()) else 'master'
[ { "context": "= $(matchKey)\n nvalue = match.val() \n key = get_seq_base(id)\n deltaKey = key + \"_delta\"\n de", "end": 3390, "score": 0.5178603529930115, "start": 3387, "tag": "KEY", "value": "get" } ]
app/assets/javascripts/assessable/text_eval.js.coffee
salex/Assessable
1
# TTTTTTTTTTTTTTTTTTT Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. $(document).ready -> $(document).on("click", '[data-behavior="edit_contains"]', -> $("#"+this.id+"_div").toggle()) $(document).on("click",'[data-behavior="edit_numeric"]', -> $("#"+this.id+"_div").toggle()) $(document).on("click", '[data-behavior="contains_cancel"]',-> seq = get_seq(this.id) $("#eval_"+seq+"_div").hide()) $(document).on("click", '[data-behavior="numeric_cancel"]', -> seq = get_seq(this.id) $("#eval_"+seq+"_div").hide()) $(document).on("click",'[data-behavior="contains_update"]', -> update_contains(this.id)) $(document).on("click",'[data-behavior="numeric_update"]', -> update_numeric(this.id)) update_contains = (id) -> key = get_seq_base(id) matchKey = key + "_match" partialKey = key + "_partial" matches = $("."+ matchKey) partials = $("."+partialKey) match_section = format_match(matches) partial_section = format_partial(partials) seq = get_seq(id) text_eval = "#question_answers_attributes_#{seq - 1}_text_eval" if partial_section == "" $(text_eval).val(match_section) else $(text_eval).val(match_section+"::"+partial_section) $("#eval_"+seq+"_div").hide() $(text_eval).css("color","orange") format_match = (matches) -> result = new Array() for match in matches if match.value != "" value = match.value id = match.id or_id = id.replace("match", "word_or") not_id = id.replace("match", "word_not") gor_id = id.replace("match", "group_or") x = $("#"+or_id).prop('checked') y = $("#"+not_id).prop('checked') z = $("#"+gor_id).prop('checked') #alert("#{z} #{x} #{y} #{value} #{gor_id}") if x if value.indexOf("|") < 0 value = value.replace( /\s+/g, ' ' ) tmp = value.split(" "); value = "(" + tmp.join("|") + ")" else value = "(" + value + ")" if y value = "!" + value if z value = "||" + value result.push(value) section = result.join("&").replace("&||","||") return(section) format_partial = (partials) -> result = new Array() for partial in partials if partial.value != "" value = partial.value id = partial.id or_id = id.replace("partial_match", "partial_or") not_id = id.replace("partial_match", "partial_not") perc_id = id.replace("partial_match", "partial_percent") x = $("#"+or_id).prop('checked') y = $("#"+not_id).prop('checked') perc = $("#"+perc_id).val() if perc == "" then perc = 0 if x if value.indexOf("|") < 0 value = value.replace( /\s+/g, ' ' ) tmp = value.split(" "); value = "(" + tmp.join("|") + ")" else value = "(" + value + ")" if y value = "!" + value value += "%%#{perc}" result.push(value) return(result.join("::")) update_numeric = (id) -> seq = get_seq(id) matchKey = "#numeric_match_"+seq match = $(matchKey) nvalue = match.val() key = get_seq_base(id) deltaKey = key + "_delta" deltas = $("."+ deltaKey) result = new Array() for delta in deltas if delta.value != "" value = delta.value delta_id = delta.id perc_id = delta_id.replace("delta", "percent") perc = $("#"+perc_id).val() if perc == "" then perc = 100 value += "%%#{perc}" result.push(value) delta_section = result.join("::") text_eval = "#question_answers_attributes_#{seq - 1}_text_eval" if delta_section == "" $(text_eval).val(nvalue) else $(text_eval).val(nvalue+"::"+delta_section) $("#eval_"+seq+"_div").hide() $(text_eval).css("color","orange") get_seq = (id) -> t = id.split("_") return t[1] get_seq_base = (id) -> t = id.split("_") return t[0]+"_"+t[1]
78603
# TTTTTTTTTTTTTTTTTTT Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. $(document).ready -> $(document).on("click", '[data-behavior="edit_contains"]', -> $("#"+this.id+"_div").toggle()) $(document).on("click",'[data-behavior="edit_numeric"]', -> $("#"+this.id+"_div").toggle()) $(document).on("click", '[data-behavior="contains_cancel"]',-> seq = get_seq(this.id) $("#eval_"+seq+"_div").hide()) $(document).on("click", '[data-behavior="numeric_cancel"]', -> seq = get_seq(this.id) $("#eval_"+seq+"_div").hide()) $(document).on("click",'[data-behavior="contains_update"]', -> update_contains(this.id)) $(document).on("click",'[data-behavior="numeric_update"]', -> update_numeric(this.id)) update_contains = (id) -> key = get_seq_base(id) matchKey = key + "_match" partialKey = key + "_partial" matches = $("."+ matchKey) partials = $("."+partialKey) match_section = format_match(matches) partial_section = format_partial(partials) seq = get_seq(id) text_eval = "#question_answers_attributes_#{seq - 1}_text_eval" if partial_section == "" $(text_eval).val(match_section) else $(text_eval).val(match_section+"::"+partial_section) $("#eval_"+seq+"_div").hide() $(text_eval).css("color","orange") format_match = (matches) -> result = new Array() for match in matches if match.value != "" value = match.value id = match.id or_id = id.replace("match", "word_or") not_id = id.replace("match", "word_not") gor_id = id.replace("match", "group_or") x = $("#"+or_id).prop('checked') y = $("#"+not_id).prop('checked') z = $("#"+gor_id).prop('checked') #alert("#{z} #{x} #{y} #{value} #{gor_id}") if x if value.indexOf("|") < 0 value = value.replace( /\s+/g, ' ' ) tmp = value.split(" "); value = "(" + tmp.join("|") + ")" else value = "(" + value + ")" if y value = "!" + value if z value = "||" + value result.push(value) section = result.join("&").replace("&||","||") return(section) format_partial = (partials) -> result = new Array() for partial in partials if partial.value != "" value = partial.value id = partial.id or_id = id.replace("partial_match", "partial_or") not_id = id.replace("partial_match", "partial_not") perc_id = id.replace("partial_match", "partial_percent") x = $("#"+or_id).prop('checked') y = $("#"+not_id).prop('checked') perc = $("#"+perc_id).val() if perc == "" then perc = 0 if x if value.indexOf("|") < 0 value = value.replace( /\s+/g, ' ' ) tmp = value.split(" "); value = "(" + tmp.join("|") + ")" else value = "(" + value + ")" if y value = "!" + value value += "%%#{perc}" result.push(value) return(result.join("::")) update_numeric = (id) -> seq = get_seq(id) matchKey = "#numeric_match_"+seq match = $(matchKey) nvalue = match.val() key = <KEY>_seq_base(id) deltaKey = key + "_delta" deltas = $("."+ deltaKey) result = new Array() for delta in deltas if delta.value != "" value = delta.value delta_id = delta.id perc_id = delta_id.replace("delta", "percent") perc = $("#"+perc_id).val() if perc == "" then perc = 100 value += "%%#{perc}" result.push(value) delta_section = result.join("::") text_eval = "#question_answers_attributes_#{seq - 1}_text_eval" if delta_section == "" $(text_eval).val(nvalue) else $(text_eval).val(nvalue+"::"+delta_section) $("#eval_"+seq+"_div").hide() $(text_eval).css("color","orange") get_seq = (id) -> t = id.split("_") return t[1] get_seq_base = (id) -> t = id.split("_") return t[0]+"_"+t[1]
true
# TTTTTTTTTTTTTTTTTTT Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. $(document).ready -> $(document).on("click", '[data-behavior="edit_contains"]', -> $("#"+this.id+"_div").toggle()) $(document).on("click",'[data-behavior="edit_numeric"]', -> $("#"+this.id+"_div").toggle()) $(document).on("click", '[data-behavior="contains_cancel"]',-> seq = get_seq(this.id) $("#eval_"+seq+"_div").hide()) $(document).on("click", '[data-behavior="numeric_cancel"]', -> seq = get_seq(this.id) $("#eval_"+seq+"_div").hide()) $(document).on("click",'[data-behavior="contains_update"]', -> update_contains(this.id)) $(document).on("click",'[data-behavior="numeric_update"]', -> update_numeric(this.id)) update_contains = (id) -> key = get_seq_base(id) matchKey = key + "_match" partialKey = key + "_partial" matches = $("."+ matchKey) partials = $("."+partialKey) match_section = format_match(matches) partial_section = format_partial(partials) seq = get_seq(id) text_eval = "#question_answers_attributes_#{seq - 1}_text_eval" if partial_section == "" $(text_eval).val(match_section) else $(text_eval).val(match_section+"::"+partial_section) $("#eval_"+seq+"_div").hide() $(text_eval).css("color","orange") format_match = (matches) -> result = new Array() for match in matches if match.value != "" value = match.value id = match.id or_id = id.replace("match", "word_or") not_id = id.replace("match", "word_not") gor_id = id.replace("match", "group_or") x = $("#"+or_id).prop('checked') y = $("#"+not_id).prop('checked') z = $("#"+gor_id).prop('checked') #alert("#{z} #{x} #{y} #{value} #{gor_id}") if x if value.indexOf("|") < 0 value = value.replace( /\s+/g, ' ' ) tmp = value.split(" "); value = "(" + tmp.join("|") + ")" else value = "(" + value + ")" if y value = "!" + value if z value = "||" + value result.push(value) section = result.join("&").replace("&||","||") return(section) format_partial = (partials) -> result = new Array() for partial in partials if partial.value != "" value = partial.value id = partial.id or_id = id.replace("partial_match", "partial_or") not_id = id.replace("partial_match", "partial_not") perc_id = id.replace("partial_match", "partial_percent") x = $("#"+or_id).prop('checked') y = $("#"+not_id).prop('checked') perc = $("#"+perc_id).val() if perc == "" then perc = 0 if x if value.indexOf("|") < 0 value = value.replace( /\s+/g, ' ' ) tmp = value.split(" "); value = "(" + tmp.join("|") + ")" else value = "(" + value + ")" if y value = "!" + value value += "%%#{perc}" result.push(value) return(result.join("::")) update_numeric = (id) -> seq = get_seq(id) matchKey = "#numeric_match_"+seq match = $(matchKey) nvalue = match.val() key = PI:KEY:<KEY>END_PI_seq_base(id) deltaKey = key + "_delta" deltas = $("."+ deltaKey) result = new Array() for delta in deltas if delta.value != "" value = delta.value delta_id = delta.id perc_id = delta_id.replace("delta", "percent") perc = $("#"+perc_id).val() if perc == "" then perc = 100 value += "%%#{perc}" result.push(value) delta_section = result.join("::") text_eval = "#question_answers_attributes_#{seq - 1}_text_eval" if delta_section == "" $(text_eval).val(nvalue) else $(text_eval).val(nvalue+"::"+delta_section) $("#eval_"+seq+"_div").hide() $(text_eval).css("color","orange") get_seq = (id) -> t = id.split("_") return t[1] get_seq_base = (id) -> t = id.split("_") return t[0]+"_"+t[1]
[ { "context": "t props to\nuserPropsToSave =\n 'name.givenName': 'firstName'\n 'name.familyName': 'lastName'\n 'gender': 'gen", "end": 231, "score": 0.9989279508590698, "start": 222, "tag": "NAME", "value": "firstName" }, { "context": "ame.givenName': 'firstName'\n 'name.familyNam...
app/lib/GPlusHandler.coffee
vyz1194/codecombat
1
CocoClass = require 'lib/CocoClass' {me, CURRENT_USER_KEY} = require 'lib/auth' {backboneFailure} = require 'lib/errors' storage = require 'lib/storage' # gplus user object props to userPropsToSave = 'name.givenName': 'firstName' 'name.familyName': 'lastName' 'gender': 'gender' 'id': 'gplusID' fieldsToFetch = 'displayName,gender,image,name(familyName,givenName),id' plusURL = '/plus/v1/people/me?fields='+fieldsToFetch revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' clientID = "800329290710-j9sivplv2gpcdgkrsis9rff3o417mlfa.apps.googleusercontent.com" module.exports = GPlusHandler = class GPlusHandler extends CocoClass constructor: -> super() subscriptions: 'gplus-logged-in':'onGPlusLogin' onGPlusLogin: (e) => return if e._aa # this seems to show that it was auto generated on page load return if not me @accessToken = e.access_token # email and profile data loaded separately @responsesComplete = 0 gapi.client.request(path:plusURL, callback:@onPersonEntityReceived) gapi.client.load('oauth2', 'v2', => gapi.client.oauth2.userinfo.get().execute(@onEmailReceived)) shouldSave: false responsesComplete: 0 onPersonEntityReceived: (r) => for gpProp, userProp of userPropsToSave keys = gpProp.split('.') value = r value = value[key] for key in keys if value and not me.get(userProp) @shouldSave = true me.set(userProp, value) @responsesComplete += 1 @saveIfAllDone() onEmailReceived: (r) => newEmail = r.email and r.email isnt me.get('email') return unless newEmail or me.get('anonymous') me.set('email', r.email) @shouldSave = true @responsesComplete += 1 @saveIfAllDone() saveIfAllDone: => return unless @responsesComplete is 2 return unless me.get('email') and me.get('gplusID') Backbone.Mediator.publish('logging-in-with-gplus') gplusID = me.get('gplusID') window.tracker?.trackEvent 'Google Login' window.tracker?.identify() patch = {} patch[key] = me.get(key) for gplusKey, key of userPropsToSave patch._id = me.id patch.email = me.get('email') me.save(patch, { patch: true error: backboneFailure, url: "/db/user?gplusID=#{gplusID}&gplusAccessToken=#{@accessToken}" success: (model) -> storage.save(CURRENT_USER_KEY, model.attributes) window.location.reload() })
42406
CocoClass = require 'lib/CocoClass' {me, CURRENT_USER_KEY} = require 'lib/auth' {backboneFailure} = require 'lib/errors' storage = require 'lib/storage' # gplus user object props to userPropsToSave = 'name.givenName': '<NAME>' 'name.familyName': '<NAME>' 'gender': 'gender' 'id': 'gplusID' fieldsToFetch = 'displayName,gender,image,name(familyName,givenName),id' plusURL = '/plus/v1/people/me?fields='+fieldsToFetch revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' clientID = "<KEY>" module.exports = GPlusHandler = class GPlusHandler extends CocoClass constructor: -> super() subscriptions: 'gplus-logged-in':'onGPlusLogin' onGPlusLogin: (e) => return if e._aa # this seems to show that it was auto generated on page load return if not me @accessToken = e.access_token # email and profile data loaded separately @responsesComplete = 0 gapi.client.request(path:plusURL, callback:@onPersonEntityReceived) gapi.client.load('oauth2', 'v2', => gapi.client.oauth2.userinfo.get().execute(@onEmailReceived)) shouldSave: false responsesComplete: 0 onPersonEntityReceived: (r) => for gpProp, userProp of userPropsToSave keys = gpProp.split('.') value = r value = value[key] for key in keys if value and not me.get(userProp) @shouldSave = true me.set(userProp, value) @responsesComplete += 1 @saveIfAllDone() onEmailReceived: (r) => newEmail = r.email and r.email isnt me.get('email') return unless newEmail or me.get('anonymous') me.set('email', r.email) @shouldSave = true @responsesComplete += 1 @saveIfAllDone() saveIfAllDone: => return unless @responsesComplete is 2 return unless me.get('email') and me.get('gplusID') Backbone.Mediator.publish('logging-in-with-gplus') gplusID = me.get('gplusID') window.tracker?.trackEvent 'Google Login' window.tracker?.identify() patch = {} patch[key] = me.get(key) for gplusKey, key of userPropsToSave patch._id = me.id patch.email = me.get('email') me.save(patch, { patch: true error: backboneFailure, url: "/db/user?gplusID=#{gplusID}&gplusAccessToken=#{@accessToken}" success: (model) -> storage.save(CURRENT_USER_KEY, model.attributes) window.location.reload() })
true
CocoClass = require 'lib/CocoClass' {me, CURRENT_USER_KEY} = require 'lib/auth' {backboneFailure} = require 'lib/errors' storage = require 'lib/storage' # gplus user object props to userPropsToSave = 'name.givenName': 'PI:NAME:<NAME>END_PI' 'name.familyName': 'PI:NAME:<NAME>END_PI' 'gender': 'gender' 'id': 'gplusID' fieldsToFetch = 'displayName,gender,image,name(familyName,givenName),id' plusURL = '/plus/v1/people/me?fields='+fieldsToFetch revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' clientID = "PI:KEY:<KEY>END_PI" module.exports = GPlusHandler = class GPlusHandler extends CocoClass constructor: -> super() subscriptions: 'gplus-logged-in':'onGPlusLogin' onGPlusLogin: (e) => return if e._aa # this seems to show that it was auto generated on page load return if not me @accessToken = e.access_token # email and profile data loaded separately @responsesComplete = 0 gapi.client.request(path:plusURL, callback:@onPersonEntityReceived) gapi.client.load('oauth2', 'v2', => gapi.client.oauth2.userinfo.get().execute(@onEmailReceived)) shouldSave: false responsesComplete: 0 onPersonEntityReceived: (r) => for gpProp, userProp of userPropsToSave keys = gpProp.split('.') value = r value = value[key] for key in keys if value and not me.get(userProp) @shouldSave = true me.set(userProp, value) @responsesComplete += 1 @saveIfAllDone() onEmailReceived: (r) => newEmail = r.email and r.email isnt me.get('email') return unless newEmail or me.get('anonymous') me.set('email', r.email) @shouldSave = true @responsesComplete += 1 @saveIfAllDone() saveIfAllDone: => return unless @responsesComplete is 2 return unless me.get('email') and me.get('gplusID') Backbone.Mediator.publish('logging-in-with-gplus') gplusID = me.get('gplusID') window.tracker?.trackEvent 'Google Login' window.tracker?.identify() patch = {} patch[key] = me.get(key) for gplusKey, key of userPropsToSave patch._id = me.id patch.email = me.get('email') me.save(patch, { patch: true error: backboneFailure, url: "/db/user?gplusID=#{gplusID}&gplusAccessToken=#{@accessToken}" success: (model) -> storage.save(CURRENT_USER_KEY, model.attributes) window.location.reload() })
[ { "context": "sed for context menu 注册表信息;\nfileKeyPath = 'HKCU\\\\Software\\\\Classes\\\\*\\\\shell\\\\Atom'\ndirectoryKeyPath = 'HKCU\\\\Software\\\\Classes\\\\d", "end": 733, "score": 0.9883415699005127, "start": 694, "tag": "KEY", "value": "HKCU\\\\Software\\\\Classes\\\\*\\\\she...
src/browser/squirrel-update.coffee
lishengze/AppClient
0
ChildProcess = require 'child_process' fs = require 'fs-plus' path = require 'path' appFolder = path.resolve(process.execPath, '..') rootAtomFolder = path.resolve(appFolder, '..') binFolder = path.join(rootAtomFolder, 'bin') updateDotExe = path.join(rootAtomFolder, 'Update.exe') exeName = path.basename(process.execPath) # exeName = '慧眼监控' if process.env.SystemRoot system32Path = path.join(process.env.SystemRoot, 'System32') regPath = path.join(system32Path, 'reg.exe') setxPath = path.join(system32Path, 'setx.exe') else regPath = 'reg.exe' setxPath = 'setx.exe' # Registry keys used for context menu 注册表信息; fileKeyPath = 'HKCU\\Software\\Classes\\*\\shell\\Atom' directoryKeyPath = 'HKCU\\Software\\Classes\\directory\\shell\\Atom' backgroundKeyPath = 'HKCU\\Software\\Classes\\directory\\background\\shell\\Atom' environmentKeyPath = 'HKCU\\Environment' # Spawn a command and invoke the callback when it completes with an error # and the output from standard out. spawn = (command, args, callback) -> stdout = '' try spawnedProcess = ChildProcess.spawn(command, args) catch error # Spawn can throw an error process.nextTick -> callback?(error, stdout) return spawnedProcess.stdout.on 'data', (data) -> stdout += data error = null spawnedProcess.on 'error', (processError) -> error ?= processError spawnedProcess.on 'close', (code, signal) -> error ?= new Error("Command failed: #{signal ? code}") if code isnt 0 error?.code ?= code error?.stdout ?= stdout callback?(error, stdout) # Spawn reg.exe and callback when it completes , 对注册表的操作; spawnReg = (args, callback) -> spawn(regPath, args, callback) # Spawn setx.exe and callback when it completes spawnSetx = (args, callback) -> spawn(setxPath, args, callback) # Spawn the Update.exe with the given arguments and invoke the callback when # the command completes. spawnUpdate = (args, callback) -> spawn(updateDotExe, args, callback) # Install the Open with Atom explorer context menu items via the registry.上下文菜单; installContextMenu = (callback) -> addToRegistry = (args, callback) -> args.unshift('add') args.push('/f') spawnReg(args, callback) installMenu = (keyPath, arg, callback) -> args = [keyPath, '/ve', '/d', 'Open with Atom'] addToRegistry args, -> args = [keyPath, '/v', 'Icon', '/d', "\"#{process.execPath}\""] addToRegistry args, -> args = ["#{keyPath}\\command", '/ve', '/d', "\"#{process.execPath}\" \"#{arg}\""] addToRegistry(args, callback) installMenu fileKeyPath, '%1', -> installMenu directoryKeyPath, '%1', -> installMenu(backgroundKeyPath, '%V', callback) isAscii = (text) -> index = 0 while index < text.length return false if text.charCodeAt(index) > 127 index++ true # Get the user's PATH environment variable registry value. getPath = (callback) -> spawnReg ['query', environmentKeyPath, '/v', 'Path'], (error, stdout) -> if error? if error.code is 1 # FIXME Don't overwrite path when reading value is disabled # https://github.com/atom/atom/issues/5092 if stdout.indexOf('ERROR: Registry editing has been disabled by your administrator.') isnt -1 return callback(error) # The query failed so the Path does not exist yet in the registry return callback(null, '') else return callback(error) # Registry query output is in the form: # # HKEY_CURRENT_USER\Environment # Path REG_SZ C:\a\folder\on\the\path;C\another\folder # lines = stdout.split(/[\r\n]+/).filter (line) -> line segments = lines[lines.length - 1]?.split(' ') if segments[1] is 'Path' and segments.length >= 3 pathEnv = segments?[3..].join(' ') if isAscii(pathEnv) callback(null, pathEnv) else # FIXME Don't corrupt non-ASCII PATH values # https://github.com/atom/atom/issues/5063 callback(new Error('PATH contains non-ASCII values')) else callback(new Error('Registry query for PATH failed')) # Uninstall the Open with Atom explorer context menu items via the registry. uninstallContextMenu = (callback) -> deleteFromRegistry = (keyPath, callback) -> spawnReg(['delete', keyPath, '/f'], callback) deleteFromRegistry fileKeyPath, -> deleteFromRegistry directoryKeyPath, -> deleteFromRegistry(backgroundKeyPath, callback) # Add atom and apm to the PATH # # This is done by adding .cmd shims to the root bin folder in the Atom # install directory that point to the newly installed versions inside # the versioned app directories. 加载环境变量; resources/win/monitor2; addCommandsToPath = (callback) -> installCommands = (callback) -> atomCommandPath = path.join(binFolder, 'monitor2.cmd') relativeAtomPath = path.relative(binFolder, path.join(appFolder, 'resources', 'cli', 'monitor2.cmd')) atomCommand = "@echo off\r\n\"%~dp0\\#{relativeAtomPath}\" %*" # atomShCommandPath = path.join(binFolder, 'atom') # relativeAtomShPath = path.relative(binFolder, path.join(appFolder, 'resources', 'cli', '慧眼监控.sh')) # atomShCommand = "#!/bin/sh\r\n\"$(dirname \"$0\")/#{relativeAtomShPath.replace(/\\/g, '/')}\" \"$@\"" # # apmCommandPath = path.join(binFolder, 'apm.cmd') # relativeApmPath = path.relative(binFolder, path.join(process.resourcesPath, 'app', 'apm', 'bin', 'apm.cmd')) # apmCommand = "@echo off\r\n\"%~dp0\\#{relativeApmPath}\" %*" # # apmShCommandPath = path.join(binFolder, 'apm') # relativeApmShPath = path.relative(binFolder, path.join(appFolder, 'resources', 'cli', 'apm.sh')) # apmShCommand = "#!/bin/sh\r\n\"$(dirname \"$0\")/#{relativeApmShPath.replace(/\\/g, '/')}\" \"$@\"" fs.writeFile atomCommandPath, atomCommand, -> callback() # fs.writeFile atomCommandPath, atomCommand, -> # fs.writeFile atomShCommandPath, atomShCommand, -> # fs.writeFile apmCommandPath, apmCommand, -> # fs.writeFile apmShCommandPath, apmShCommand, -> # callback() addBinToPath = (pathSegments, callback) -> pathSegments.push(binFolder) newPathEnv = pathSegments.join(';') spawnSetx(['Path', newPathEnv], callback) installCommands (error) -> return callback(error) if error? getPath (error, pathEnv) -> return callback(error) if error? pathSegments = pathEnv.split(/;+/).filter (pathSegment) -> pathSegment if pathSegments.indexOf(binFolder) is -1 addBinToPath(pathSegments, callback) else callback() # Remove atom and apm from the PATH removeCommandsFromPath = (callback) -> getPath (error, pathEnv) -> return callback(error) if error? pathSegments = pathEnv.split(/;+/).filter (pathSegment) -> pathSegment and pathSegment isnt binFolder newPathEnv = pathSegments.join(';') if pathEnv isnt newPathEnv spawnSetx(['Path', newPathEnv], callback) else callback() # Create a desktop and start menu shortcut by using the command line API # provided by Squirrel's Update.exe createShortcuts = (callback) -> spawnUpdate(['--createShortcut', exeName], callback) # Update the desktop and start menu shortcuts by using the command line API # provided by Squirrel's Update.exe updateShortcuts = (callback) -> if homeDirectory = fs.getHomeDirectory() desktopShortcutPath = path.join(homeDirectory, 'Desktop', '慧眼监控.lnk') # Check if the desktop shortcut has been previously deleted and # and keep it deleted if it was fs.exists desktopShortcutPath, (desktopShortcutExists) -> createShortcuts -> if desktopShortcutExists callback() else # Remove the unwanted desktop shortcut that was recreated fs.unlink(desktopShortcutPath, callback) else createShortcuts(callback) # Remove the desktop and start menu shortcuts by using the command line API # provided by Squirrel's Update.exe removeShortcuts = (callback) -> spawnUpdate(['--removeShortcut', exeName], callback) exports.spawn = spawnUpdate # Is the Update.exe installed with Atom? exports.existsSync = -> fs.existsSync(updateDotExe) # Restart Atom using the version pointed to by the 慧眼监控.cmd shim exports.restartAtom = (app) -> if projectPath = global.atomApplication?.lastFocusedWindow?.projectPath args = [projectPath] app.once 'will-quit', -> spawn(path.join(binFolder, 'monitor2.cmd'), args) app.quit() # Handle squirrel events denoted by --squirrel-* command line arguments. exports.handleStartupEvent = (app, squirrelCommand) -> switch squirrelCommand when '--squirrel-install' createShortcuts -> addCommandsToPath -> app.quit() # installContextMenu -> # addCommandsToPath -> # app.quit() true when '--squirrel-updated' updateShortcuts -> addCommandsToPath -> app.quit() # installContextMenu -> # addCommandsToPath -> # app.quit() true when '--squirrel-uninstall' removeShortcuts -> addCommandsToPath -> app.quit() # uninstallContextMenu -> # removeCommandsFromPath -> # app.quit() true when '--squirrel-obsolete' app.quit() true else false
63285
ChildProcess = require 'child_process' fs = require 'fs-plus' path = require 'path' appFolder = path.resolve(process.execPath, '..') rootAtomFolder = path.resolve(appFolder, '..') binFolder = path.join(rootAtomFolder, 'bin') updateDotExe = path.join(rootAtomFolder, 'Update.exe') exeName = path.basename(process.execPath) # exeName = '慧眼监控' if process.env.SystemRoot system32Path = path.join(process.env.SystemRoot, 'System32') regPath = path.join(system32Path, 'reg.exe') setxPath = path.join(system32Path, 'setx.exe') else regPath = 'reg.exe' setxPath = 'setx.exe' # Registry keys used for context menu 注册表信息; fileKeyPath = '<KEY>' directoryKeyPath = '<KEY>' backgroundKeyPath = '<KEY>' environmentKeyPath = '<KEY>' # Spawn a command and invoke the callback when it completes with an error # and the output from standard out. spawn = (command, args, callback) -> stdout = '' try spawnedProcess = ChildProcess.spawn(command, args) catch error # Spawn can throw an error process.nextTick -> callback?(error, stdout) return spawnedProcess.stdout.on 'data', (data) -> stdout += data error = null spawnedProcess.on 'error', (processError) -> error ?= processError spawnedProcess.on 'close', (code, signal) -> error ?= new Error("Command failed: #{signal ? code}") if code isnt 0 error?.code ?= code error?.stdout ?= stdout callback?(error, stdout) # Spawn reg.exe and callback when it completes , 对注册表的操作; spawnReg = (args, callback) -> spawn(regPath, args, callback) # Spawn setx.exe and callback when it completes spawnSetx = (args, callback) -> spawn(setxPath, args, callback) # Spawn the Update.exe with the given arguments and invoke the callback when # the command completes. spawnUpdate = (args, callback) -> spawn(updateDotExe, args, callback) # Install the Open with Atom explorer context menu items via the registry.上下文菜单; installContextMenu = (callback) -> addToRegistry = (args, callback) -> args.unshift('add') args.push('/f') spawnReg(args, callback) installMenu = (keyPath, arg, callback) -> args = [keyPath, '/ve', '/d', 'Open with Atom'] addToRegistry args, -> args = [keyPath, '/v', 'Icon', '/d', "\"#{process.execPath}\""] addToRegistry args, -> args = ["#{keyPath}\\command", '/ve', '/d', "\"#{process.execPath}\" \"#{arg}\""] addToRegistry(args, callback) installMenu fileKeyPath, '%1', -> installMenu directoryKeyPath, '%1', -> installMenu(backgroundKeyPath, '%V', callback) isAscii = (text) -> index = 0 while index < text.length return false if text.charCodeAt(index) > 127 index++ true # Get the user's PATH environment variable registry value. getPath = (callback) -> spawnReg ['query', environmentKeyPath, '/v', 'Path'], (error, stdout) -> if error? if error.code is 1 # FIXME Don't overwrite path when reading value is disabled # https://github.com/atom/atom/issues/5092 if stdout.indexOf('ERROR: Registry editing has been disabled by your administrator.') isnt -1 return callback(error) # The query failed so the Path does not exist yet in the registry return callback(null, '') else return callback(error) # Registry query output is in the form: # # HKEY_CURRENT_USER\Environment # Path REG_SZ C:\a\folder\on\the\path;C\another\folder # lines = stdout.split(/[\r\n]+/).filter (line) -> line segments = lines[lines.length - 1]?.split(' ') if segments[1] is 'Path' and segments.length >= 3 pathEnv = segments?[3..].join(' ') if isAscii(pathEnv) callback(null, pathEnv) else # FIXME Don't corrupt non-ASCII PATH values # https://github.com/atom/atom/issues/5063 callback(new Error('PATH contains non-ASCII values')) else callback(new Error('Registry query for PATH failed')) # Uninstall the Open with Atom explorer context menu items via the registry. uninstallContextMenu = (callback) -> deleteFromRegistry = (keyPath, callback) -> spawnReg(['delete', keyPath, '/f'], callback) deleteFromRegistry fileKeyPath, -> deleteFromRegistry directoryKeyPath, -> deleteFromRegistry(backgroundKeyPath, callback) # Add atom and apm to the PATH # # This is done by adding .cmd shims to the root bin folder in the Atom # install directory that point to the newly installed versions inside # the versioned app directories. 加载环境变量; resources/win/monitor2; addCommandsToPath = (callback) -> installCommands = (callback) -> atomCommandPath = path.join(binFolder, 'monitor2.cmd') relativeAtomPath = path.relative(binFolder, path.join(appFolder, 'resources', 'cli', 'monitor2.cmd')) atomCommand = "@echo off\r\n\"%~dp0\\#{relativeAtomPath}\" %*" # atomShCommandPath = path.join(binFolder, 'atom') # relativeAtomShPath = path.relative(binFolder, path.join(appFolder, 'resources', 'cli', '慧眼监控.sh')) # atomShCommand = "#!/bin/sh\r\n\"$(dirname \"$0\")/#{relativeAtomShPath.replace(/\\/g, '/')}\" \"$@\"" # # apmCommandPath = path.join(binFolder, 'apm.cmd') # relativeApmPath = path.relative(binFolder, path.join(process.resourcesPath, 'app', 'apm', 'bin', 'apm.cmd')) # apmCommand = "@echo off\r\n\"%~dp0\\#{relativeApmPath}\" %*" # # apmShCommandPath = path.join(binFolder, 'apm') # relativeApmShPath = path.relative(binFolder, path.join(appFolder, 'resources', 'cli', 'apm.sh')) # apmShCommand = "#!/bin/sh\r\n\"$(dirname \"$0\")/#{relativeApmShPath.replace(/\\/g, '/')}\" \"$@\"" fs.writeFile atomCommandPath, atomCommand, -> callback() # fs.writeFile atomCommandPath, atomCommand, -> # fs.writeFile atomShCommandPath, atomShCommand, -> # fs.writeFile apmCommandPath, apmCommand, -> # fs.writeFile apmShCommandPath, apmShCommand, -> # callback() addBinToPath = (pathSegments, callback) -> pathSegments.push(binFolder) newPathEnv = pathSegments.join(';') spawnSetx(['Path', newPathEnv], callback) installCommands (error) -> return callback(error) if error? getPath (error, pathEnv) -> return callback(error) if error? pathSegments = pathEnv.split(/;+/).filter (pathSegment) -> pathSegment if pathSegments.indexOf(binFolder) is -1 addBinToPath(pathSegments, callback) else callback() # Remove atom and apm from the PATH removeCommandsFromPath = (callback) -> getPath (error, pathEnv) -> return callback(error) if error? pathSegments = pathEnv.split(/;+/).filter (pathSegment) -> pathSegment and pathSegment isnt binFolder newPathEnv = pathSegments.join(';') if pathEnv isnt newPathEnv spawnSetx(['Path', newPathEnv], callback) else callback() # Create a desktop and start menu shortcut by using the command line API # provided by Squirrel's Update.exe createShortcuts = (callback) -> spawnUpdate(['--createShortcut', exeName], callback) # Update the desktop and start menu shortcuts by using the command line API # provided by Squirrel's Update.exe updateShortcuts = (callback) -> if homeDirectory = fs.getHomeDirectory() desktopShortcutPath = path.join(homeDirectory, 'Desktop', '慧眼监控.lnk') # Check if the desktop shortcut has been previously deleted and # and keep it deleted if it was fs.exists desktopShortcutPath, (desktopShortcutExists) -> createShortcuts -> if desktopShortcutExists callback() else # Remove the unwanted desktop shortcut that was recreated fs.unlink(desktopShortcutPath, callback) else createShortcuts(callback) # Remove the desktop and start menu shortcuts by using the command line API # provided by Squirrel's Update.exe removeShortcuts = (callback) -> spawnUpdate(['--removeShortcut', exeName], callback) exports.spawn = spawnUpdate # Is the Update.exe installed with Atom? exports.existsSync = -> fs.existsSync(updateDotExe) # Restart Atom using the version pointed to by the 慧眼监控.cmd shim exports.restartAtom = (app) -> if projectPath = global.atomApplication?.lastFocusedWindow?.projectPath args = [projectPath] app.once 'will-quit', -> spawn(path.join(binFolder, 'monitor2.cmd'), args) app.quit() # Handle squirrel events denoted by --squirrel-* command line arguments. exports.handleStartupEvent = (app, squirrelCommand) -> switch squirrelCommand when '--squirrel-install' createShortcuts -> addCommandsToPath -> app.quit() # installContextMenu -> # addCommandsToPath -> # app.quit() true when '--squirrel-updated' updateShortcuts -> addCommandsToPath -> app.quit() # installContextMenu -> # addCommandsToPath -> # app.quit() true when '--squirrel-uninstall' removeShortcuts -> addCommandsToPath -> app.quit() # uninstallContextMenu -> # removeCommandsFromPath -> # app.quit() true when '--squirrel-obsolete' app.quit() true else false
true
ChildProcess = require 'child_process' fs = require 'fs-plus' path = require 'path' appFolder = path.resolve(process.execPath, '..') rootAtomFolder = path.resolve(appFolder, '..') binFolder = path.join(rootAtomFolder, 'bin') updateDotExe = path.join(rootAtomFolder, 'Update.exe') exeName = path.basename(process.execPath) # exeName = '慧眼监控' if process.env.SystemRoot system32Path = path.join(process.env.SystemRoot, 'System32') regPath = path.join(system32Path, 'reg.exe') setxPath = path.join(system32Path, 'setx.exe') else regPath = 'reg.exe' setxPath = 'setx.exe' # Registry keys used for context menu 注册表信息; fileKeyPath = 'PI:KEY:<KEY>END_PI' directoryKeyPath = 'PI:KEY:<KEY>END_PI' backgroundKeyPath = 'PI:KEY:<KEY>END_PI' environmentKeyPath = 'PI:KEY:<KEY>END_PI' # Spawn a command and invoke the callback when it completes with an error # and the output from standard out. spawn = (command, args, callback) -> stdout = '' try spawnedProcess = ChildProcess.spawn(command, args) catch error # Spawn can throw an error process.nextTick -> callback?(error, stdout) return spawnedProcess.stdout.on 'data', (data) -> stdout += data error = null spawnedProcess.on 'error', (processError) -> error ?= processError spawnedProcess.on 'close', (code, signal) -> error ?= new Error("Command failed: #{signal ? code}") if code isnt 0 error?.code ?= code error?.stdout ?= stdout callback?(error, stdout) # Spawn reg.exe and callback when it completes , 对注册表的操作; spawnReg = (args, callback) -> spawn(regPath, args, callback) # Spawn setx.exe and callback when it completes spawnSetx = (args, callback) -> spawn(setxPath, args, callback) # Spawn the Update.exe with the given arguments and invoke the callback when # the command completes. spawnUpdate = (args, callback) -> spawn(updateDotExe, args, callback) # Install the Open with Atom explorer context menu items via the registry.上下文菜单; installContextMenu = (callback) -> addToRegistry = (args, callback) -> args.unshift('add') args.push('/f') spawnReg(args, callback) installMenu = (keyPath, arg, callback) -> args = [keyPath, '/ve', '/d', 'Open with Atom'] addToRegistry args, -> args = [keyPath, '/v', 'Icon', '/d', "\"#{process.execPath}\""] addToRegistry args, -> args = ["#{keyPath}\\command", '/ve', '/d', "\"#{process.execPath}\" \"#{arg}\""] addToRegistry(args, callback) installMenu fileKeyPath, '%1', -> installMenu directoryKeyPath, '%1', -> installMenu(backgroundKeyPath, '%V', callback) isAscii = (text) -> index = 0 while index < text.length return false if text.charCodeAt(index) > 127 index++ true # Get the user's PATH environment variable registry value. getPath = (callback) -> spawnReg ['query', environmentKeyPath, '/v', 'Path'], (error, stdout) -> if error? if error.code is 1 # FIXME Don't overwrite path when reading value is disabled # https://github.com/atom/atom/issues/5092 if stdout.indexOf('ERROR: Registry editing has been disabled by your administrator.') isnt -1 return callback(error) # The query failed so the Path does not exist yet in the registry return callback(null, '') else return callback(error) # Registry query output is in the form: # # HKEY_CURRENT_USER\Environment # Path REG_SZ C:\a\folder\on\the\path;C\another\folder # lines = stdout.split(/[\r\n]+/).filter (line) -> line segments = lines[lines.length - 1]?.split(' ') if segments[1] is 'Path' and segments.length >= 3 pathEnv = segments?[3..].join(' ') if isAscii(pathEnv) callback(null, pathEnv) else # FIXME Don't corrupt non-ASCII PATH values # https://github.com/atom/atom/issues/5063 callback(new Error('PATH contains non-ASCII values')) else callback(new Error('Registry query for PATH failed')) # Uninstall the Open with Atom explorer context menu items via the registry. uninstallContextMenu = (callback) -> deleteFromRegistry = (keyPath, callback) -> spawnReg(['delete', keyPath, '/f'], callback) deleteFromRegistry fileKeyPath, -> deleteFromRegistry directoryKeyPath, -> deleteFromRegistry(backgroundKeyPath, callback) # Add atom and apm to the PATH # # This is done by adding .cmd shims to the root bin folder in the Atom # install directory that point to the newly installed versions inside # the versioned app directories. 加载环境变量; resources/win/monitor2; addCommandsToPath = (callback) -> installCommands = (callback) -> atomCommandPath = path.join(binFolder, 'monitor2.cmd') relativeAtomPath = path.relative(binFolder, path.join(appFolder, 'resources', 'cli', 'monitor2.cmd')) atomCommand = "@echo off\r\n\"%~dp0\\#{relativeAtomPath}\" %*" # atomShCommandPath = path.join(binFolder, 'atom') # relativeAtomShPath = path.relative(binFolder, path.join(appFolder, 'resources', 'cli', '慧眼监控.sh')) # atomShCommand = "#!/bin/sh\r\n\"$(dirname \"$0\")/#{relativeAtomShPath.replace(/\\/g, '/')}\" \"$@\"" # # apmCommandPath = path.join(binFolder, 'apm.cmd') # relativeApmPath = path.relative(binFolder, path.join(process.resourcesPath, 'app', 'apm', 'bin', 'apm.cmd')) # apmCommand = "@echo off\r\n\"%~dp0\\#{relativeApmPath}\" %*" # # apmShCommandPath = path.join(binFolder, 'apm') # relativeApmShPath = path.relative(binFolder, path.join(appFolder, 'resources', 'cli', 'apm.sh')) # apmShCommand = "#!/bin/sh\r\n\"$(dirname \"$0\")/#{relativeApmShPath.replace(/\\/g, '/')}\" \"$@\"" fs.writeFile atomCommandPath, atomCommand, -> callback() # fs.writeFile atomCommandPath, atomCommand, -> # fs.writeFile atomShCommandPath, atomShCommand, -> # fs.writeFile apmCommandPath, apmCommand, -> # fs.writeFile apmShCommandPath, apmShCommand, -> # callback() addBinToPath = (pathSegments, callback) -> pathSegments.push(binFolder) newPathEnv = pathSegments.join(';') spawnSetx(['Path', newPathEnv], callback) installCommands (error) -> return callback(error) if error? getPath (error, pathEnv) -> return callback(error) if error? pathSegments = pathEnv.split(/;+/).filter (pathSegment) -> pathSegment if pathSegments.indexOf(binFolder) is -1 addBinToPath(pathSegments, callback) else callback() # Remove atom and apm from the PATH removeCommandsFromPath = (callback) -> getPath (error, pathEnv) -> return callback(error) if error? pathSegments = pathEnv.split(/;+/).filter (pathSegment) -> pathSegment and pathSegment isnt binFolder newPathEnv = pathSegments.join(';') if pathEnv isnt newPathEnv spawnSetx(['Path', newPathEnv], callback) else callback() # Create a desktop and start menu shortcut by using the command line API # provided by Squirrel's Update.exe createShortcuts = (callback) -> spawnUpdate(['--createShortcut', exeName], callback) # Update the desktop and start menu shortcuts by using the command line API # provided by Squirrel's Update.exe updateShortcuts = (callback) -> if homeDirectory = fs.getHomeDirectory() desktopShortcutPath = path.join(homeDirectory, 'Desktop', '慧眼监控.lnk') # Check if the desktop shortcut has been previously deleted and # and keep it deleted if it was fs.exists desktopShortcutPath, (desktopShortcutExists) -> createShortcuts -> if desktopShortcutExists callback() else # Remove the unwanted desktop shortcut that was recreated fs.unlink(desktopShortcutPath, callback) else createShortcuts(callback) # Remove the desktop and start menu shortcuts by using the command line API # provided by Squirrel's Update.exe removeShortcuts = (callback) -> spawnUpdate(['--removeShortcut', exeName], callback) exports.spawn = spawnUpdate # Is the Update.exe installed with Atom? exports.existsSync = -> fs.existsSync(updateDotExe) # Restart Atom using the version pointed to by the 慧眼监控.cmd shim exports.restartAtom = (app) -> if projectPath = global.atomApplication?.lastFocusedWindow?.projectPath args = [projectPath] app.once 'will-quit', -> spawn(path.join(binFolder, 'monitor2.cmd'), args) app.quit() # Handle squirrel events denoted by --squirrel-* command line arguments. exports.handleStartupEvent = (app, squirrelCommand) -> switch squirrelCommand when '--squirrel-install' createShortcuts -> addCommandsToPath -> app.quit() # installContextMenu -> # addCommandsToPath -> # app.quit() true when '--squirrel-updated' updateShortcuts -> addCommandsToPath -> app.quit() # installContextMenu -> # addCommandsToPath -> # app.quit() true when '--squirrel-uninstall' removeShortcuts -> addCommandsToPath -> app.quit() # uninstallContextMenu -> # removeCommandsFromPath -> # app.quit() true when '--squirrel-obsolete' app.quit() true else false
[ { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ", "end": 38, "score": 0.9998894929885864, "start": 25, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright...
public/taiga-front/app/coffee/modules/projects/main.coffee
mabotech/maboss
0
### # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com> # # 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: modules/common/attachments.coffee ### taiga = @.taiga module = angular.module("taigaProject") bindOnce = @.taiga.bindOnce class ProjectsController extends taiga.Controller @.$inject = [ "$scope", "$q", "$tgResources", "$rootScope", "$tgNavUrls", "$tgAuth", "$tgLocation", "$appTitle", "$projectUrl", "tgLoader" ] constructor: (@scope, @q, @rs, @rootscope, @navUrls, @auth, @location, @appTitle, @projectUrl, @tgLoader) -> @appTitle.set("Projects") if !@auth.isAuthenticated() @location.path(@navUrls.resolve("login")) @.user = @auth.getUser() @.projects = [] promise = @.loadInitialData() promise.then () => @scope.$emit("projects:loaded") @tgLoader.pageLoaded() promise.then null, @.onInitialDataError.bind(@) loadInitialData: -> return @rs.projects.list().then (projects) => @.projects = {'recents': projects.slice(0, 8), 'all': projects} for project in projects project.url = @projectUrl.get(project) return projects newProject: -> @rootscope.$broadcast("projects:create") logout: -> @auth.logout() @location.path(@navUrls.resolve("login")) module.controller("ProjectsController", ProjectsController) class ProjectController extends taiga.Controller @.$inject = [ "$scope", "$tgResources", "$tgRepo", "$routeParams", "$q", "$rootScope", "$appTitle", "$tgLocation", "$tgNavUrls" ] constructor: (@scope, @rs, @repo, @params, @q, @rootscope, @appTitle, @location, @navUrls) -> promise = @.loadInitialData() promise.then () => @appTitle.set(@scope.project.name) @scope.$emit("regenerate:project-pagination") promise.then null, @.onInitialDataError.bind(@) loadInitialData: -> # Resolve project slug promise = @repo.resolve({pslug: @params.pslug}).then (data) => @scope.projectId = data.project return data return promise.then(=> @.loadPageData()) .then(=> @scope.$emit("project:loaded", @scope.project)) loadPageData: -> return @q.all([ @.loadProjectStats(), @.loadProject()]) loadProject: -> return @rs.projects.get(@scope.projectId).then (project) => @scope.project = project return project loadProjectStats: -> return @rs.projects.stats(@scope.projectId).then (stats) => @scope.stats = stats return stats module.controller("ProjectController", ProjectController) ProjectsPaginationDirective = ($timeout) -> link = ($scope, $el, $attrs) -> prevBtn = $el.find(".v-pagination-previous") nextBtn = $el.find(".v-pagination-next") container = $el.find("ul") pageSize = 0 containerSize = 0 render = -> pageSize = $el.find(".v-pagination-list").height() if container.find("li").length if hasPagination() if hasNextPage() visible(nextBtn) else hide(nextBtn) if hasPrevPage() visible(prevBtn) else hide(prevBtn) else remove() else remove() hasPagination = -> containerSize = container.height() return containerSize > pageSize hasPrevPage = (top) -> if !top? top = -parseInt(container.css('top'), 10) || 0 return top != 0 hasNextPage = (top) -> containerSize = container.height() if !top top = -parseInt(container.css('top'), 10) || 0 return containerSize > pageSize && top + pageSize < containerSize nextPage = (callback) -> top = parseInt(container.css('top'), 10) newTop = top - pageSize lastLi = $el.find(".v-pagination-list li:last-child") maxTop = -((lastLi.position().top + lastLi.outerHeight()) - pageSize) newTop = maxTop if newTop < maxTop container.animate({"top": newTop}, callback) return newTop prevPage = (callback) -> top = parseInt(container.css('top'), 10) newTop = top + pageSize newTop = 0 if newTop > 0 container.animate({"top": newTop}, callback) return newTop visible = (element) -> element.css('visibility', 'visible') hide = (element) -> element.css('visibility', 'hidden') checkButtonVisibility = () -> remove = () -> container.css('top', 0) hide(prevBtn) hide(nextBtn) $el.on "click", ".v-pagination-previous", (event) -> event.preventDefault() if container.is(':animated') return visible(nextBtn) newTop = prevPage() if !hasPrevPage(newTop) hide(prevBtn) $el.on "click", ".v-pagination-next", (event) -> event.preventDefault() if container.is(':animated') return visible(prevBtn) newTop = -nextPage() if !hasNextPage(newTop) hide(nextBtn) $scope.$on "regenerate:project-pagination", -> remove() render() $(window).on "resize.projects-pagination", render $scope.$on "$destroy", -> $(window).off "resize.projects-pagination" return { link: link } module.directive("tgProjectsPagination", ['$timeout', ProjectsPaginationDirective]) ProjectsListDirective = ($compile) -> template = _.template(""" <div tg-projects-pagination> <div class="projects-pagination"> <a class="v-pagination-previous icon icon-arrow-up" href=""></a> <div class="v-pagination-list"> <ul class="projects-list"> <% _.each(projects, function(project) { %> <li> <a class="button" href="<%- project.url %>"> <%- project.name %> </a> </li> <% }) %> </ul> </div> <a class="v-pagination-next icon icon-arrow-bottom" href=""></a> </div> </div> """) link = ($scope, $el, $attrs, $ctrls) -> render = (projects) -> $el.html($compile(template({projects: projects}))($scope)) $scope.$emit("regenerate:project-pagination") $scope.$watch "projects", (projects) -> render(projects) if projects? return { link: link } module.directive("tgProjectsList", ["$compile", ProjectsListDirective])
91316
### # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<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: modules/common/attachments.coffee ### taiga = @.taiga module = angular.module("taigaProject") bindOnce = @.taiga.bindOnce class ProjectsController extends taiga.Controller @.$inject = [ "$scope", "$q", "$tgResources", "$rootScope", "$tgNavUrls", "$tgAuth", "$tgLocation", "$appTitle", "$projectUrl", "tgLoader" ] constructor: (@scope, @q, @rs, @rootscope, @navUrls, @auth, @location, @appTitle, @projectUrl, @tgLoader) -> @appTitle.set("Projects") if !@auth.isAuthenticated() @location.path(@navUrls.resolve("login")) @.user = @auth.getUser() @.projects = [] promise = @.loadInitialData() promise.then () => @scope.$emit("projects:loaded") @tgLoader.pageLoaded() promise.then null, @.onInitialDataError.bind(@) loadInitialData: -> return @rs.projects.list().then (projects) => @.projects = {'recents': projects.slice(0, 8), 'all': projects} for project in projects project.url = @projectUrl.get(project) return projects newProject: -> @rootscope.$broadcast("projects:create") logout: -> @auth.logout() @location.path(@navUrls.resolve("login")) module.controller("ProjectsController", ProjectsController) class ProjectController extends taiga.Controller @.$inject = [ "$scope", "$tgResources", "$tgRepo", "$routeParams", "$q", "$rootScope", "$appTitle", "$tgLocation", "$tgNavUrls" ] constructor: (@scope, @rs, @repo, @params, @q, @rootscope, @appTitle, @location, @navUrls) -> promise = @.loadInitialData() promise.then () => @appTitle.set(@scope.project.name) @scope.$emit("regenerate:project-pagination") promise.then null, @.onInitialDataError.bind(@) loadInitialData: -> # Resolve project slug promise = @repo.resolve({pslug: @params.pslug}).then (data) => @scope.projectId = data.project return data return promise.then(=> @.loadPageData()) .then(=> @scope.$emit("project:loaded", @scope.project)) loadPageData: -> return @q.all([ @.loadProjectStats(), @.loadProject()]) loadProject: -> return @rs.projects.get(@scope.projectId).then (project) => @scope.project = project return project loadProjectStats: -> return @rs.projects.stats(@scope.projectId).then (stats) => @scope.stats = stats return stats module.controller("ProjectController", ProjectController) ProjectsPaginationDirective = ($timeout) -> link = ($scope, $el, $attrs) -> prevBtn = $el.find(".v-pagination-previous") nextBtn = $el.find(".v-pagination-next") container = $el.find("ul") pageSize = 0 containerSize = 0 render = -> pageSize = $el.find(".v-pagination-list").height() if container.find("li").length if hasPagination() if hasNextPage() visible(nextBtn) else hide(nextBtn) if hasPrevPage() visible(prevBtn) else hide(prevBtn) else remove() else remove() hasPagination = -> containerSize = container.height() return containerSize > pageSize hasPrevPage = (top) -> if !top? top = -parseInt(container.css('top'), 10) || 0 return top != 0 hasNextPage = (top) -> containerSize = container.height() if !top top = -parseInt(container.css('top'), 10) || 0 return containerSize > pageSize && top + pageSize < containerSize nextPage = (callback) -> top = parseInt(container.css('top'), 10) newTop = top - pageSize lastLi = $el.find(".v-pagination-list li:last-child") maxTop = -((lastLi.position().top + lastLi.outerHeight()) - pageSize) newTop = maxTop if newTop < maxTop container.animate({"top": newTop}, callback) return newTop prevPage = (callback) -> top = parseInt(container.css('top'), 10) newTop = top + pageSize newTop = 0 if newTop > 0 container.animate({"top": newTop}, callback) return newTop visible = (element) -> element.css('visibility', 'visible') hide = (element) -> element.css('visibility', 'hidden') checkButtonVisibility = () -> remove = () -> container.css('top', 0) hide(prevBtn) hide(nextBtn) $el.on "click", ".v-pagination-previous", (event) -> event.preventDefault() if container.is(':animated') return visible(nextBtn) newTop = prevPage() if !hasPrevPage(newTop) hide(prevBtn) $el.on "click", ".v-pagination-next", (event) -> event.preventDefault() if container.is(':animated') return visible(prevBtn) newTop = -nextPage() if !hasNextPage(newTop) hide(nextBtn) $scope.$on "regenerate:project-pagination", -> remove() render() $(window).on "resize.projects-pagination", render $scope.$on "$destroy", -> $(window).off "resize.projects-pagination" return { link: link } module.directive("tgProjectsPagination", ['$timeout', ProjectsPaginationDirective]) ProjectsListDirective = ($compile) -> template = _.template(""" <div tg-projects-pagination> <div class="projects-pagination"> <a class="v-pagination-previous icon icon-arrow-up" href=""></a> <div class="v-pagination-list"> <ul class="projects-list"> <% _.each(projects, function(project) { %> <li> <a class="button" href="<%- project.url %>"> <%- project.name %> </a> </li> <% }) %> </ul> </div> <a class="v-pagination-next icon icon-arrow-bottom" href=""></a> </div> </div> """) link = ($scope, $el, $attrs, $ctrls) -> render = (projects) -> $el.html($compile(template({projects: projects}))($scope)) $scope.$emit("regenerate:project-pagination") $scope.$watch "projects", (projects) -> render(projects) if projects? return { link: link } module.directive("tgProjectsList", ["$compile", ProjectsListDirective])
true
### # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <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: modules/common/attachments.coffee ### taiga = @.taiga module = angular.module("taigaProject") bindOnce = @.taiga.bindOnce class ProjectsController extends taiga.Controller @.$inject = [ "$scope", "$q", "$tgResources", "$rootScope", "$tgNavUrls", "$tgAuth", "$tgLocation", "$appTitle", "$projectUrl", "tgLoader" ] constructor: (@scope, @q, @rs, @rootscope, @navUrls, @auth, @location, @appTitle, @projectUrl, @tgLoader) -> @appTitle.set("Projects") if !@auth.isAuthenticated() @location.path(@navUrls.resolve("login")) @.user = @auth.getUser() @.projects = [] promise = @.loadInitialData() promise.then () => @scope.$emit("projects:loaded") @tgLoader.pageLoaded() promise.then null, @.onInitialDataError.bind(@) loadInitialData: -> return @rs.projects.list().then (projects) => @.projects = {'recents': projects.slice(0, 8), 'all': projects} for project in projects project.url = @projectUrl.get(project) return projects newProject: -> @rootscope.$broadcast("projects:create") logout: -> @auth.logout() @location.path(@navUrls.resolve("login")) module.controller("ProjectsController", ProjectsController) class ProjectController extends taiga.Controller @.$inject = [ "$scope", "$tgResources", "$tgRepo", "$routeParams", "$q", "$rootScope", "$appTitle", "$tgLocation", "$tgNavUrls" ] constructor: (@scope, @rs, @repo, @params, @q, @rootscope, @appTitle, @location, @navUrls) -> promise = @.loadInitialData() promise.then () => @appTitle.set(@scope.project.name) @scope.$emit("regenerate:project-pagination") promise.then null, @.onInitialDataError.bind(@) loadInitialData: -> # Resolve project slug promise = @repo.resolve({pslug: @params.pslug}).then (data) => @scope.projectId = data.project return data return promise.then(=> @.loadPageData()) .then(=> @scope.$emit("project:loaded", @scope.project)) loadPageData: -> return @q.all([ @.loadProjectStats(), @.loadProject()]) loadProject: -> return @rs.projects.get(@scope.projectId).then (project) => @scope.project = project return project loadProjectStats: -> return @rs.projects.stats(@scope.projectId).then (stats) => @scope.stats = stats return stats module.controller("ProjectController", ProjectController) ProjectsPaginationDirective = ($timeout) -> link = ($scope, $el, $attrs) -> prevBtn = $el.find(".v-pagination-previous") nextBtn = $el.find(".v-pagination-next") container = $el.find("ul") pageSize = 0 containerSize = 0 render = -> pageSize = $el.find(".v-pagination-list").height() if container.find("li").length if hasPagination() if hasNextPage() visible(nextBtn) else hide(nextBtn) if hasPrevPage() visible(prevBtn) else hide(prevBtn) else remove() else remove() hasPagination = -> containerSize = container.height() return containerSize > pageSize hasPrevPage = (top) -> if !top? top = -parseInt(container.css('top'), 10) || 0 return top != 0 hasNextPage = (top) -> containerSize = container.height() if !top top = -parseInt(container.css('top'), 10) || 0 return containerSize > pageSize && top + pageSize < containerSize nextPage = (callback) -> top = parseInt(container.css('top'), 10) newTop = top - pageSize lastLi = $el.find(".v-pagination-list li:last-child") maxTop = -((lastLi.position().top + lastLi.outerHeight()) - pageSize) newTop = maxTop if newTop < maxTop container.animate({"top": newTop}, callback) return newTop prevPage = (callback) -> top = parseInt(container.css('top'), 10) newTop = top + pageSize newTop = 0 if newTop > 0 container.animate({"top": newTop}, callback) return newTop visible = (element) -> element.css('visibility', 'visible') hide = (element) -> element.css('visibility', 'hidden') checkButtonVisibility = () -> remove = () -> container.css('top', 0) hide(prevBtn) hide(nextBtn) $el.on "click", ".v-pagination-previous", (event) -> event.preventDefault() if container.is(':animated') return visible(nextBtn) newTop = prevPage() if !hasPrevPage(newTop) hide(prevBtn) $el.on "click", ".v-pagination-next", (event) -> event.preventDefault() if container.is(':animated') return visible(prevBtn) newTop = -nextPage() if !hasNextPage(newTop) hide(nextBtn) $scope.$on "regenerate:project-pagination", -> remove() render() $(window).on "resize.projects-pagination", render $scope.$on "$destroy", -> $(window).off "resize.projects-pagination" return { link: link } module.directive("tgProjectsPagination", ['$timeout', ProjectsPaginationDirective]) ProjectsListDirective = ($compile) -> template = _.template(""" <div tg-projects-pagination> <div class="projects-pagination"> <a class="v-pagination-previous icon icon-arrow-up" href=""></a> <div class="v-pagination-list"> <ul class="projects-list"> <% _.each(projects, function(project) { %> <li> <a class="button" href="<%- project.url %>"> <%- project.name %> </a> </li> <% }) %> </ul> </div> <a class="v-pagination-next icon icon-arrow-bottom" href=""></a> </div> </div> """) link = ($scope, $el, $attrs, $ctrls) -> render = (projects) -> $el.html($compile(template({projects: projects}))($scope)) $scope.$emit("regenerate:project-pagination") $scope.$watch "projects", (projects) -> render(projects) if projects? return { link: link } module.directive("tgProjectsList", ["$compile", ProjectsListDirective])
[ { "context": "#\n# Copyright 2017 Dr. Michael Menzel, Amazon Web Services Germany GmbH\n#\n# Licensed ", "end": 40, "score": 0.999586284160614, "start": 26, "tag": "NAME", "value": "Michael Menzel" } ]
app/components/bucket-viewer.component.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 BucketViewerController constructor: (S3, $scope) -> @scope = $scope @s3 = S3 @currentPrefix = '' $onInit: => @refresh() home: => @currentPrefix = '' @refresh() open: (prefix) => @currentPrefix = @currentPrefix + prefix @refresh() close: => @currentPrefix = @currentPrefix.slice(0, -1) if @currentPrefix.slice(-1) is '/' @currentPrefix = @currentPrefix.substr(0, @currentPrefix.lastIndexOf('/') + 1) @refresh() prefix: => @basePrefix + @currentPrefix bucketNamesList: => @bucketNames.trim().replace(' ', '').split(',') updateFiles: (newFiles) => @files = newFiles @scope.$digest() refresh: => Promise.all(@bucketNamesList().map((bucketName) => @s3.list(bucketName, @prefix()))) .then((lists) => lists.reduce((arr, val) -> arr.concat(val) , []) ).then((data) => data .map (el) => el.Key = el.Key.substr(@prefix().length) el .map (el) => if el.Key.indexOf('/') > -1 el.type = 'folder' el.Key = el.Key.substr(0, el.Key.indexOf('/') + 1) else el.type = 'file' el.Key = el.Key.substr(el.Key.lastIndexOf('/') + 1) el.url = "about:home" #@s3.downloadLink(bucketName, @prefix + el.Key).then((url) -> el.url = url) if el.type is 'file' el .reduce((a, b) -> a.push(b) if a.map((el) -> el.Key).indexOf(b.Key) < 0 a , []) ).then(@updateFiles) angular.module('DemoApp').component('bucketViewer', #Note: The URL is relative to our `index.html` file templateUrl: 'components/bucket-viewer.template.html' controller: ['S3', '$scope', BucketViewerController] bindings: bucketNames: '@' basePrefix: '@' )
69633
# # 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 BucketViewerController constructor: (S3, $scope) -> @scope = $scope @s3 = S3 @currentPrefix = '' $onInit: => @refresh() home: => @currentPrefix = '' @refresh() open: (prefix) => @currentPrefix = @currentPrefix + prefix @refresh() close: => @currentPrefix = @currentPrefix.slice(0, -1) if @currentPrefix.slice(-1) is '/' @currentPrefix = @currentPrefix.substr(0, @currentPrefix.lastIndexOf('/') + 1) @refresh() prefix: => @basePrefix + @currentPrefix bucketNamesList: => @bucketNames.trim().replace(' ', '').split(',') updateFiles: (newFiles) => @files = newFiles @scope.$digest() refresh: => Promise.all(@bucketNamesList().map((bucketName) => @s3.list(bucketName, @prefix()))) .then((lists) => lists.reduce((arr, val) -> arr.concat(val) , []) ).then((data) => data .map (el) => el.Key = el.Key.substr(@prefix().length) el .map (el) => if el.Key.indexOf('/') > -1 el.type = 'folder' el.Key = el.Key.substr(0, el.Key.indexOf('/') + 1) else el.type = 'file' el.Key = el.Key.substr(el.Key.lastIndexOf('/') + 1) el.url = "about:home" #@s3.downloadLink(bucketName, @prefix + el.Key).then((url) -> el.url = url) if el.type is 'file' el .reduce((a, b) -> a.push(b) if a.map((el) -> el.Key).indexOf(b.Key) < 0 a , []) ).then(@updateFiles) angular.module('DemoApp').component('bucketViewer', #Note: The URL is relative to our `index.html` file templateUrl: 'components/bucket-viewer.template.html' controller: ['S3', '$scope', BucketViewerController] bindings: bucketNames: '@' basePrefix: '@' )
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 BucketViewerController constructor: (S3, $scope) -> @scope = $scope @s3 = S3 @currentPrefix = '' $onInit: => @refresh() home: => @currentPrefix = '' @refresh() open: (prefix) => @currentPrefix = @currentPrefix + prefix @refresh() close: => @currentPrefix = @currentPrefix.slice(0, -1) if @currentPrefix.slice(-1) is '/' @currentPrefix = @currentPrefix.substr(0, @currentPrefix.lastIndexOf('/') + 1) @refresh() prefix: => @basePrefix + @currentPrefix bucketNamesList: => @bucketNames.trim().replace(' ', '').split(',') updateFiles: (newFiles) => @files = newFiles @scope.$digest() refresh: => Promise.all(@bucketNamesList().map((bucketName) => @s3.list(bucketName, @prefix()))) .then((lists) => lists.reduce((arr, val) -> arr.concat(val) , []) ).then((data) => data .map (el) => el.Key = el.Key.substr(@prefix().length) el .map (el) => if el.Key.indexOf('/') > -1 el.type = 'folder' el.Key = el.Key.substr(0, el.Key.indexOf('/') + 1) else el.type = 'file' el.Key = el.Key.substr(el.Key.lastIndexOf('/') + 1) el.url = "about:home" #@s3.downloadLink(bucketName, @prefix + el.Key).then((url) -> el.url = url) if el.type is 'file' el .reduce((a, b) -> a.push(b) if a.map((el) -> el.Key).indexOf(b.Key) < 0 a , []) ).then(@updateFiles) angular.module('DemoApp').component('bucketViewer', #Note: The URL is relative to our `index.html` file templateUrl: 'components/bucket-viewer.template.html' controller: ['S3', '$scope', BucketViewerController] bindings: bucketNames: '@' basePrefix: '@' )
[ { "context": "age summernoteDrafts.js\n * @version 1.0\n * @author Jessica González <suki@missallsunday.com>\n * @copyright Copyright ", "end": 79, "score": 0.9998708367347717, "start": 63, "tag": "NAME", "value": "Jessica González" }, { "context": "s.js\n * @version 1.0\n * @author ...
src/summernoteDrafts.coffee
MissAllSunday/summernoteDrafts
7
### * @package summernoteDrafts.js * @version 1.0 * @author Jessica González <suki@missallsunday.com> * @copyright Copyright (c) 2017, Jessica González * @license https://opensource.org/licenses/MIT MIT ### ((factory) -> if typeof define == 'function' and define.amd define [ 'jquery' ], factory else if typeof module == 'object' and module.exports module.exports = factory(require('jquery')) else factory window.jQuery return ) ($) -> $.extend $.summernote.options, sDrafts: storePrefix:'sDrafts' dateFormat: null saveIcon: null loadIcon: null $.extend $.summernote.lang['en-US'], sDrafts : save : 'Save draft' load : 'Load Drafts' select : 'select the draft you want to load' provideName : 'Provide a name for this draft' saved : 'Draft was successfully saved' loaded: 'Draft was successfully loaded' deleteAll: 'Delete all drafts' noDraft : 'The selected draft couldn\'t be loaded, try again or select another one' nosavedDrafts : 'There aren\'t any drafts saved' deleteDraft : 'delete' youSure : 'Are you sure you want to do this?' $.extend $.summernote.plugins, 'sDraftsSave' : (context) -> ui = $.summernote.ui options = context.options lang = options.langInfo.sDrafts $editor = context.layoutInfo.editor context.memo 'button.sDraftsSave', () -> button = ui.button contents: if options.sDrafts.saveIcon then options.sDrafts.saveIcon else lang.save tooltip: lang.save click: (e) -> e.preventDefault() context.invoke 'sDraftsSave.show' false button.render() @initialize = => $container = if options.dialogsInBody then $(document.body) else $editor body = "<div class='form-group'><label>#{lang.provideName}</label><input class='note-draftName form-control' type='text' /></div>" footer = "<button href='#' class='btn btn-primary note-link-btn'>#{lang.save}</button>" @$dialog = ui.dialog( className: 'link-dialog' title: lang.save fade: options.dialogsFade body: body footer: footer).render().appendTo $container return @destroy = => ui.hideDialog @$dialog @$dialog.remove() return @show = => ui.showDialog @$dialog $saveBtn = @$dialog.find '.note-link-btn' .click (e) => e.preventDefault draftName = @$dialog.find '.note-draftName' .val() @saveDraft draftName false @saveDraft = (name) => isoDate = new Date() .toISOString() name ?= isoDate keyName = options.sDrafts.storePrefix + '-' + name body = context.code() store.set keyName, name: name sDate: isoDate body : body alert lang.saved @destroy() return return $.extend $.summernote.plugins, 'sDraftsLoad' : (context) -> ui = $.summernote.ui options = context.options lang = options.langInfo.sDrafts $editor = context.layoutInfo.editor drafts = [] store.each (key, value) -> if typeof key is 'string' and key.indexOf(options.sDrafts.storePrefix) >= 0 drafts[key] = value htmlList = '' for key, draft of drafts do -> fDate = if options.sDrafts.dateFormat and typeof options.sDrafts.dateFormat is 'function' then options.sDrafts.dateFormat(draft.sDate) else draft.sDate htmlList += "<li class='list-group-item'><a href='#' class='note-draft' data-draft='#{key}'>#{draft.name} - <small>#{fDate}</small></a><a href='#' class='label label-danger pull-right delete-draft' data-draft='#{key}'>#{lang.deleteDraft}</a></li>" context.memo 'button.sDraftsLoad', () -> button = ui.button contents: if options.sDrafts.loadIcon then options.sDrafts.loadIcon else lang.load tooltip: lang.load click: (e) -> e.preventDefault() context.invoke 'sDraftsLoad.show' false button.render() @initialize = => $container = if options.dialogsInBody then $(document.body) else $editor body = if htmlList.length then "<h4>#{lang.select}</h4><ul class='list-group'>#{htmlList}</ul>" else "<h4>#{lang.nosavedDrafts}</h4>" footer = if htmlList.length then "<button href='#' class='btn btn-primary deleteAll'>#{lang.deleteAll}</button>" else "" @$dialog = ui.dialog( className: 'link-dialog' title: lang.load fade: options.dialogsFade body: body footer: footer).render().appendTo $container return @destroy = => ui.hideDialog @$dialog @$dialog.remove() return @show = => ui.showDialog @$dialog self = @ $selectedDraft = @$dialog.find '.note-draft' .click (e) -> e.preventDefault div = document.createElement 'div' key = $ this .data 'draft' data = drafts[key] if data div.innerHTML = data.body context.invoke('editor.insertNode', div) alert lang.loaded else alert lang.noDraft self.destroy() false $deleteDraft = @$dialog.find 'a.delete-draft' .click (e) -> if confirm lang.youSure key = $ this .data 'draft' data = drafts[key] if data store.remove key self = $ this self.parent().hide 'slow', -> $(this).remove() return else alert lang.noDraft $deleteAllDrafts = @$dialog.find 'button.deleteAll' .click (e) -> selfButton = $ this if confirm lang.youSure for key, draft of drafts do -> store.remove key uiDialog = self.$dialog.find 'ul.list-group' .hide 'slow', -> $(this).replaceWith "<h4>#{lang.nosavedDrafts}</h4>" selfButton.hide 'slow' return return return
169995
### * @package summernoteDrafts.js * @version 1.0 * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2017, <NAME> * @license https://opensource.org/licenses/MIT MIT ### ((factory) -> if typeof define == 'function' and define.amd define [ 'jquery' ], factory else if typeof module == 'object' and module.exports module.exports = factory(require('jquery')) else factory window.jQuery return ) ($) -> $.extend $.summernote.options, sDrafts: storePrefix:'sDrafts' dateFormat: null saveIcon: null loadIcon: null $.extend $.summernote.lang['en-US'], sDrafts : save : 'Save draft' load : 'Load Drafts' select : 'select the draft you want to load' provideName : 'Provide a name for this draft' saved : 'Draft was successfully saved' loaded: 'Draft was successfully loaded' deleteAll: 'Delete all drafts' noDraft : 'The selected draft couldn\'t be loaded, try again or select another one' nosavedDrafts : 'There aren\'t any drafts saved' deleteDraft : 'delete' youSure : 'Are you sure you want to do this?' $.extend $.summernote.plugins, 'sDraftsSave' : (context) -> ui = $.summernote.ui options = context.options lang = options.langInfo.sDrafts $editor = context.layoutInfo.editor context.memo 'button.sDraftsSave', () -> button = ui.button contents: if options.sDrafts.saveIcon then options.sDrafts.saveIcon else lang.save tooltip: lang.save click: (e) -> e.preventDefault() context.invoke 'sDraftsSave.show' false button.render() @initialize = => $container = if options.dialogsInBody then $(document.body) else $editor body = "<div class='form-group'><label>#{lang.provideName}</label><input class='note-draftName form-control' type='text' /></div>" footer = "<button href='#' class='btn btn-primary note-link-btn'>#{lang.save}</button>" @$dialog = ui.dialog( className: 'link-dialog' title: lang.save fade: options.dialogsFade body: body footer: footer).render().appendTo $container return @destroy = => ui.hideDialog @$dialog @$dialog.remove() return @show = => ui.showDialog @$dialog $saveBtn = @$dialog.find '.note-link-btn' .click (e) => e.preventDefault draftName = @$dialog.find '.note-draftName' .val() @saveDraft draftName false @saveDraft = (name) => isoDate = new Date() .toISOString() name ?= isoDate keyName = options.sDrafts.storePrefix <KEY> name body = context.code() store.set keyName, name: name sDate: isoDate body : body alert lang.saved @destroy() return return $.extend $.summernote.plugins, 'sDraftsLoad' : (context) -> ui = $.summernote.ui options = context.options lang = options.langInfo.sDrafts $editor = context.layoutInfo.editor drafts = [] store.each (key, value) -> if typeof key is 'string' and key.indexOf(options.sDrafts.storePrefix) >= 0 drafts[key] = value htmlList = '' for key, draft of drafts do -> fDate = if options.sDrafts.dateFormat and typeof options.sDrafts.dateFormat is 'function' then options.sDrafts.dateFormat(draft.sDate) else draft.sDate htmlList += "<li class='list-group-item'><a href='#' class='note-draft' data-draft='#{key}'>#{draft.name} - <small>#{fDate}</small></a><a href='#' class='label label-danger pull-right delete-draft' data-draft='#{key}'>#{lang.deleteDraft}</a></li>" context.memo 'button.sDraftsLoad', () -> button = ui.button contents: if options.sDrafts.loadIcon then options.sDrafts.loadIcon else lang.load tooltip: lang.load click: (e) -> e.preventDefault() context.invoke 'sDraftsLoad.show' false button.render() @initialize = => $container = if options.dialogsInBody then $(document.body) else $editor body = if htmlList.length then "<h4>#{lang.select}</h4><ul class='list-group'>#{htmlList}</ul>" else "<h4>#{lang.nosavedDrafts}</h4>" footer = if htmlList.length then "<button href='#' class='btn btn-primary deleteAll'>#{lang.deleteAll}</button>" else "" @$dialog = ui.dialog( className: 'link-dialog' title: lang.load fade: options.dialogsFade body: body footer: footer).render().appendTo $container return @destroy = => ui.hideDialog @$dialog @$dialog.remove() return @show = => ui.showDialog @$dialog self = @ $selectedDraft = @$dialog.find '.note-draft' .click (e) -> e.preventDefault div = document.createElement 'div' key = $ this .data 'draft' data = drafts[key] if data div.innerHTML = data.body context.invoke('editor.insertNode', div) alert lang.loaded else alert lang.noDraft self.destroy() false $deleteDraft = @$dialog.find 'a.delete-draft' .click (e) -> if confirm lang.youSure key = $ this .data 'draft' data = drafts[key] if data store.remove key self = $ this self.parent().hide 'slow', -> $(this).remove() return else alert lang.noDraft $deleteAllDrafts = @$dialog.find 'button.deleteAll' .click (e) -> selfButton = $ this if confirm lang.youSure for key, draft of drafts do -> store.remove key uiDialog = self.$dialog.find 'ul.list-group' .hide 'slow', -> $(this).replaceWith "<h4>#{lang.nosavedDrafts}</h4>" selfButton.hide 'slow' return return return
true
### * @package summernoteDrafts.js * @version 1.0 * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * @copyright Copyright (c) 2017, PI:NAME:<NAME>END_PI * @license https://opensource.org/licenses/MIT MIT ### ((factory) -> if typeof define == 'function' and define.amd define [ 'jquery' ], factory else if typeof module == 'object' and module.exports module.exports = factory(require('jquery')) else factory window.jQuery return ) ($) -> $.extend $.summernote.options, sDrafts: storePrefix:'sDrafts' dateFormat: null saveIcon: null loadIcon: null $.extend $.summernote.lang['en-US'], sDrafts : save : 'Save draft' load : 'Load Drafts' select : 'select the draft you want to load' provideName : 'Provide a name for this draft' saved : 'Draft was successfully saved' loaded: 'Draft was successfully loaded' deleteAll: 'Delete all drafts' noDraft : 'The selected draft couldn\'t be loaded, try again or select another one' nosavedDrafts : 'There aren\'t any drafts saved' deleteDraft : 'delete' youSure : 'Are you sure you want to do this?' $.extend $.summernote.plugins, 'sDraftsSave' : (context) -> ui = $.summernote.ui options = context.options lang = options.langInfo.sDrafts $editor = context.layoutInfo.editor context.memo 'button.sDraftsSave', () -> button = ui.button contents: if options.sDrafts.saveIcon then options.sDrafts.saveIcon else lang.save tooltip: lang.save click: (e) -> e.preventDefault() context.invoke 'sDraftsSave.show' false button.render() @initialize = => $container = if options.dialogsInBody then $(document.body) else $editor body = "<div class='form-group'><label>#{lang.provideName}</label><input class='note-draftName form-control' type='text' /></div>" footer = "<button href='#' class='btn btn-primary note-link-btn'>#{lang.save}</button>" @$dialog = ui.dialog( className: 'link-dialog' title: lang.save fade: options.dialogsFade body: body footer: footer).render().appendTo $container return @destroy = => ui.hideDialog @$dialog @$dialog.remove() return @show = => ui.showDialog @$dialog $saveBtn = @$dialog.find '.note-link-btn' .click (e) => e.preventDefault draftName = @$dialog.find '.note-draftName' .val() @saveDraft draftName false @saveDraft = (name) => isoDate = new Date() .toISOString() name ?= isoDate keyName = options.sDrafts.storePrefix PI:KEY:<KEY>END_PI name body = context.code() store.set keyName, name: name sDate: isoDate body : body alert lang.saved @destroy() return return $.extend $.summernote.plugins, 'sDraftsLoad' : (context) -> ui = $.summernote.ui options = context.options lang = options.langInfo.sDrafts $editor = context.layoutInfo.editor drafts = [] store.each (key, value) -> if typeof key is 'string' and key.indexOf(options.sDrafts.storePrefix) >= 0 drafts[key] = value htmlList = '' for key, draft of drafts do -> fDate = if options.sDrafts.dateFormat and typeof options.sDrafts.dateFormat is 'function' then options.sDrafts.dateFormat(draft.sDate) else draft.sDate htmlList += "<li class='list-group-item'><a href='#' class='note-draft' data-draft='#{key}'>#{draft.name} - <small>#{fDate}</small></a><a href='#' class='label label-danger pull-right delete-draft' data-draft='#{key}'>#{lang.deleteDraft}</a></li>" context.memo 'button.sDraftsLoad', () -> button = ui.button contents: if options.sDrafts.loadIcon then options.sDrafts.loadIcon else lang.load tooltip: lang.load click: (e) -> e.preventDefault() context.invoke 'sDraftsLoad.show' false button.render() @initialize = => $container = if options.dialogsInBody then $(document.body) else $editor body = if htmlList.length then "<h4>#{lang.select}</h4><ul class='list-group'>#{htmlList}</ul>" else "<h4>#{lang.nosavedDrafts}</h4>" footer = if htmlList.length then "<button href='#' class='btn btn-primary deleteAll'>#{lang.deleteAll}</button>" else "" @$dialog = ui.dialog( className: 'link-dialog' title: lang.load fade: options.dialogsFade body: body footer: footer).render().appendTo $container return @destroy = => ui.hideDialog @$dialog @$dialog.remove() return @show = => ui.showDialog @$dialog self = @ $selectedDraft = @$dialog.find '.note-draft' .click (e) -> e.preventDefault div = document.createElement 'div' key = $ this .data 'draft' data = drafts[key] if data div.innerHTML = data.body context.invoke('editor.insertNode', div) alert lang.loaded else alert lang.noDraft self.destroy() false $deleteDraft = @$dialog.find 'a.delete-draft' .click (e) -> if confirm lang.youSure key = $ this .data 'draft' data = drafts[key] if data store.remove key self = $ this self.parent().hide 'slow', -> $(this).remove() return else alert lang.noDraft $deleteAllDrafts = @$dialog.find 'button.deleteAll' .click (e) -> selfButton = $ this if confirm lang.youSure for key, draft of drafts do -> store.remove key uiDialog = self.$dialog.find 'ul.list-group' .hide 'slow', -> $(this).replaceWith "<h4>#{lang.nosavedDrafts}</h4>" selfButton.hide 'slow' return return return
[ { "context": " ->\n article = {\n author_id: '5086df098523e60002000018'\n published: tr", "end": 1117, "score": 0.5270767211914062, "start": 1116, "tag": "USERNAME", "value": "5" }, { "context": "->\n article = {\n author_id: '5086df...
src/api/apps/articles/test/model/distribute.test.coffee
artsyjian/positron
0
{ EDITORIAL_CHANNEL } = process.env _ = require 'underscore' rewire = require 'rewire' { fabricate, empty } = require '../../../../test/helpers/db' Distribute = rewire '../../model/distribute' express = require 'express' gravity = require('@artsy/antigravity').server app = require('express')() sinon = require 'sinon' describe 'Save', -> before (done) -> app.use '/__gravity', gravity @server = app.listen 5000, -> done() after -> @server.close() beforeEach (done) -> @sailthru = Distribute.__get__ 'sailthru' @sailthru.apiPost = sinon.stub().yields() @sailthru.apiDelete = sinon.stub().yields() Distribute.__set__ 'sailthru', @sailthru Distribute.__set__ 'request', post: (@post = sinon.stub()).returns send: (@send = sinon.stub()).returns end: sinon.stub().yields() empty -> fabricate 'articles', _.times(10, -> {}), -> done() describe '#distributeArticle', -> describe 'sends article to sailthru', -> describe 'article url', -> article = {} beforeEach -> article = { author_id: '5086df098523e60002000018' published: true slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' ] } it 'constructs the url for classic articles', (done) -> article.layout = 'classic' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('article/artsy-editorial-slug-two') done() it 'constructs the url for standard articles', (done) -> article.layout = 'standard' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('article/artsy-editorial-slug-two') done() it 'constructs the url for feature articles', (done) -> article.layout = 'feature' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('article/artsy-editorial-slug-two') done() it 'constructs the url for series articles', (done) -> article.layout = 'series' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('series/artsy-editorial-slug-two') done() it 'constructs the url for video articles', (done) -> article.layout = 'video' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('video/artsy-editorial-slug-two') done() it 'constructs the url for news articles', (done) -> article.layout = 'news' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('news/artsy-editorial-slug-two') done() it 'concats the article tag for a normal article', (done) -> Distribute.distributeArticle { author_id: '5086df098523e60002000018' published: true }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].tags.should.containEql 'article' @sailthru.apiPost.args[0][1].tags.should.not.containEql 'artsy-editorial' done() it 'concats the article and artsy-editorial tag for editorial channel', (done) -> Distribute.distributeArticle { author_id: '5086df098523e60002000018' published: true channel_id: EDITORIAL_CHANNEL }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].tags.should.containEql 'article' @sailthru.apiPost.args[0][1].tags.should.containEql 'artsy-editorial' done() it 'does not send if it is scheduled', (done) -> Distribute.distributeArticle { author_id: '5086df098523e60002000018' published: false scheduled_publish_at: '10-10-11' }, (err, article) => @sailthru.apiPost.calledOnce.should.be.false() done() it 'concats the tracking_tags and vertical', (done) -> Distribute.distributeArticle { author_id: '5086df098523e60002000018' published: true keywords: ['China'] tracking_tags: ['explainers', 'profiles'] vertical: {name: 'culture', id: '591b0babc88a280f5e9efa7a'} }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].tags.should.containEql 'China' @sailthru.apiPost.args[0][1].tags.should.containEql 'explainers' @sailthru.apiPost.args[0][1].tags.should.containEql 'profiles' @sailthru.apiPost.args[0][1].tags.should.containEql 'culture' done() it 'sends vertical as a custom variable', (done) -> Distribute.distributeArticle { author_id: '5086df098523e60002000018' published: true vertical: { name: 'culture', id: '591b0babc88a280f5e9efa7a' } }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].vars.vertical.should.equal 'culture' done() it 'sends layout as a custom variable', (done) -> Distribute.distributeArticle { author_id: '5086df098523e60002000018' published: true layout: 'news' }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].vars.layout.should.equal 'news' done() it 'concats the keywords at the end', (done) -> Distribute.distributeArticle { author_id: '5086df098523e60002000018' published: true keywords: ['sofa', 'midcentury', 'knoll'] }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].tags[0].should.equal 'article' @sailthru.apiPost.args[0][1].tags[1].should.equal 'sofa' @sailthru.apiPost.args[0][1].tags[2].should.equal 'midcentury' @sailthru.apiPost.args[0][1].tags[3].should.equal 'knoll' done() it 'uses email_metadata vars if provided', (done) -> Distribute.distributeArticle { author_id: '5086df098523e60002000018' published: true email_metadata: headline: 'Article Email Title' author: 'Kana Abe' image_url: 'imageurl.com/image.jpg' }, (err, article) => @sailthru.apiPost.args[0][1].title.should.containEql 'Article Email Title' @sailthru.apiPost.args[0][1].author.should.containEql 'Kana Abe' @sailthru.apiPost.args[0][1].images.full.url.should.containEql '&width=1200&height=706&quality=95&src=imageurl.com%2Fimage.jpg' @sailthru.apiPost.args[0][1].images.thumb.url.should.containEql '&width=900&height=530&quality=95&src=imageurl.com%2Fimage.jpg' done() it 'sends the article text body', (done) -> Distribute.distributeArticle { author_id: '5086df098523e60002000018' published: true send_body: true sections: [ { type: 'text' body: '<html>BODY OF TEXT</html>' } { type: 'image_collection' images: [ caption: 'This Caption' url: 'URL' ] } ] }, (err, article) => @sailthru.apiPost.args[0][1].vars.html.should.containEql '<html>BODY OF TEXT</html>' @sailthru.apiPost.args[0][1].vars.html.should.not.containEql 'This Caption' done() it 'deletes all previously formed slugs in Sailthru', (done) -> Distribute.distributeArticle { author_id: '5086df098523e60002000018' published: true slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' 'artsy-editorial-slug-three' ] }, (err, article) => @sailthru.apiDelete.callCount.should.equal 2 @sailthru.apiDelete.args[0][1].url.should.containEql 'slug-one' @sailthru.apiDelete.args[1][1].url.should.containEql 'slug-two' done() describe '#deleteArticleFromSailthru', -> it 'deletes the article from sailthru', (done) -> Distribute.deleteArticleFromSailthru 'artsy-editorial-delete-me', (err, article) => @sailthru.apiDelete.args[0][1].url.should.containEql 'artsy-editorial-delete-me' done() describe '#cleanArticlesInSailthru', -> it 'Calls #deleteArticleFromSailthru on slugs that are not last', (done) -> Distribute.deleteArticleFromSailthru = sinon.stub() Distribute.cleanArticlesInSailthru({ author_id: '5086df098523e60002000018' layout: 'video' published: true slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' 'artsy-editorial-slug-three' ] }) Distribute.deleteArticleFromSailthru.args[0][0].should.containEql '/video/artsy-editorial-slug-one' Distribute.deleteArticleFromSailthru.args[1][0].should.containEql '/video/artsy-editorial-slug-two' done() describe '#getArticleUrl', -> it 'constructs the url for an article using the last slug by default', -> article = { layout: 'classic' slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' ] } url = Distribute.getArticleUrl article url.should.containEql('article/artsy-editorial-slug-two') it 'Can use a specified slug if provided', -> article = { layout: 'classic' slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' ] } url = Distribute.getArticleUrl article, article.slugs[0] url.should.containEql('article/artsy-editorial-slug-one')
1182
{ EDITORIAL_CHANNEL } = process.env _ = require 'underscore' rewire = require 'rewire' { fabricate, empty } = require '../../../../test/helpers/db' Distribute = rewire '../../model/distribute' express = require 'express' gravity = require('@artsy/antigravity').server app = require('express')() sinon = require 'sinon' describe 'Save', -> before (done) -> app.use '/__gravity', gravity @server = app.listen 5000, -> done() after -> @server.close() beforeEach (done) -> @sailthru = Distribute.__get__ 'sailthru' @sailthru.apiPost = sinon.stub().yields() @sailthru.apiDelete = sinon.stub().yields() Distribute.__set__ 'sailthru', @sailthru Distribute.__set__ 'request', post: (@post = sinon.stub()).returns send: (@send = sinon.stub()).returns end: sinon.stub().yields() empty -> fabricate 'articles', _.times(10, -> {}), -> done() describe '#distributeArticle', -> describe 'sends article to sailthru', -> describe 'article url', -> article = {} beforeEach -> article = { author_id: '5<PASSWORD>' published: true slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' ] } it 'constructs the url for classic articles', (done) -> article.layout = 'classic' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('article/artsy-editorial-slug-two') done() it 'constructs the url for standard articles', (done) -> article.layout = 'standard' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('article/artsy-editorial-slug-two') done() it 'constructs the url for feature articles', (done) -> article.layout = 'feature' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('article/artsy-editorial-slug-two') done() it 'constructs the url for series articles', (done) -> article.layout = 'series' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('series/artsy-editorial-slug-two') done() it 'constructs the url for video articles', (done) -> article.layout = 'video' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('video/artsy-editorial-slug-two') done() it 'constructs the url for news articles', (done) -> article.layout = 'news' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('news/artsy-editorial-slug-two') done() it 'concats the article tag for a normal article', (done) -> Distribute.distributeArticle { author_id: '5<PASSWORD>' published: true }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].tags.should.containEql 'article' @sailthru.apiPost.args[0][1].tags.should.not.containEql 'artsy-editorial' done() it 'concats the article and artsy-editorial tag for editorial channel', (done) -> Distribute.distributeArticle { author_id: '5086df098523e60002000018' published: true channel_id: EDITORIAL_CHANNEL }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].tags.should.containEql 'article' @sailthru.apiPost.args[0][1].tags.should.containEql 'artsy-editorial' done() it 'does not send if it is scheduled', (done) -> Distribute.distributeArticle { author_id: '5<PASSWORD>' published: false scheduled_publish_at: '10-10-11' }, (err, article) => @sailthru.apiPost.calledOnce.should.be.false() done() it 'concats the tracking_tags and vertical', (done) -> Distribute.distributeArticle { author_id: '5<PASSWORD>' published: true keywords: ['China'] tracking_tags: ['explainers', 'profiles'] vertical: {name: 'culture', id: '591b0babc88a280f5e9efa7a'} }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].tags.should.containEql 'China' @sailthru.apiPost.args[0][1].tags.should.containEql 'explainers' @sailthru.apiPost.args[0][1].tags.should.containEql 'profiles' @sailthru.apiPost.args[0][1].tags.should.containEql 'culture' done() it 'sends vertical as a custom variable', (done) -> Distribute.distributeArticle { author_id: '5<PASSWORD>60002000018' published: true vertical: { name: 'culture', id: '591b0babc88a280f5e9efa7a' } }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].vars.vertical.should.equal 'culture' done() it 'sends layout as a custom variable', (done) -> Distribute.distributeArticle { author_id: '5<PASSWORD>' published: true layout: 'news' }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].vars.layout.should.equal 'news' done() it 'concats the keywords at the end', (done) -> Distribute.distributeArticle { author_id: '5<PASSWORD>' published: true keywords: ['sofa', 'midcentury', 'knoll'] }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].tags[0].should.equal 'article' @sailthru.apiPost.args[0][1].tags[1].should.equal 'sofa' @sailthru.apiPost.args[0][1].tags[2].should.equal 'midcentury' @sailthru.apiPost.args[0][1].tags[3].should.equal 'knoll' done() it 'uses email_metadata vars if provided', (done) -> Distribute.distributeArticle { author_id: '5<PASSWORD>' published: true email_metadata: headline: 'Article Email Title' author: '<NAME>' image_url: 'imageurl.com/image.jpg' }, (err, article) => @sailthru.apiPost.args[0][1].title.should.containEql 'Article Email Title' @sailthru.apiPost.args[0][1].author.should.containEql '<NAME>' @sailthru.apiPost.args[0][1].images.full.url.should.containEql '&width=1200&height=706&quality=95&src=imageurl.com%2Fimage.jpg' @sailthru.apiPost.args[0][1].images.thumb.url.should.containEql '&width=900&height=530&quality=95&src=imageurl.com%2Fimage.jpg' done() it 'sends the article text body', (done) -> Distribute.distributeArticle { author_id: '<PASSWORD>' published: true send_body: true sections: [ { type: 'text' body: '<html>BODY OF TEXT</html>' } { type: 'image_collection' images: [ caption: 'This Caption' url: 'URL' ] } ] }, (err, article) => @sailthru.apiPost.args[0][1].vars.html.should.containEql '<html>BODY OF TEXT</html>' @sailthru.apiPost.args[0][1].vars.html.should.not.containEql 'This Caption' done() it 'deletes all previously formed slugs in Sailthru', (done) -> Distribute.distributeArticle { author_id: '<PASSWORD>' published: true slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' 'artsy-editorial-slug-three' ] }, (err, article) => @sailthru.apiDelete.callCount.should.equal 2 @sailthru.apiDelete.args[0][1].url.should.containEql 'slug-one' @sailthru.apiDelete.args[1][1].url.should.containEql 'slug-two' done() describe '#deleteArticleFromSailthru', -> it 'deletes the article from sailthru', (done) -> Distribute.deleteArticleFromSailthru 'artsy-editorial-delete-me', (err, article) => @sailthru.apiDelete.args[0][1].url.should.containEql 'artsy-editorial-delete-me' done() describe '#cleanArticlesInSailthru', -> it 'Calls #deleteArticleFromSailthru on slugs that are not last', (done) -> Distribute.deleteArticleFromSailthru = sinon.stub() Distribute.cleanArticlesInSailthru({ author_id: '<PASSWORD>' layout: 'video' published: true slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' 'artsy-editorial-slug-three' ] }) Distribute.deleteArticleFromSailthru.args[0][0].should.containEql '/video/artsy-editorial-slug-one' Distribute.deleteArticleFromSailthru.args[1][0].should.containEql '/video/artsy-editorial-slug-two' done() describe '#getArticleUrl', -> it 'constructs the url for an article using the last slug by default', -> article = { layout: 'classic' slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' ] } url = Distribute.getArticleUrl article url.should.containEql('article/artsy-editorial-slug-two') it 'Can use a specified slug if provided', -> article = { layout: 'classic' slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' ] } url = Distribute.getArticleUrl article, article.slugs[0] url.should.containEql('article/artsy-editorial-slug-one')
true
{ EDITORIAL_CHANNEL } = process.env _ = require 'underscore' rewire = require 'rewire' { fabricate, empty } = require '../../../../test/helpers/db' Distribute = rewire '../../model/distribute' express = require 'express' gravity = require('@artsy/antigravity').server app = require('express')() sinon = require 'sinon' describe 'Save', -> before (done) -> app.use '/__gravity', gravity @server = app.listen 5000, -> done() after -> @server.close() beforeEach (done) -> @sailthru = Distribute.__get__ 'sailthru' @sailthru.apiPost = sinon.stub().yields() @sailthru.apiDelete = sinon.stub().yields() Distribute.__set__ 'sailthru', @sailthru Distribute.__set__ 'request', post: (@post = sinon.stub()).returns send: (@send = sinon.stub()).returns end: sinon.stub().yields() empty -> fabricate 'articles', _.times(10, -> {}), -> done() describe '#distributeArticle', -> describe 'sends article to sailthru', -> describe 'article url', -> article = {} beforeEach -> article = { author_id: '5PI:PASSWORD:<PASSWORD>END_PI' published: true slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' ] } it 'constructs the url for classic articles', (done) -> article.layout = 'classic' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('article/artsy-editorial-slug-two') done() it 'constructs the url for standard articles', (done) -> article.layout = 'standard' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('article/artsy-editorial-slug-two') done() it 'constructs the url for feature articles', (done) -> article.layout = 'feature' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('article/artsy-editorial-slug-two') done() it 'constructs the url for series articles', (done) -> article.layout = 'series' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('series/artsy-editorial-slug-two') done() it 'constructs the url for video articles', (done) -> article.layout = 'video' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('video/artsy-editorial-slug-two') done() it 'constructs the url for news articles', (done) -> article.layout = 'news' Distribute.distributeArticle article, (err, article) -> @sailthru.apiPost.args[0][1].url.should.containEql('news/artsy-editorial-slug-two') done() it 'concats the article tag for a normal article', (done) -> Distribute.distributeArticle { author_id: '5PI:PASSWORD:<PASSWORD>END_PI' published: true }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].tags.should.containEql 'article' @sailthru.apiPost.args[0][1].tags.should.not.containEql 'artsy-editorial' done() it 'concats the article and artsy-editorial tag for editorial channel', (done) -> Distribute.distributeArticle { author_id: '5086df098523e60002000018' published: true channel_id: EDITORIAL_CHANNEL }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].tags.should.containEql 'article' @sailthru.apiPost.args[0][1].tags.should.containEql 'artsy-editorial' done() it 'does not send if it is scheduled', (done) -> Distribute.distributeArticle { author_id: '5PI:PASSWORD:<PASSWORD>END_PI' published: false scheduled_publish_at: '10-10-11' }, (err, article) => @sailthru.apiPost.calledOnce.should.be.false() done() it 'concats the tracking_tags and vertical', (done) -> Distribute.distributeArticle { author_id: '5PI:PASSWORD:<PASSWORD>END_PI' published: true keywords: ['China'] tracking_tags: ['explainers', 'profiles'] vertical: {name: 'culture', id: '591b0babc88a280f5e9efa7a'} }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].tags.should.containEql 'China' @sailthru.apiPost.args[0][1].tags.should.containEql 'explainers' @sailthru.apiPost.args[0][1].tags.should.containEql 'profiles' @sailthru.apiPost.args[0][1].tags.should.containEql 'culture' done() it 'sends vertical as a custom variable', (done) -> Distribute.distributeArticle { author_id: '5PI:PASSWORD:<PASSWORD>END_PI60002000018' published: true vertical: { name: 'culture', id: '591b0babc88a280f5e9efa7a' } }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].vars.vertical.should.equal 'culture' done() it 'sends layout as a custom variable', (done) -> Distribute.distributeArticle { author_id: '5PI:PASSWORD:<PASSWORD>END_PI' published: true layout: 'news' }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].vars.layout.should.equal 'news' done() it 'concats the keywords at the end', (done) -> Distribute.distributeArticle { author_id: '5PI:PASSWORD:<PASSWORD>END_PI' published: true keywords: ['sofa', 'midcentury', 'knoll'] }, (err, article) => @sailthru.apiPost.calledOnce.should.be.true() @sailthru.apiPost.args[0][1].tags[0].should.equal 'article' @sailthru.apiPost.args[0][1].tags[1].should.equal 'sofa' @sailthru.apiPost.args[0][1].tags[2].should.equal 'midcentury' @sailthru.apiPost.args[0][1].tags[3].should.equal 'knoll' done() it 'uses email_metadata vars if provided', (done) -> Distribute.distributeArticle { author_id: '5PI:PASSWORD:<PASSWORD>END_PI' published: true email_metadata: headline: 'Article Email Title' author: 'PI:NAME:<NAME>END_PI' image_url: 'imageurl.com/image.jpg' }, (err, article) => @sailthru.apiPost.args[0][1].title.should.containEql 'Article Email Title' @sailthru.apiPost.args[0][1].author.should.containEql 'PI:NAME:<NAME>END_PI' @sailthru.apiPost.args[0][1].images.full.url.should.containEql '&width=1200&height=706&quality=95&src=imageurl.com%2Fimage.jpg' @sailthru.apiPost.args[0][1].images.thumb.url.should.containEql '&width=900&height=530&quality=95&src=imageurl.com%2Fimage.jpg' done() it 'sends the article text body', (done) -> Distribute.distributeArticle { author_id: 'PI:PASSWORD:<PASSWORD>END_PI' published: true send_body: true sections: [ { type: 'text' body: '<html>BODY OF TEXT</html>' } { type: 'image_collection' images: [ caption: 'This Caption' url: 'URL' ] } ] }, (err, article) => @sailthru.apiPost.args[0][1].vars.html.should.containEql '<html>BODY OF TEXT</html>' @sailthru.apiPost.args[0][1].vars.html.should.not.containEql 'This Caption' done() it 'deletes all previously formed slugs in Sailthru', (done) -> Distribute.distributeArticle { author_id: 'PI:PASSWORD:<PASSWORD>END_PI' published: true slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' 'artsy-editorial-slug-three' ] }, (err, article) => @sailthru.apiDelete.callCount.should.equal 2 @sailthru.apiDelete.args[0][1].url.should.containEql 'slug-one' @sailthru.apiDelete.args[1][1].url.should.containEql 'slug-two' done() describe '#deleteArticleFromSailthru', -> it 'deletes the article from sailthru', (done) -> Distribute.deleteArticleFromSailthru 'artsy-editorial-delete-me', (err, article) => @sailthru.apiDelete.args[0][1].url.should.containEql 'artsy-editorial-delete-me' done() describe '#cleanArticlesInSailthru', -> it 'Calls #deleteArticleFromSailthru on slugs that are not last', (done) -> Distribute.deleteArticleFromSailthru = sinon.stub() Distribute.cleanArticlesInSailthru({ author_id: 'PI:PASSWORD:<PASSWORD>END_PI' layout: 'video' published: true slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' 'artsy-editorial-slug-three' ] }) Distribute.deleteArticleFromSailthru.args[0][0].should.containEql '/video/artsy-editorial-slug-one' Distribute.deleteArticleFromSailthru.args[1][0].should.containEql '/video/artsy-editorial-slug-two' done() describe '#getArticleUrl', -> it 'constructs the url for an article using the last slug by default', -> article = { layout: 'classic' slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' ] } url = Distribute.getArticleUrl article url.should.containEql('article/artsy-editorial-slug-two') it 'Can use a specified slug if provided', -> article = { layout: 'classic' slugs: [ 'artsy-editorial-slug-one' 'artsy-editorial-slug-two' ] } url = Distribute.getArticleUrl article, article.slugs[0] url.should.containEql('article/artsy-editorial-slug-one')
[ { "context": "endencies\", (done) ->\n firstName = Observable \"Duder\"\n lastName = Observable \"Man\"\n\n o = Observa", "end": 4600, "score": 0.9997354745864868, "start": 4595, "tag": "NAME", "value": "Duder" }, { "context": "e = Observable \"Duder\"\n lastName = Observ...
test/observable.coffee
distri/observable
14
{Observable} = require "../" assert = require "assert" describe 'Observable', -> it "should create an observable with no value", -> o = Observable() assert.equal o(), undefined it 'should create an observable for an object', -> n = 5 observable = Observable(n) assert.equal(observable(), n) it 'should fire events when setting', -> string = "yolo" observable = Observable(string) observable.observe (newValue) -> assert.equal newValue, "4life" observable("4life") it "should not fire when setting to the same value", -> o = Observable 5 o.observe -> assert false o(5) it 'should be idempotent', -> o = Observable(5) assert.equal o, Observable(o) it "should create an observbale for objects that have a non-function observe property", -> o = Observable observe: false assert.deepEqual o(), observe: false it "should have releaseDependencies as a noop because primitive observables don't have any dependencies", -> o = Observable(5) o.releaseDependencies() it "should provide an updating non-observing semi-private reference to value", -> o = Observable(5) assert.equal o._value, 5 o 7 assert.equal o._value, 7 o2 = Observable -> o._value o3 = Observable -> o() assert.equal o2(), 7 assert.equal o3(), 7 o 9 assert.equal o2(), 7 assert.equal o2._value, 7 assert.equal o3(), 9 assert.equal o3._value, 9 assert.equal o._value, 9 it "should allow for stopping observation", -> observable = Observable("string") called = 0 fn = (newValue="") -> called += 1 assert.equal newValue, "4life" observable.observe fn observable("4life") observable.stopObserving fn observable("wat") assert.equal called, 1 it "should do nothing when removing a listener that's not present", -> observable = Observable("string") observable.stopObserving -> it "should increment", -> observable = Observable 1 observable.increment(5) assert.equal observable(), 6 observable.increment() assert.equal observable(), 7 observable.increment(0.05) assert.equal observable(), 7.05 observable.increment(0.05) assert.equal observable(), 7.10 it "should decremnet", -> observable = Observable 1 observable.decrement 5 assert.equal observable(), -4 observable.decrement() assert.equal observable(), -5 it "should toggle", -> observable = Observable false observable.toggle() assert.equal observable(), true observable.toggle() assert.equal observable(), false it "should trigger when toggling", (done) -> observable = Observable true observable.observe (v) -> assert.equal v, false done() observable.toggle() it "should have a nice toString", -> observable = Observable 5 assert.equal observable.toString(), "Observable(5)" describe "Observable Array", -> it "should proxy array methods", -> o = Observable [5] o.map (n) -> assert.equal n, 5 it "should notify on mutation methods", (done) -> o = Observable [0] o.observe (newValue) -> assert.equal newValue[1], 1 o.push 1 done() it "#get", -> o = Observable [0, 1, 2, 3] assert.equal o.get(2), 2 it "#first", -> o = Observable [0, 1, 2, 3] assert.equal o.first(), 0 it "#last", -> o = Observable [0, 1, 2, 3] assert.equal o.last(), 3 it "#remove", -> o = Observable [0, 1, 2, 3] assert.equal o.remove(2), 2 assert.equal o.length, 3 assert.equal o.remove(-5), undefined assert.equal o.length, 3 it "#remove non-existent element", -> o = Observable [1, 2, 3] assert.equal o.remove(0), undefined it "should proxy the length property", -> o = Observable [1, 2, 3] assert.equal o.length, 3 called = false o.observe (value) -> assert.equal value[0], 1 assert.equal value[1], undefined called = true o.length = 1 assert.equal o.length, 1 assert.equal called, true it "should auto detect conditionals of length as a dependency", -> observableArray = Observable [1, 2, 3] o = Observable -> if observableArray.length > 5 true else false assert.equal o(), false called = 0 o.observe -> called += 1 observableArray.push 4, 5, 6 assert.equal called, 1 describe "Observable functions", -> it "should compute dependencies", (done) -> firstName = Observable "Duder" lastName = Observable "Man" o = Observable -> "#{firstName()} #{lastName()}" o.observe (newValue) -> assert.equal newValue, "Duder Bro" done() lastName "Bro" it "should compute array#get as a dependency", -> observableArray = Observable [0, 1, 2] observableFn = Observable -> observableArray.get(0) assert.equal observableFn(), 0 observableArray([5]) assert.equal observableFn(), 5 it "should compute array#first as a dependency", -> observableArray = Observable [0, 1, 2] observableFn = Observable -> observableArray.first() + 1 assert.equal observableFn(), 1 observableArray([5]) assert.equal observableFn(), 6 it "should compute array#last as a dependency", -> observableArray = Observable [0, 1, 2] observableFn = Observable -> observableArray.last() assert.equal observableFn(), 2 observableArray.pop() assert.equal observableFn(), 1 observableArray([5]) assert.equal observableFn(), 5 it "should compute array#size as a dependency", -> observableArray = Observable [0, 1, 2] observableFn = Observable -> observableArray.length * 2 assert.equal observableFn(), 6 observableArray.pop() assert.equal observableFn(), 4 observableArray.shift() assert.equal observableFn(), 2 it "should allow double nesting", (done) -> bottom = Observable "rad" middle = Observable -> bottom() top = Observable -> middle() top.observe (newValue) -> assert.equal newValue, "wat" assert.equal top(), newValue assert.equal middle(), newValue done() bottom("wat") it "should work with dynamic dependencies", -> observableArray = Observable [ age: Observable 1 ] dynamicObservable = Observable -> observableArray.filter (item) -> item.age() > 3 assert.equal dynamicObservable().length, 0 observableArray()[0]?.age 5 assert.equal dynamicObservable().length, 1 it "should work with context", -> model = a: Observable "Hello" b: Observable "there" c: -> "#{@a()} #{@b()}" model.c = Observable model.c, model assert.equal model.c(), "Hello there" model.b "world" assert.equal model.c(), "Hello world" it "should be ok even if the function throws an exception", -> assert.throws -> Observable -> throw "wat" # TODO: Should be able to find a test case that is affected by this rather than # checking it directly assert.equal Observable.OBSERVABLE_ROOT.length, 0 it "should work on an array dependency", -> oA = Observable [1, 2, 3] o = Observable -> oA()[0] last = Observable -> oA()[oA().length-1] assert.equal o(), 1 oA.unshift 0 assert.equal o(), 0 oA.push 4 assert.equal last(), 4, "Last should be 4" it "should work with multiple dependencies", -> letter = Observable "A" checked = -> l = letter() # @ts-ignore @name().indexOf(l) is 0 first = name: Observable("Andrew") checked: checked first.checked = Observable checked, first second = name: Observable("Benjamin") checked: checked second.checked = Observable checked, second assert.equal first.checked(), true assert.equal second.checked(), false assert.equal letter.listeners.length, 2 letter "B" assert.equal first.checked(), false assert.equal second.checked(), true it "shouldn't double count dependencies", -> dep = Observable "yo" o = Observable -> dep() dep() dep() count = 0 o.observe -> count += 1 dep('heyy') assert.equal count, 1 it "should recompute the correct number of times", -> joiner = Observable "," items = Observable [ "A" "B" "C" ] called = 0 fn = Observable -> called += 1 items.join joiner() assert.equal fn(), "A,B,C" assert.equal called, 1 items.push "D" assert.equal fn(), "A,B,C,D" assert.equal called, 2 joiner "." assert.equal fn(), "A.B.C.D" assert.equal called, 3 items.push "E" assert.equal fn(), "A.B.C.D.E" assert.equal called, 4 it "should work with nested observable construction", -> gen = Observable -> Observable "Duder" o = gen() o2 = gen() assert.equal o, o2 assert.equal o(), "Duder" o("wat") assert.equal o(), "wat" it "should be scoped to optional context", (done) -> model = firstName: Observable "Duder" lastName: Observable "Man" name: -> "#{@firstName()} #{@lastName()}" (model.name = Observable model.name, model) .observe (newValue) -> assert.equal newValue, "Duder Bro" done() model.lastName "Bro"
142722
{Observable} = require "../" assert = require "assert" describe 'Observable', -> it "should create an observable with no value", -> o = Observable() assert.equal o(), undefined it 'should create an observable for an object', -> n = 5 observable = Observable(n) assert.equal(observable(), n) it 'should fire events when setting', -> string = "yolo" observable = Observable(string) observable.observe (newValue) -> assert.equal newValue, "4life" observable("4life") it "should not fire when setting to the same value", -> o = Observable 5 o.observe -> assert false o(5) it 'should be idempotent', -> o = Observable(5) assert.equal o, Observable(o) it "should create an observbale for objects that have a non-function observe property", -> o = Observable observe: false assert.deepEqual o(), observe: false it "should have releaseDependencies as a noop because primitive observables don't have any dependencies", -> o = Observable(5) o.releaseDependencies() it "should provide an updating non-observing semi-private reference to value", -> o = Observable(5) assert.equal o._value, 5 o 7 assert.equal o._value, 7 o2 = Observable -> o._value o3 = Observable -> o() assert.equal o2(), 7 assert.equal o3(), 7 o 9 assert.equal o2(), 7 assert.equal o2._value, 7 assert.equal o3(), 9 assert.equal o3._value, 9 assert.equal o._value, 9 it "should allow for stopping observation", -> observable = Observable("string") called = 0 fn = (newValue="") -> called += 1 assert.equal newValue, "4life" observable.observe fn observable("4life") observable.stopObserving fn observable("wat") assert.equal called, 1 it "should do nothing when removing a listener that's not present", -> observable = Observable("string") observable.stopObserving -> it "should increment", -> observable = Observable 1 observable.increment(5) assert.equal observable(), 6 observable.increment() assert.equal observable(), 7 observable.increment(0.05) assert.equal observable(), 7.05 observable.increment(0.05) assert.equal observable(), 7.10 it "should decremnet", -> observable = Observable 1 observable.decrement 5 assert.equal observable(), -4 observable.decrement() assert.equal observable(), -5 it "should toggle", -> observable = Observable false observable.toggle() assert.equal observable(), true observable.toggle() assert.equal observable(), false it "should trigger when toggling", (done) -> observable = Observable true observable.observe (v) -> assert.equal v, false done() observable.toggle() it "should have a nice toString", -> observable = Observable 5 assert.equal observable.toString(), "Observable(5)" describe "Observable Array", -> it "should proxy array methods", -> o = Observable [5] o.map (n) -> assert.equal n, 5 it "should notify on mutation methods", (done) -> o = Observable [0] o.observe (newValue) -> assert.equal newValue[1], 1 o.push 1 done() it "#get", -> o = Observable [0, 1, 2, 3] assert.equal o.get(2), 2 it "#first", -> o = Observable [0, 1, 2, 3] assert.equal o.first(), 0 it "#last", -> o = Observable [0, 1, 2, 3] assert.equal o.last(), 3 it "#remove", -> o = Observable [0, 1, 2, 3] assert.equal o.remove(2), 2 assert.equal o.length, 3 assert.equal o.remove(-5), undefined assert.equal o.length, 3 it "#remove non-existent element", -> o = Observable [1, 2, 3] assert.equal o.remove(0), undefined it "should proxy the length property", -> o = Observable [1, 2, 3] assert.equal o.length, 3 called = false o.observe (value) -> assert.equal value[0], 1 assert.equal value[1], undefined called = true o.length = 1 assert.equal o.length, 1 assert.equal called, true it "should auto detect conditionals of length as a dependency", -> observableArray = Observable [1, 2, 3] o = Observable -> if observableArray.length > 5 true else false assert.equal o(), false called = 0 o.observe -> called += 1 observableArray.push 4, 5, 6 assert.equal called, 1 describe "Observable functions", -> it "should compute dependencies", (done) -> firstName = Observable "<NAME>" lastName = Observable "<NAME>" o = Observable -> "#{firstName()} #{lastName()}" o.observe (newValue) -> assert.equal newValue, "<NAME>" done() lastName "<NAME>" it "should compute array#get as a dependency", -> observableArray = Observable [0, 1, 2] observableFn = Observable -> observableArray.get(0) assert.equal observableFn(), 0 observableArray([5]) assert.equal observableFn(), 5 it "should compute array#first as a dependency", -> observableArray = Observable [0, 1, 2] observableFn = Observable -> observableArray.first() + 1 assert.equal observableFn(), 1 observableArray([5]) assert.equal observableFn(), 6 it "should compute array#last as a dependency", -> observableArray = Observable [0, 1, 2] observableFn = Observable -> observableArray.last() assert.equal observableFn(), 2 observableArray.pop() assert.equal observableFn(), 1 observableArray([5]) assert.equal observableFn(), 5 it "should compute array#size as a dependency", -> observableArray = Observable [0, 1, 2] observableFn = Observable -> observableArray.length * 2 assert.equal observableFn(), 6 observableArray.pop() assert.equal observableFn(), 4 observableArray.shift() assert.equal observableFn(), 2 it "should allow double nesting", (done) -> bottom = Observable "rad" middle = Observable -> bottom() top = Observable -> middle() top.observe (newValue) -> assert.equal newValue, "wat" assert.equal top(), newValue assert.equal middle(), newValue done() bottom("wat") it "should work with dynamic dependencies", -> observableArray = Observable [ age: Observable 1 ] dynamicObservable = Observable -> observableArray.filter (item) -> item.age() > 3 assert.equal dynamicObservable().length, 0 observableArray()[0]?.age 5 assert.equal dynamicObservable().length, 1 it "should work with context", -> model = a: Observable "Hello" b: Observable "there" c: -> "#{@a()} #{@b()}" model.c = Observable model.c, model assert.equal model.c(), "Hello there" model.b "world" assert.equal model.c(), "Hello world" it "should be ok even if the function throws an exception", -> assert.throws -> Observable -> throw "wat" # TODO: Should be able to find a test case that is affected by this rather than # checking it directly assert.equal Observable.OBSERVABLE_ROOT.length, 0 it "should work on an array dependency", -> oA = Observable [1, 2, 3] o = Observable -> oA()[0] last = Observable -> oA()[oA().length-1] assert.equal o(), 1 oA.unshift 0 assert.equal o(), 0 oA.push 4 assert.equal last(), 4, "Last should be 4" it "should work with multiple dependencies", -> letter = Observable "A" checked = -> l = letter() # @ts-ignore @name().indexOf(l) is 0 first = name: Observable("<NAME>") checked: checked first.checked = Observable checked, first second = name: Observable("<NAME>") checked: checked second.checked = Observable checked, second assert.equal first.checked(), true assert.equal second.checked(), false assert.equal letter.listeners.length, 2 letter "B" assert.equal first.checked(), false assert.equal second.checked(), true it "shouldn't double count dependencies", -> dep = Observable "yo" o = Observable -> dep() dep() dep() count = 0 o.observe -> count += 1 dep('heyy') assert.equal count, 1 it "should recompute the correct number of times", -> joiner = Observable "," items = Observable [ "A" "B" "C" ] called = 0 fn = Observable -> called += 1 items.join joiner() assert.equal fn(), "A,B,C" assert.equal called, 1 items.push "D" assert.equal fn(), "A,B,C,D" assert.equal called, 2 joiner "." assert.equal fn(), "A.B.C.D" assert.equal called, 3 items.push "E" assert.equal fn(), "A.B.C.D.E" assert.equal called, 4 it "should work with nested observable construction", -> gen = Observable -> Observable "Duder" o = gen() o2 = gen() assert.equal o, o2 assert.equal o(), "Duder" o("wat") assert.equal o(), "wat" it "should be scoped to optional context", (done) -> model = firstName: Observable "<NAME>" lastName: Observable "<NAME>" name: -> "#{@firstName()} #{@lastName()}" (model.name = Observable model.name, model) .observe (newValue) -> assert.equal newValue, "<NAME>" done() model.lastName "Bro"
true
{Observable} = require "../" assert = require "assert" describe 'Observable', -> it "should create an observable with no value", -> o = Observable() assert.equal o(), undefined it 'should create an observable for an object', -> n = 5 observable = Observable(n) assert.equal(observable(), n) it 'should fire events when setting', -> string = "yolo" observable = Observable(string) observable.observe (newValue) -> assert.equal newValue, "4life" observable("4life") it "should not fire when setting to the same value", -> o = Observable 5 o.observe -> assert false o(5) it 'should be idempotent', -> o = Observable(5) assert.equal o, Observable(o) it "should create an observbale for objects that have a non-function observe property", -> o = Observable observe: false assert.deepEqual o(), observe: false it "should have releaseDependencies as a noop because primitive observables don't have any dependencies", -> o = Observable(5) o.releaseDependencies() it "should provide an updating non-observing semi-private reference to value", -> o = Observable(5) assert.equal o._value, 5 o 7 assert.equal o._value, 7 o2 = Observable -> o._value o3 = Observable -> o() assert.equal o2(), 7 assert.equal o3(), 7 o 9 assert.equal o2(), 7 assert.equal o2._value, 7 assert.equal o3(), 9 assert.equal o3._value, 9 assert.equal o._value, 9 it "should allow for stopping observation", -> observable = Observable("string") called = 0 fn = (newValue="") -> called += 1 assert.equal newValue, "4life" observable.observe fn observable("4life") observable.stopObserving fn observable("wat") assert.equal called, 1 it "should do nothing when removing a listener that's not present", -> observable = Observable("string") observable.stopObserving -> it "should increment", -> observable = Observable 1 observable.increment(5) assert.equal observable(), 6 observable.increment() assert.equal observable(), 7 observable.increment(0.05) assert.equal observable(), 7.05 observable.increment(0.05) assert.equal observable(), 7.10 it "should decremnet", -> observable = Observable 1 observable.decrement 5 assert.equal observable(), -4 observable.decrement() assert.equal observable(), -5 it "should toggle", -> observable = Observable false observable.toggle() assert.equal observable(), true observable.toggle() assert.equal observable(), false it "should trigger when toggling", (done) -> observable = Observable true observable.observe (v) -> assert.equal v, false done() observable.toggle() it "should have a nice toString", -> observable = Observable 5 assert.equal observable.toString(), "Observable(5)" describe "Observable Array", -> it "should proxy array methods", -> o = Observable [5] o.map (n) -> assert.equal n, 5 it "should notify on mutation methods", (done) -> o = Observable [0] o.observe (newValue) -> assert.equal newValue[1], 1 o.push 1 done() it "#get", -> o = Observable [0, 1, 2, 3] assert.equal o.get(2), 2 it "#first", -> o = Observable [0, 1, 2, 3] assert.equal o.first(), 0 it "#last", -> o = Observable [0, 1, 2, 3] assert.equal o.last(), 3 it "#remove", -> o = Observable [0, 1, 2, 3] assert.equal o.remove(2), 2 assert.equal o.length, 3 assert.equal o.remove(-5), undefined assert.equal o.length, 3 it "#remove non-existent element", -> o = Observable [1, 2, 3] assert.equal o.remove(0), undefined it "should proxy the length property", -> o = Observable [1, 2, 3] assert.equal o.length, 3 called = false o.observe (value) -> assert.equal value[0], 1 assert.equal value[1], undefined called = true o.length = 1 assert.equal o.length, 1 assert.equal called, true it "should auto detect conditionals of length as a dependency", -> observableArray = Observable [1, 2, 3] o = Observable -> if observableArray.length > 5 true else false assert.equal o(), false called = 0 o.observe -> called += 1 observableArray.push 4, 5, 6 assert.equal called, 1 describe "Observable functions", -> it "should compute dependencies", (done) -> firstName = Observable "PI:NAME:<NAME>END_PI" lastName = Observable "PI:NAME:<NAME>END_PI" o = Observable -> "#{firstName()} #{lastName()}" o.observe (newValue) -> assert.equal newValue, "PI:NAME:<NAME>END_PI" done() lastName "PI:NAME:<NAME>END_PI" it "should compute array#get as a dependency", -> observableArray = Observable [0, 1, 2] observableFn = Observable -> observableArray.get(0) assert.equal observableFn(), 0 observableArray([5]) assert.equal observableFn(), 5 it "should compute array#first as a dependency", -> observableArray = Observable [0, 1, 2] observableFn = Observable -> observableArray.first() + 1 assert.equal observableFn(), 1 observableArray([5]) assert.equal observableFn(), 6 it "should compute array#last as a dependency", -> observableArray = Observable [0, 1, 2] observableFn = Observable -> observableArray.last() assert.equal observableFn(), 2 observableArray.pop() assert.equal observableFn(), 1 observableArray([5]) assert.equal observableFn(), 5 it "should compute array#size as a dependency", -> observableArray = Observable [0, 1, 2] observableFn = Observable -> observableArray.length * 2 assert.equal observableFn(), 6 observableArray.pop() assert.equal observableFn(), 4 observableArray.shift() assert.equal observableFn(), 2 it "should allow double nesting", (done) -> bottom = Observable "rad" middle = Observable -> bottom() top = Observable -> middle() top.observe (newValue) -> assert.equal newValue, "wat" assert.equal top(), newValue assert.equal middle(), newValue done() bottom("wat") it "should work with dynamic dependencies", -> observableArray = Observable [ age: Observable 1 ] dynamicObservable = Observable -> observableArray.filter (item) -> item.age() > 3 assert.equal dynamicObservable().length, 0 observableArray()[0]?.age 5 assert.equal dynamicObservable().length, 1 it "should work with context", -> model = a: Observable "Hello" b: Observable "there" c: -> "#{@a()} #{@b()}" model.c = Observable model.c, model assert.equal model.c(), "Hello there" model.b "world" assert.equal model.c(), "Hello world" it "should be ok even if the function throws an exception", -> assert.throws -> Observable -> throw "wat" # TODO: Should be able to find a test case that is affected by this rather than # checking it directly assert.equal Observable.OBSERVABLE_ROOT.length, 0 it "should work on an array dependency", -> oA = Observable [1, 2, 3] o = Observable -> oA()[0] last = Observable -> oA()[oA().length-1] assert.equal o(), 1 oA.unshift 0 assert.equal o(), 0 oA.push 4 assert.equal last(), 4, "Last should be 4" it "should work with multiple dependencies", -> letter = Observable "A" checked = -> l = letter() # @ts-ignore @name().indexOf(l) is 0 first = name: Observable("PI:NAME:<NAME>END_PI") checked: checked first.checked = Observable checked, first second = name: Observable("PI:NAME:<NAME>END_PI") checked: checked second.checked = Observable checked, second assert.equal first.checked(), true assert.equal second.checked(), false assert.equal letter.listeners.length, 2 letter "B" assert.equal first.checked(), false assert.equal second.checked(), true it "shouldn't double count dependencies", -> dep = Observable "yo" o = Observable -> dep() dep() dep() count = 0 o.observe -> count += 1 dep('heyy') assert.equal count, 1 it "should recompute the correct number of times", -> joiner = Observable "," items = Observable [ "A" "B" "C" ] called = 0 fn = Observable -> called += 1 items.join joiner() assert.equal fn(), "A,B,C" assert.equal called, 1 items.push "D" assert.equal fn(), "A,B,C,D" assert.equal called, 2 joiner "." assert.equal fn(), "A.B.C.D" assert.equal called, 3 items.push "E" assert.equal fn(), "A.B.C.D.E" assert.equal called, 4 it "should work with nested observable construction", -> gen = Observable -> Observable "Duder" o = gen() o2 = gen() assert.equal o, o2 assert.equal o(), "Duder" o("wat") assert.equal o(), "wat" it "should be scoped to optional context", (done) -> model = firstName: Observable "PI:NAME:<NAME>END_PI" lastName: Observable "PI:NAME:<NAME>END_PI" name: -> "#{@firstName()} #{@lastName()}" (model.name = Observable model.name, model) .observe (newValue) -> assert.equal newValue, "PI:NAME:<NAME>END_PI" done() model.lastName "Bro"
[ { "context": "o.equal 1\n\t\t\t\texpect(data.data[0].name).to.equal 'David Kudera'\n\t\t\t\texpect(ares.lastOriginalData).not.to.be.null", "end": 532, "score": 0.9998636245727539, "start": 520, "tag": "NAME", "value": "David Kudera" } ]
test/tests/Ares.coffee
ezo5/Node-AresData
5
Ares = require '../../src/Ares' http = require 'browser-http' Http = null ares = null describe 'Ares', -> beforeEach( -> Http = new http.Mocks.Http ares = new Ares('http://localhost/') ares.http = Http ) describe '#findByIdentification()', -> it 'should load old information about author', (done) -> Http.receive(require('../responses/employer'), 'content-type': 'text/xml') ares.findByIdentification(88241653, (data) -> expect(data.length).to.equal 1 expect(data.data[0].name).to.equal 'David Kudera' expect(ares.lastOriginalData).not.to.be.null done() ) it 'should load informations about some random companies', (done) -> Http.receive(require('../responses/companies'), 'content-type': 'text/xml') ares.findByCompanyName('IBM', (data) -> expect(data.length).to.be.above 1 expect(ares.lastOriginalData).not.to.be.null done() ) it 'should return an error for bad company identification', (done) -> ares.findByIdentification(12345678, (data, err) -> expect(err).to.be.an.instanceof(Error) expect(err.message).to.be.equal('Company identification is not valid') done() ) it 'should return an error for more results than limit', (done) -> Http.receive(require('../responses/limitError'), 'content-type': 'text/xml') ares.findByCompanyName('europa', (data, err) -> expect(err).to.be.an.instanceof(Error) expect(err.message).to.be.equal('Na zadaný Dotaz by se vrátilo více odpovědí, než odpovídá parametru max_pocet. POZOR! Hrozí zablokování Vaší IP adresy! Prosím čtěte http://wwwinfo.mfcr.cz/ares/ares_xml_standard.html.cz#max') done() )
18159
Ares = require '../../src/Ares' http = require 'browser-http' Http = null ares = null describe 'Ares', -> beforeEach( -> Http = new http.Mocks.Http ares = new Ares('http://localhost/') ares.http = Http ) describe '#findByIdentification()', -> it 'should load old information about author', (done) -> Http.receive(require('../responses/employer'), 'content-type': 'text/xml') ares.findByIdentification(88241653, (data) -> expect(data.length).to.equal 1 expect(data.data[0].name).to.equal '<NAME>' expect(ares.lastOriginalData).not.to.be.null done() ) it 'should load informations about some random companies', (done) -> Http.receive(require('../responses/companies'), 'content-type': 'text/xml') ares.findByCompanyName('IBM', (data) -> expect(data.length).to.be.above 1 expect(ares.lastOriginalData).not.to.be.null done() ) it 'should return an error for bad company identification', (done) -> ares.findByIdentification(12345678, (data, err) -> expect(err).to.be.an.instanceof(Error) expect(err.message).to.be.equal('Company identification is not valid') done() ) it 'should return an error for more results than limit', (done) -> Http.receive(require('../responses/limitError'), 'content-type': 'text/xml') ares.findByCompanyName('europa', (data, err) -> expect(err).to.be.an.instanceof(Error) expect(err.message).to.be.equal('Na zadaný Dotaz by se vrátilo více odpovědí, než odpovídá parametru max_pocet. POZOR! Hrozí zablokování Vaší IP adresy! Prosím čtěte http://wwwinfo.mfcr.cz/ares/ares_xml_standard.html.cz#max') done() )
true
Ares = require '../../src/Ares' http = require 'browser-http' Http = null ares = null describe 'Ares', -> beforeEach( -> Http = new http.Mocks.Http ares = new Ares('http://localhost/') ares.http = Http ) describe '#findByIdentification()', -> it 'should load old information about author', (done) -> Http.receive(require('../responses/employer'), 'content-type': 'text/xml') ares.findByIdentification(88241653, (data) -> expect(data.length).to.equal 1 expect(data.data[0].name).to.equal 'PI:NAME:<NAME>END_PI' expect(ares.lastOriginalData).not.to.be.null done() ) it 'should load informations about some random companies', (done) -> Http.receive(require('../responses/companies'), 'content-type': 'text/xml') ares.findByCompanyName('IBM', (data) -> expect(data.length).to.be.above 1 expect(ares.lastOriginalData).not.to.be.null done() ) it 'should return an error for bad company identification', (done) -> ares.findByIdentification(12345678, (data, err) -> expect(err).to.be.an.instanceof(Error) expect(err.message).to.be.equal('Company identification is not valid') done() ) it 'should return an error for more results than limit', (done) -> Http.receive(require('../responses/limitError'), 'content-type': 'text/xml') ares.findByCompanyName('europa', (data, err) -> expect(err).to.be.an.instanceof(Error) expect(err.message).to.be.equal('Na zadaný Dotaz by se vrátilo více odpovědí, než odpovídá parametru max_pocet. POZOR! Hrozí zablokování Vaší IP adresy! Prosím čtěte http://wwwinfo.mfcr.cz/ares/ares_xml_standard.html.cz#max') done() )
[ { "context": "ormation, please see the LICENSE file\n\n@author Bryan Conrad <bkconrad@gmail.com>\n@copyright 2016 Bryan Conra", "end": 156, "score": 0.9998883008956909, "start": 144, "tag": "NAME", "value": "Bryan Conrad" }, { "context": "e see the LICENSE file\n\n@author Br...
src/ScreepsStatsd.coffee
screepers/screeps-grafana
70
### hopsoft\screeps-statsd Licensed under the MIT license For full copyright and license information, please see the LICENSE file @author Bryan Conrad <bkconrad@gmail.com> @copyright 2016 Bryan Conrad @link https://github.com/hopsoft/docker-graphite-statsd @license http://choosealicense.com/licenses/MIT MIT License ### ### SimpleClass documentation @since 0.1.0 ### rp = require 'request-promise' zlib = require 'zlib' # require('request-debug')(rp) StatsD = require 'node-statsd' token = "" succes = false class ScreepsStatsd ### Do absolutely nothing and still return something @param {string} string The string to be returned - untouched, of course @return string @since 0.1.0 ### run: ( string ) -> rp.defaults jar: true @loop() setInterval @loop, 15000 loop: () => @signin() signin: () => if(token != "" && succes) @getMemory() return @client = new StatsD host: process.env.GRAPHITE_PORT_8125_UDP_ADDR console.log "New login request - " + new Date() options = uri: 'https://screeps.com/api/auth/signin' json: true method: 'POST' body: email: process.env.SCREEPS_EMAIL password: process.env.SCREEPS_PASSWORD rp(options).then (x) => token = x.token @getMemory() getMemory: () => succes = false options = uri: 'https://screeps.com/api/user/memory' method: 'GET' json: true resolveWithFullResponse: true headers: "X-Token": token "X-Username": token qs: path: 'stats' shard: process.env.SCREEPS_SHARD rp(options).then (x) => # yeah... dunno why token = x.headers['x-token'] return unless x.body.data data = x.body.data.split('gz:')[1] finalData = JSON.parse zlib.gunzipSync(new Buffer(data, 'base64')).toString() succes = true @report(finalData) report: (data, prefix="") => if prefix is '' console.log "Pushing to gauges - " + new Date() for k,v of data if typeof v is 'object' @report(v, prefix+k+'.') else @client.gauge prefix+k, v module.exports = ScreepsStatsd
78073
### hopsoft\screeps-statsd Licensed under the MIT license For full copyright and license information, please see the LICENSE file @author <NAME> <<EMAIL>> @copyright 2016 <NAME> @link https://github.com/hopsoft/docker-graphite-statsd @license http://choosealicense.com/licenses/MIT MIT License ### ### SimpleClass documentation @since 0.1.0 ### rp = require 'request-promise' zlib = require 'zlib' # require('request-debug')(rp) StatsD = require 'node-statsd' token = "" succes = false class ScreepsStatsd ### Do absolutely nothing and still return something @param {string} string The string to be returned - untouched, of course @return string @since 0.1.0 ### run: ( string ) -> rp.defaults jar: true @loop() setInterval @loop, 15000 loop: () => @signin() signin: () => if(token != "" && succes) @getMemory() return @client = new StatsD host: process.env.GRAPHITE_PORT_8125_UDP_ADDR console.log "New login request - " + new Date() options = uri: 'https://screeps.com/api/auth/signin' json: true method: 'POST' body: email: process.env.SCREEPS_EMAIL password: <PASSWORD> rp(options).then (x) => token = x.token @getMemory() getMemory: () => succes = false options = uri: 'https://screeps.com/api/user/memory' method: 'GET' json: true resolveWithFullResponse: true headers: "X-Token": token "X-Username": token qs: path: 'stats' shard: process.env.SCREEPS_SHARD rp(options).then (x) => # yeah... dunno why token = x.headers['x-token'] return unless x.body.data data = x.body.data.split('gz:')[1] finalData = JSON.parse zlib.gunzipSync(new Buffer(data, 'base64')).toString() succes = true @report(finalData) report: (data, prefix="") => if prefix is '' console.log "Pushing to gauges - " + new Date() for k,v of data if typeof v is 'object' @report(v, prefix+k+'.') else @client.gauge prefix+k, v module.exports = ScreepsStatsd
true
### hopsoft\screeps-statsd Licensed under the MIT license For full copyright and license information, please see the LICENSE file @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> @copyright 2016 PI:NAME:<NAME>END_PI @link https://github.com/hopsoft/docker-graphite-statsd @license http://choosealicense.com/licenses/MIT MIT License ### ### SimpleClass documentation @since 0.1.0 ### rp = require 'request-promise' zlib = require 'zlib' # require('request-debug')(rp) StatsD = require 'node-statsd' token = "" succes = false class ScreepsStatsd ### Do absolutely nothing and still return something @param {string} string The string to be returned - untouched, of course @return string @since 0.1.0 ### run: ( string ) -> rp.defaults jar: true @loop() setInterval @loop, 15000 loop: () => @signin() signin: () => if(token != "" && succes) @getMemory() return @client = new StatsD host: process.env.GRAPHITE_PORT_8125_UDP_ADDR console.log "New login request - " + new Date() options = uri: 'https://screeps.com/api/auth/signin' json: true method: 'POST' body: email: process.env.SCREEPS_EMAIL password: PI:PASSWORD:<PASSWORD>END_PI rp(options).then (x) => token = x.token @getMemory() getMemory: () => succes = false options = uri: 'https://screeps.com/api/user/memory' method: 'GET' json: true resolveWithFullResponse: true headers: "X-Token": token "X-Username": token qs: path: 'stats' shard: process.env.SCREEPS_SHARD rp(options).then (x) => # yeah... dunno why token = x.headers['x-token'] return unless x.body.data data = x.body.data.split('gz:')[1] finalData = JSON.parse zlib.gunzipSync(new Buffer(data, 'base64')).toString() succes = true @report(finalData) report: (data, prefix="") => if prefix is '' console.log "Pushing to gauges - " + new Date() for k,v of data if typeof v is 'object' @report(v, prefix+k+'.') else @client.gauge prefix+k, v module.exports = ScreepsStatsd
[ { "context": "Description:\\n\\n\" +\n \"Copyright (c) 2016-2018, Jericho Crosby <jericho.crosby227@gmail.com>\\n\" +\n \"Notice: ", "end": 1092, "score": 0.9998893141746521, "start": 1078, "tag": "NAME", "value": "Jericho Crosby" }, { "context": " +\n \"Copyright (c) 201...
Miscellaneous/Atom/snippets.cson
logan737/HALO-SCRIPT-PROJECTS
0
'.source.lua': 'random': 'prefix': 'random' 'body': 'math.random()' 'math.random': 'prefix': 'math.random' 'body': 'math.random()' 'end': 'prefix': 'end' 'body': 'end' 'then': 'prefix': 'then' 'body': 'then' 'write_word': 'prefix': 'write_word' 'body': 'write_word' 'execute_command': 'prefix': 'execute_command' 'body': 'execute_command' 'function': 'prefix': 'function' 'body': 'function' 'functoin': 'prefix': 'functoin' 'body': 'function' 'true': 'prefix': 'true' 'body': 'true' 'mapname': 'prefix': 'mapname' 'body': 'mapname = get_var(0, "$map")' 'mapname': 'prefix': 'mapname' 'body': "line 1\n" + "line 2\n" + "line 3" 'script_title': 'prefix': 'script_title' 'body': "--[[\n" + "--=====================================================================================================--\n" + "Script Name: Document_Name, for SAPP (PC & CE)\n" + "Description:\n\n" + "Copyright (c) 2016-2018, Jericho Crosby <jericho.crosby227@gmail.com>\n" + "Notice: You can use this document subject to the following conditions:\n" + "https://github.com/Chalwk77/Halo-Scripts-Phasor-V2-/blob/master/LICENSE\n" + "~ Created by Jericho Crosby (Chalwk)\n" + "--=====================================================================================================--\n" + "]]\n\n" + "api_version = '1.12.0.0'\n\n" + "function OnScriptLoad()\n\tregister_callback(cb['EVENT_NAME'], 'function_name')\nend\n\nfunction OnScriptUnload()\n\nend\n\n" 'api_version': 'prefix': 'api_version' 'body': 'api_version = "1.12.0.0"' 'description': 'This is the Lua API version being used on the server' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">* Required to load script</span>' 'OnScriptLoad': 'prefix': 'OnScriptLoad' 'body': 'OnScriptLoad()\n\tregister_callback(cb["EVENT_NAME"], "function_name")\nend' 'description': "Initialization code goes here" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">* Requires callback</span>' 'OnEcho': 'prefix': 'OnEcho' 'body': 'OnEcho()\n\nend' 'description': "This function is called when true is passed to the Echo argument of either the execute_command() or the execute_command_sequence() functions" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnSnap': 'prefix': 'OnSnap' 'body': 'OnSnap(PlayerIndex, SnapScore)\n\nend' 'description': "This function is called when a player has snapped while aimbot banning has been enabled" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, SnapScore</span>' 'OnCamp': 'prefix': 'OnCamp' 'body': 'OnCamp(PlayerIndex, CampKills)\n\nend' 'description': "This function is called when a camping player kills another player while the anticamp command is enabled" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, CampKills</span>' 'OnWarp': 'prefix': 'OnWarp' 'body': 'OnWarp(PlayerIndex)\n\nend' 'description': 'This function is called when a player has warped more times than specified by the antiwarp command' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnLogin': 'prefix': 'OnLogin' 'body': 'OnLogin(PlayerIndex)\n\nend' 'description': "This function is called when an admin logs in using their username and password" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnScore': 'prefix': 'OnScore' 'body': 'OnScore(PlayerIndex)\n\nend' 'description': "This function is called when a player has scored a point" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnTick': 'prefix': 'OnTick' 'body': 'OnTick()\n\nend' 'description': "This function is called every game tick (1/30 second) - 33.3333333 ms\n\nSimilar to Phasor's OnClientUpdate() function" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnBetray': 'prefix': 'OnBetray' 'body': 'OnBetray(PlayerIndex, VictimIndex)\n\nend' 'description': "This function is called when a player kills a team mate" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, VictimIndex</span>' 'OnSuicide': 'prefix': 'OnSuicide' 'body': 'OnSuicide(PlayerIndex)\n\nend' 'description': "This function is called when a player has committed suicide" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnGameEnd': 'prefix': 'OnGameEnd' 'body': 'OnGameEnd()\n\nend' 'description': "This function is called when a new game has ended" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnNewGame': 'prefix': 'OnNewGame' 'body': 'OnNewGame()\n\nend' 'description': "This function is called when a new game has started" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnMapReset': 'prefix': 'OnMapReset' 'body': 'OnMapReset()\n\nend' 'description': "This function is called when 'sv_map_reset' has been executed" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnAreaExit': 'prefix': 'OnAreaExit' 'body': 'OnAreaExit(PlayerIndex, AreaName)\n\nend' 'description': "This function is called when a player has exited a custom area" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, AreaName</span>' 'OnAreaEnter': 'prefix': 'OnAreaEnter' 'body': 'OnAreaEnter(PlayerIndex, AreaName)\n\nend' 'description': "This function is called when a player has entered a custom area" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, AreaName</span>' 'OnTeamSwitch': 'prefix': 'OnTeamSwitch' 'body': 'OnTeamSwitch(PlayerIndex)\n\nend' 'description': "This function is called when a player has changed teams" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerJoin': 'prefix': 'OnPlayerJoin' 'body': 'OnPlayerJoin(PlayerIndex)\n\nend' 'description': "This function is called when a player has finished joining the server" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerChat': 'prefix': 'OnPlayerChat' 'body': 'OnPlayerChat(PlayerIndex, Message, Type)\n\nend' 'description': 'This function is called when a player has sent a message' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, Message, Type</span>' 'OnWeaponDrop': 'prefix': 'OnWeaponDrop' 'body': 'OnWeaponDrop(PlayerIndex, Slot)\n\nend' 'description': 'This function is called when a player has dropped a weapon' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, Slot</span>' 'OnPlayerKill': 'prefix': 'OnPlayerKill' 'body': 'OnPlayerKill(PlayerIndex, VictimIndex)\n\nend' 'description': "This function is called when a player kills another player" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, VictimIndex</span>' 'OnCheckAlive': 'prefix': 'OnCheckAlive' 'body': 'OnCheckAlive(PlayerIndex)\n\nend' 'description': "Returns true if the player is alive" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerDeath': 'prefix': 'OnPlayerDeath' 'body': 'OnPlayerDeath(PlayerIndex, KillerIndex)\n\nend' 'description': "This function is called any time a death occurs" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, KillerIndex</span>' 'OnPlayerSpawn': 'prefix': 'OnPlayerSpawn' 'body': 'OnPlayerSpawn(PlayerIndex)\n\nend' 'description': "This function is called when a player has finished spawning" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerLeave': 'prefix': 'OnPlayerLeave' 'body': 'OnPlayerLeave(PlayerIndex)\n\nend' 'description': "This function is called when a player has disconnected from the server" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnObjectSpawn': 'prefix': 'OnObjectSpawn' 'body': 'OnObjectSpawn(PlayerIndex, MapID, ParentID, ObjectID)\n\nend' 'description': "This function is called when the server is attempting to spawn an object" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, MapID, ParentID, ObjectID</span>' 'OnVehicleExit': 'prefix': 'OnVehicleExit' 'body': 'OnVehicleExit(PlayerIndex)\n\nend' 'description': "This function is called when a player has exited a vehicle (called immediately after pressing action key and before exit animation has ended)" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnWeaponPickup': 'prefix': 'OnWeaponPickup' 'body': 'OnWeaponPickup(PlayerIndex, WeaponIndex, Type)\n\nend' 'description': 'This function is called when a player has picked up a weapon or grenade' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, WeaponIndex, Type</span>' 'OnVehicleEntry': 'prefix': 'OnVehicleEntry' 'body': 'OnVehicleEntry(PlayerIndex, Seat)\n\nend' 'description': 'This function is called when a player has entered a vehicle' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, Seat</span>' 'OnServerCommand': 'prefix': 'OnServerCommand' 'body': 'OnServerCommand(PlayerIndex, Command, Environment)\n\nend' 'description': 'This function is called when a player attempts to use a command' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, Command, Environment</span>' 'OnPlayerPrejoin': 'prefix': 'OnPlayerPrejoin' 'body': 'OnPlayerPrejoin(PlayerIndex)\n\nend' 'description': 'This function is called when a player is attempting to join the server but the connection has not been completely established yet' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerPrespawn': 'prefix': 'OnPlayerPrespawn' 'body': 'OnPlayerPrespawn(PlayerIndex)\n\nend' 'description': 'This function is called when a player is spawning (but not alive yet)' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnDamageApplication': 'prefix': 'OnDamageApplication' 'body': 'OnDamageApplication(PlayerIndex, CauserIndex, MetaID, Damage, HitString, Backtap)\n\nend' 'description': "This function is called when damage is applied to a player" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, CauserIndex, MetaID, Damage, HitString, Backtap</span>'
128175
'.source.lua': 'random': 'prefix': 'random' 'body': 'math.random()' 'math.random': 'prefix': 'math.random' 'body': 'math.random()' 'end': 'prefix': 'end' 'body': 'end' 'then': 'prefix': 'then' 'body': 'then' 'write_word': 'prefix': 'write_word' 'body': 'write_word' 'execute_command': 'prefix': 'execute_command' 'body': 'execute_command' 'function': 'prefix': 'function' 'body': 'function' 'functoin': 'prefix': 'functoin' 'body': 'function' 'true': 'prefix': 'true' 'body': 'true' 'mapname': 'prefix': 'mapname' 'body': 'mapname = get_var(0, "$map")' 'mapname': 'prefix': 'mapname' 'body': "line 1\n" + "line 2\n" + "line 3" 'script_title': 'prefix': 'script_title' 'body': "--[[\n" + "--=====================================================================================================--\n" + "Script Name: Document_Name, for SAPP (PC & CE)\n" + "Description:\n\n" + "Copyright (c) 2016-2018, <NAME> <<EMAIL>>\n" + "Notice: You can use this document subject to the following conditions:\n" + "https://github.com/Chalwk77/Halo-Scripts-Phasor-V2-/blob/master/LICENSE\n" + "~ Created by <NAME> (Chalwk)\n" + "--=====================================================================================================--\n" + "]]\n\n" + "api_version = '1.12.0.0'\n\n" + "function OnScriptLoad()\n\tregister_callback(cb['EVENT_NAME'], 'function_name')\nend\n\nfunction OnScriptUnload()\n\nend\n\n" 'api_version': 'prefix': 'api_version' 'body': 'api_version = "1.12.0.0"' 'description': 'This is the Lua API version being used on the server' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">* Required to load script</span>' 'OnScriptLoad': 'prefix': 'OnScriptLoad' 'body': 'OnScriptLoad()\n\tregister_callback(cb["EVENT_NAME"], "function_name")\nend' 'description': "Initialization code goes here" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">* Requires callback</span>' 'OnEcho': 'prefix': 'OnEcho' 'body': 'OnEcho()\n\nend' 'description': "This function is called when true is passed to the Echo argument of either the execute_command() or the execute_command_sequence() functions" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnSnap': 'prefix': 'OnSnap' 'body': 'OnSnap(PlayerIndex, SnapScore)\n\nend' 'description': "This function is called when a player has snapped while aimbot banning has been enabled" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, SnapScore</span>' 'OnCamp': 'prefix': 'OnCamp' 'body': 'OnCamp(PlayerIndex, CampKills)\n\nend' 'description': "This function is called when a camping player kills another player while the anticamp command is enabled" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, CampKills</span>' 'OnWarp': 'prefix': 'OnWarp' 'body': 'OnWarp(PlayerIndex)\n\nend' 'description': 'This function is called when a player has warped more times than specified by the antiwarp command' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnLogin': 'prefix': 'OnLogin' 'body': 'OnLogin(PlayerIndex)\n\nend' 'description': "This function is called when an admin logs in using their username and password" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnScore': 'prefix': 'OnScore' 'body': 'OnScore(PlayerIndex)\n\nend' 'description': "This function is called when a player has scored a point" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnTick': 'prefix': 'OnTick' 'body': 'OnTick()\n\nend' 'description': "This function is called every game tick (1/30 second) - 33.3333333 ms\n\nSimilar to Phasor's OnClientUpdate() function" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnBetray': 'prefix': 'OnBetray' 'body': 'OnBetray(PlayerIndex, VictimIndex)\n\nend' 'description': "This function is called when a player kills a team mate" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, VictimIndex</span>' 'OnSuicide': 'prefix': 'OnSuicide' 'body': 'OnSuicide(PlayerIndex)\n\nend' 'description': "This function is called when a player has committed suicide" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnGameEnd': 'prefix': 'OnGameEnd' 'body': 'OnGameEnd()\n\nend' 'description': "This function is called when a new game has ended" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnNewGame': 'prefix': 'OnNewGame' 'body': 'OnNewGame()\n\nend' 'description': "This function is called when a new game has started" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnMapReset': 'prefix': 'OnMapReset' 'body': 'OnMapReset()\n\nend' 'description': "This function is called when 'sv_map_reset' has been executed" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnAreaExit': 'prefix': 'OnAreaExit' 'body': 'OnAreaExit(PlayerIndex, AreaName)\n\nend' 'description': "This function is called when a player has exited a custom area" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, AreaName</span>' 'OnAreaEnter': 'prefix': 'OnAreaEnter' 'body': 'OnAreaEnter(PlayerIndex, AreaName)\n\nend' 'description': "This function is called when a player has entered a custom area" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, AreaName</span>' 'OnTeamSwitch': 'prefix': 'OnTeamSwitch' 'body': 'OnTeamSwitch(PlayerIndex)\n\nend' 'description': "This function is called when a player has changed teams" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerJoin': 'prefix': 'OnPlayerJoin' 'body': 'OnPlayerJoin(PlayerIndex)\n\nend' 'description': "This function is called when a player has finished joining the server" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerChat': 'prefix': 'OnPlayerChat' 'body': 'OnPlayerChat(PlayerIndex, Message, Type)\n\nend' 'description': 'This function is called when a player has sent a message' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, Message, Type</span>' 'OnWeaponDrop': 'prefix': 'OnWeaponDrop' 'body': 'OnWeaponDrop(PlayerIndex, Slot)\n\nend' 'description': 'This function is called when a player has dropped a weapon' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, Slot</span>' 'OnPlayerKill': 'prefix': 'OnPlayerKill' 'body': 'OnPlayerKill(PlayerIndex, VictimIndex)\n\nend' 'description': "This function is called when a player kills another player" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, VictimIndex</span>' 'OnCheckAlive': 'prefix': 'OnCheckAlive' 'body': 'OnCheckAlive(PlayerIndex)\n\nend' 'description': "Returns true if the player is alive" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerDeath': 'prefix': 'OnPlayerDeath' 'body': 'OnPlayerDeath(PlayerIndex, KillerIndex)\n\nend' 'description': "This function is called any time a death occurs" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, KillerIndex</span>' 'OnPlayerSpawn': 'prefix': 'OnPlayerSpawn' 'body': 'OnPlayerSpawn(PlayerIndex)\n\nend' 'description': "This function is called when a player has finished spawning" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerLeave': 'prefix': 'OnPlayerLeave' 'body': 'OnPlayerLeave(PlayerIndex)\n\nend' 'description': "This function is called when a player has disconnected from the server" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnObjectSpawn': 'prefix': 'OnObjectSpawn' 'body': 'OnObjectSpawn(PlayerIndex, MapID, ParentID, ObjectID)\n\nend' 'description': "This function is called when the server is attempting to spawn an object" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, MapID, ParentID, ObjectID</span>' 'OnVehicleExit': 'prefix': 'OnVehicleExit' 'body': 'OnVehicleExit(PlayerIndex)\n\nend' 'description': "This function is called when a player has exited a vehicle (called immediately after pressing action key and before exit animation has ended)" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnWeaponPickup': 'prefix': 'OnWeaponPickup' 'body': 'OnWeaponPickup(PlayerIndex, WeaponIndex, Type)\n\nend' 'description': 'This function is called when a player has picked up a weapon or grenade' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, WeaponIndex, Type</span>' 'OnVehicleEntry': 'prefix': 'OnVehicleEntry' 'body': 'OnVehicleEntry(PlayerIndex, Seat)\n\nend' 'description': 'This function is called when a player has entered a vehicle' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, Seat</span>' 'OnServerCommand': 'prefix': 'OnServerCommand' 'body': 'OnServerCommand(PlayerIndex, Command, Environment)\n\nend' 'description': 'This function is called when a player attempts to use a command' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, Command, Environment</span>' 'OnPlayerPrejoin': 'prefix': 'OnPlayerPrejoin' 'body': 'OnPlayerPrejoin(PlayerIndex)\n\nend' 'description': 'This function is called when a player is attempting to join the server but the connection has not been completely established yet' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerPrespawn': 'prefix': 'OnPlayerPrespawn' 'body': 'OnPlayerPrespawn(PlayerIndex)\n\nend' 'description': 'This function is called when a player is spawning (but not alive yet)' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnDamageApplication': 'prefix': 'OnDamageApplication' 'body': 'OnDamageApplication(PlayerIndex, CauserIndex, MetaID, Damage, HitString, Backtap)\n\nend' 'description': "This function is called when damage is applied to a player" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, CauserIndex, MetaID, Damage, HitString, Backtap</span>'
true
'.source.lua': 'random': 'prefix': 'random' 'body': 'math.random()' 'math.random': 'prefix': 'math.random' 'body': 'math.random()' 'end': 'prefix': 'end' 'body': 'end' 'then': 'prefix': 'then' 'body': 'then' 'write_word': 'prefix': 'write_word' 'body': 'write_word' 'execute_command': 'prefix': 'execute_command' 'body': 'execute_command' 'function': 'prefix': 'function' 'body': 'function' 'functoin': 'prefix': 'functoin' 'body': 'function' 'true': 'prefix': 'true' 'body': 'true' 'mapname': 'prefix': 'mapname' 'body': 'mapname = get_var(0, "$map")' 'mapname': 'prefix': 'mapname' 'body': "line 1\n" + "line 2\n" + "line 3" 'script_title': 'prefix': 'script_title' 'body': "--[[\n" + "--=====================================================================================================--\n" + "Script Name: Document_Name, for SAPP (PC & CE)\n" + "Description:\n\n" + "Copyright (c) 2016-2018, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>\n" + "Notice: You can use this document subject to the following conditions:\n" + "https://github.com/Chalwk77/Halo-Scripts-Phasor-V2-/blob/master/LICENSE\n" + "~ Created by PI:NAME:<NAME>END_PI (Chalwk)\n" + "--=====================================================================================================--\n" + "]]\n\n" + "api_version = '1.12.0.0'\n\n" + "function OnScriptLoad()\n\tregister_callback(cb['EVENT_NAME'], 'function_name')\nend\n\nfunction OnScriptUnload()\n\nend\n\n" 'api_version': 'prefix': 'api_version' 'body': 'api_version = "1.12.0.0"' 'description': 'This is the Lua API version being used on the server' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">* Required to load script</span>' 'OnScriptLoad': 'prefix': 'OnScriptLoad' 'body': 'OnScriptLoad()\n\tregister_callback(cb["EVENT_NAME"], "function_name")\nend' 'description': "Initialization code goes here" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">* Requires callback</span>' 'OnEcho': 'prefix': 'OnEcho' 'body': 'OnEcho()\n\nend' 'description': "This function is called when true is passed to the Echo argument of either the execute_command() or the execute_command_sequence() functions" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnSnap': 'prefix': 'OnSnap' 'body': 'OnSnap(PlayerIndex, SnapScore)\n\nend' 'description': "This function is called when a player has snapped while aimbot banning has been enabled" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, SnapScore</span>' 'OnCamp': 'prefix': 'OnCamp' 'body': 'OnCamp(PlayerIndex, CampKills)\n\nend' 'description': "This function is called when a camping player kills another player while the anticamp command is enabled" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, CampKills</span>' 'OnWarp': 'prefix': 'OnWarp' 'body': 'OnWarp(PlayerIndex)\n\nend' 'description': 'This function is called when a player has warped more times than specified by the antiwarp command' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnLogin': 'prefix': 'OnLogin' 'body': 'OnLogin(PlayerIndex)\n\nend' 'description': "This function is called when an admin logs in using their username and password" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnScore': 'prefix': 'OnScore' 'body': 'OnScore(PlayerIndex)\n\nend' 'description': "This function is called when a player has scored a point" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnTick': 'prefix': 'OnTick' 'body': 'OnTick()\n\nend' 'description': "This function is called every game tick (1/30 second) - 33.3333333 ms\n\nSimilar to Phasor's OnClientUpdate() function" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnBetray': 'prefix': 'OnBetray' 'body': 'OnBetray(PlayerIndex, VictimIndex)\n\nend' 'description': "This function is called when a player kills a team mate" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, VictimIndex</span>' 'OnSuicide': 'prefix': 'OnSuicide' 'body': 'OnSuicide(PlayerIndex)\n\nend' 'description': "This function is called when a player has committed suicide" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnGameEnd': 'prefix': 'OnGameEnd' 'body': 'OnGameEnd()\n\nend' 'description': "This function is called when a new game has ended" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnNewGame': 'prefix': 'OnNewGame' 'body': 'OnNewGame()\n\nend' 'description': "This function is called when a new game has started" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnMapReset': 'prefix': 'OnMapReset' 'body': 'OnMapReset()\n\nend' 'description': "This function is called when 'sv_map_reset' has been executed" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">none</span>' 'OnAreaExit': 'prefix': 'OnAreaExit' 'body': 'OnAreaExit(PlayerIndex, AreaName)\n\nend' 'description': "This function is called when a player has exited a custom area" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, AreaName</span>' 'OnAreaEnter': 'prefix': 'OnAreaEnter' 'body': 'OnAreaEnter(PlayerIndex, AreaName)\n\nend' 'description': "This function is called when a player has entered a custom area" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, AreaName</span>' 'OnTeamSwitch': 'prefix': 'OnTeamSwitch' 'body': 'OnTeamSwitch(PlayerIndex)\n\nend' 'description': "This function is called when a player has changed teams" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerJoin': 'prefix': 'OnPlayerJoin' 'body': 'OnPlayerJoin(PlayerIndex)\n\nend' 'description': "This function is called when a player has finished joining the server" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerChat': 'prefix': 'OnPlayerChat' 'body': 'OnPlayerChat(PlayerIndex, Message, Type)\n\nend' 'description': 'This function is called when a player has sent a message' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, Message, Type</span>' 'OnWeaponDrop': 'prefix': 'OnWeaponDrop' 'body': 'OnWeaponDrop(PlayerIndex, Slot)\n\nend' 'description': 'This function is called when a player has dropped a weapon' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, Slot</span>' 'OnPlayerKill': 'prefix': 'OnPlayerKill' 'body': 'OnPlayerKill(PlayerIndex, VictimIndex)\n\nend' 'description': "This function is called when a player kills another player" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, VictimIndex</span>' 'OnCheckAlive': 'prefix': 'OnCheckAlive' 'body': 'OnCheckAlive(PlayerIndex)\n\nend' 'description': "Returns true if the player is alive" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerDeath': 'prefix': 'OnPlayerDeath' 'body': 'OnPlayerDeath(PlayerIndex, KillerIndex)\n\nend' 'description': "This function is called any time a death occurs" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, KillerIndex</span>' 'OnPlayerSpawn': 'prefix': 'OnPlayerSpawn' 'body': 'OnPlayerSpawn(PlayerIndex)\n\nend' 'description': "This function is called when a player has finished spawning" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerLeave': 'prefix': 'OnPlayerLeave' 'body': 'OnPlayerLeave(PlayerIndex)\n\nend' 'description': "This function is called when a player has disconnected from the server" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnObjectSpawn': 'prefix': 'OnObjectSpawn' 'body': 'OnObjectSpawn(PlayerIndex, MapID, ParentID, ObjectID)\n\nend' 'description': "This function is called when the server is attempting to spawn an object" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, MapID, ParentID, ObjectID</span>' 'OnVehicleExit': 'prefix': 'OnVehicleExit' 'body': 'OnVehicleExit(PlayerIndex)\n\nend' 'description': "This function is called when a player has exited a vehicle (called immediately after pressing action key and before exit animation has ended)" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnWeaponPickup': 'prefix': 'OnWeaponPickup' 'body': 'OnWeaponPickup(PlayerIndex, WeaponIndex, Type)\n\nend' 'description': 'This function is called when a player has picked up a weapon or grenade' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, WeaponIndex, Type</span>' 'OnVehicleEntry': 'prefix': 'OnVehicleEntry' 'body': 'OnVehicleEntry(PlayerIndex, Seat)\n\nend' 'description': 'This function is called when a player has entered a vehicle' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, Seat</span>' 'OnServerCommand': 'prefix': 'OnServerCommand' 'body': 'OnServerCommand(PlayerIndex, Command, Environment)\n\nend' 'description': 'This function is called when a player attempts to use a command' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, Command, Environment</span>' 'OnPlayerPrejoin': 'prefix': 'OnPlayerPrejoin' 'body': 'OnPlayerPrejoin(PlayerIndex)\n\nend' 'description': 'This function is called when a player is attempting to join the server but the connection has not been completely established yet' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnPlayerPrespawn': 'prefix': 'OnPlayerPrespawn' 'body': 'OnPlayerPrespawn(PlayerIndex)\n\nend' 'description': 'This function is called when a player is spawning (but not alive yet)' 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex</span>' 'OnDamageApplication': 'prefix': 'OnDamageApplication' 'body': 'OnDamageApplication(PlayerIndex, CauserIndex, MetaID, Damage, HitString, Backtap)\n\nend' 'description': "This function is called when damage is applied to a player" 'rightLabelHTML': '<span style="color:red">Parameters: </span><span style="color:green">PlayerIndex, CauserIndex, MetaID, Damage, HitString, Backtap</span>'
[ { "context": "# @Author 程巍巍\n# @Mail littocats@gmail.com\n# @Create 2019-04-1", "end": 13, "score": 0.9998539686203003, "start": 10, "tag": "NAME", "value": "程巍巍" }, { "context": "# @Author 程巍巍\n# @Mail littocats@gmail.com\n# @Create 2019-04-14 13:48:12\n# \n# Copyright 2019", ...
source/options.coffee
LittoCats/svg-font
0
# @Author 程巍巍 # @Mail littocats@gmail.com # @Create 2019-04-14 13:48:12 # # Copyright 2019-04-14 程巍巍 # # 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. # fs = require 'fs-extra' path = require 'path' program = require 'commander' program .version '1.0.0' .usage '[svgdir]' .option '-o, --output <string>', 'output file' .option '-f, --filter [string]', 'RegExp, only process matched svg file' .option '-p, --preview [string]', 'Generate preview page, html.' .parse process.argv cwd = do process.cwd # 检参数 output = program.output filter = program.filter or /(.+)\.svg$/i preview = program.preview svgdir = program.args[0] output = path.resolve cwd, output if output svgdir = path.resolve cwd, svgdir if svgdir preview = path.resolve cwd, preview if preview throw new Error "--output option is required." if not output throw new Error "svgdir is required" if not svgdir throw new Error "svgdir is not found." if not fs.existsSync svgdir stat = fs.statSync svgdir throw new Error "svgdir is not a dir: #{svgdir}" if not stat.isDirectory() filter = new RegExp filter exports.output = output exports.svgdir = svgdir exports.regexp = filter exports.preview = preview exports.filter = (file)-> filter.test path.basename file
182277
# @Author <NAME> # @Mail <EMAIL> # @Create 2019-04-14 13:48:12 # # Copyright 2019-04-14 <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. # fs = require 'fs-extra' path = require 'path' program = require 'commander' program .version '1.0.0' .usage '[svgdir]' .option '-o, --output <string>', 'output file' .option '-f, --filter [string]', 'RegExp, only process matched svg file' .option '-p, --preview [string]', 'Generate preview page, html.' .parse process.argv cwd = do process.cwd # 检参数 output = program.output filter = program.filter or /(.+)\.svg$/i preview = program.preview svgdir = program.args[0] output = path.resolve cwd, output if output svgdir = path.resolve cwd, svgdir if svgdir preview = path.resolve cwd, preview if preview throw new Error "--output option is required." if not output throw new Error "svgdir is required" if not svgdir throw new Error "svgdir is not found." if not fs.existsSync svgdir stat = fs.statSync svgdir throw new Error "svgdir is not a dir: #{svgdir}" if not stat.isDirectory() filter = new RegExp filter exports.output = output exports.svgdir = svgdir exports.regexp = filter exports.preview = preview exports.filter = (file)-> filter.test path.basename file
true
# @Author PI:NAME:<NAME>END_PI # @Mail PI:EMAIL:<EMAIL>END_PI # @Create 2019-04-14 13:48:12 # # Copyright 2019-04-14 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. # fs = require 'fs-extra' path = require 'path' program = require 'commander' program .version '1.0.0' .usage '[svgdir]' .option '-o, --output <string>', 'output file' .option '-f, --filter [string]', 'RegExp, only process matched svg file' .option '-p, --preview [string]', 'Generate preview page, html.' .parse process.argv cwd = do process.cwd # 检参数 output = program.output filter = program.filter or /(.+)\.svg$/i preview = program.preview svgdir = program.args[0] output = path.resolve cwd, output if output svgdir = path.resolve cwd, svgdir if svgdir preview = path.resolve cwd, preview if preview throw new Error "--output option is required." if not output throw new Error "svgdir is required" if not svgdir throw new Error "svgdir is not found." if not fs.existsSync svgdir stat = fs.statSync svgdir throw new Error "svgdir is not a dir: #{svgdir}" if not stat.isDirectory() filter = new RegExp filter exports.output = output exports.svgdir = svgdir exports.regexp = filter exports.preview = preview exports.filter = (file)-> filter.test path.basename file
[ { "context": "__author-name').first().html().should.containEql \"Sophie-Alexia\"\n @view.$('.fair-feed__entry__names__usern", "end": 1308, "score": 0.9998767375946045, "start": 1295, "tag": "NAME", "value": "Sophie-Alexia" }, { "context": "mes__username').first().html().should...
src/mobile/apps/fair/test/client/feed.coffee
kanaabe/force
1
_ = require 'underscore' Backbone = require 'backbone' Fair = require '../../../../models/fair' FairEntries = require '../../../../collections/fair_entries' { fabricate } = require 'antigravity' sinon = require 'sinon' benv = require 'benv' fabricatedFeed = require './fabricate_feed.json' { resolve } = require 'path' cheerio = require 'cheerio' describe 'Fair feed page client-side code', -> beforeEach (done) -> benv.setup => benv.expose { $: benv.require 'jquery' } Backbone.$ = $ sinon.stub Backbone, 'sync' benv.render resolve(__dirname, '../../templates/feed.jade'), { fair: new Fair(fabricate 'fair') sd: {} }, => { FeedView } = benv.requireWithJadeify resolve(__dirname, '../../client/feed'), ['fairEntriesTemplate'] @view = new FeedView fair: new Fair(fabricate 'fair') el: $ 'body' collection: new FairEntries fabricatedFeed done() afterEach -> benv.teardown() Backbone.sync.restore() describe 'FeedView', -> describe '#render', -> it 'renders entries properly', -> @view.render() @view.$('.fair-feed__entry').length.should.equal 1 @view.$('.fair-feed__entry__names__author-name').first().html().should.containEql "Sophie-Alexia" @view.$('.fair-feed__entry__names__username').first().html().should.containEql "sophie_alexia"
87717
_ = require 'underscore' Backbone = require 'backbone' Fair = require '../../../../models/fair' FairEntries = require '../../../../collections/fair_entries' { fabricate } = require 'antigravity' sinon = require 'sinon' benv = require 'benv' fabricatedFeed = require './fabricate_feed.json' { resolve } = require 'path' cheerio = require 'cheerio' describe 'Fair feed page client-side code', -> beforeEach (done) -> benv.setup => benv.expose { $: benv.require 'jquery' } Backbone.$ = $ sinon.stub Backbone, 'sync' benv.render resolve(__dirname, '../../templates/feed.jade'), { fair: new Fair(fabricate 'fair') sd: {} }, => { FeedView } = benv.requireWithJadeify resolve(__dirname, '../../client/feed'), ['fairEntriesTemplate'] @view = new FeedView fair: new Fair(fabricate 'fair') el: $ 'body' collection: new FairEntries fabricatedFeed done() afterEach -> benv.teardown() Backbone.sync.restore() describe 'FeedView', -> describe '#render', -> it 'renders entries properly', -> @view.render() @view.$('.fair-feed__entry').length.should.equal 1 @view.$('.fair-feed__entry__names__author-name').first().html().should.containEql "<NAME>" @view.$('.fair-feed__entry__names__username').first().html().should.containEql "sophie_alexia"
true
_ = require 'underscore' Backbone = require 'backbone' Fair = require '../../../../models/fair' FairEntries = require '../../../../collections/fair_entries' { fabricate } = require 'antigravity' sinon = require 'sinon' benv = require 'benv' fabricatedFeed = require './fabricate_feed.json' { resolve } = require 'path' cheerio = require 'cheerio' describe 'Fair feed page client-side code', -> beforeEach (done) -> benv.setup => benv.expose { $: benv.require 'jquery' } Backbone.$ = $ sinon.stub Backbone, 'sync' benv.render resolve(__dirname, '../../templates/feed.jade'), { fair: new Fair(fabricate 'fair') sd: {} }, => { FeedView } = benv.requireWithJadeify resolve(__dirname, '../../client/feed'), ['fairEntriesTemplate'] @view = new FeedView fair: new Fair(fabricate 'fair') el: $ 'body' collection: new FairEntries fabricatedFeed done() afterEach -> benv.teardown() Backbone.sync.restore() describe 'FeedView', -> describe '#render', -> it 'renders entries properly', -> @view.render() @view.$('.fair-feed__entry').length.should.equal 1 @view.$('.fair-feed__entry__names__author-name').first().html().should.containEql "PI:NAME:<NAME>END_PI" @view.$('.fair-feed__entry__names__username').first().html().should.containEql "sophie_alexia"
[ { "context": "e text !!!\n\n $scope.q.stop = true\n\n\n key = '18a3cf93a5b4e89f173afbb2f2932f93'\n frm = 'json'\n\n prm = $scope.q.query\n\n ", "end": 583, "score": 0.9997442364692688, "start": 551, "tag": "KEY", "value": "18a3cf93a5b4e89f173afbb2f2932f93" } ]
app/js/controllers/search_controller.coffee
sergey-kudriavtsev/ng-lineman-musicfan
1
# Controller of search music artist angular.module('app').controller 'SearchController', ($scope, $http, $rootScope, LocalStoreService) -> # Query completion flag $scope.q = {stop:false} # Query data items $scope.q.data = []; # Query parametrs $scope.q.query = {lm:10,startPage:1,total:0} #serch function $scope.search = -> $scope.q.data = []; #check length of text if $scope.q.artist.length < 3 or $scope.q.stop return #TODO: Create a content check in the text !!! $scope.q.stop = true key = '18a3cf93a5b4e89f173afbb2f2932f93' frm = 'json' prm = $scope.q.query url = 'https://ws.audioscrobbler.com/2.0/?method=artist.search&' + 'artist=' + $scope.q.artist + '&api_key=' + key + '&format=' + frm + '&limit=' + prm.lm.toString() + '&page=' + prm.startPage.toString() + "&callback=JSON_CALLBACK" #console.log url promise = $http.jsonp(url) promise.success (data) -> $scope.q.stop = false if data.results == undefined return $scope.q.data = data.results.artistmatches.artist $scope.q.query = data.results["opensearch:Query"] $scope.q.query.lm = prm.lm $scope.q.query.total = data.results["opensearch:totalResults"] console.log $scope.q return return $scope.nexPage = -> $scope.q.query.startPage += 1 $scope.search return $scope.addFavorites = LocalStoreService.setDate return
11736
# Controller of search music artist angular.module('app').controller 'SearchController', ($scope, $http, $rootScope, LocalStoreService) -> # Query completion flag $scope.q = {stop:false} # Query data items $scope.q.data = []; # Query parametrs $scope.q.query = {lm:10,startPage:1,total:0} #serch function $scope.search = -> $scope.q.data = []; #check length of text if $scope.q.artist.length < 3 or $scope.q.stop return #TODO: Create a content check in the text !!! $scope.q.stop = true key = '<KEY>' frm = 'json' prm = $scope.q.query url = 'https://ws.audioscrobbler.com/2.0/?method=artist.search&' + 'artist=' + $scope.q.artist + '&api_key=' + key + '&format=' + frm + '&limit=' + prm.lm.toString() + '&page=' + prm.startPage.toString() + "&callback=JSON_CALLBACK" #console.log url promise = $http.jsonp(url) promise.success (data) -> $scope.q.stop = false if data.results == undefined return $scope.q.data = data.results.artistmatches.artist $scope.q.query = data.results["opensearch:Query"] $scope.q.query.lm = prm.lm $scope.q.query.total = data.results["opensearch:totalResults"] console.log $scope.q return return $scope.nexPage = -> $scope.q.query.startPage += 1 $scope.search return $scope.addFavorites = LocalStoreService.setDate return
true
# Controller of search music artist angular.module('app').controller 'SearchController', ($scope, $http, $rootScope, LocalStoreService) -> # Query completion flag $scope.q = {stop:false} # Query data items $scope.q.data = []; # Query parametrs $scope.q.query = {lm:10,startPage:1,total:0} #serch function $scope.search = -> $scope.q.data = []; #check length of text if $scope.q.artist.length < 3 or $scope.q.stop return #TODO: Create a content check in the text !!! $scope.q.stop = true key = 'PI:KEY:<KEY>END_PI' frm = 'json' prm = $scope.q.query url = 'https://ws.audioscrobbler.com/2.0/?method=artist.search&' + 'artist=' + $scope.q.artist + '&api_key=' + key + '&format=' + frm + '&limit=' + prm.lm.toString() + '&page=' + prm.startPage.toString() + "&callback=JSON_CALLBACK" #console.log url promise = $http.jsonp(url) promise.success (data) -> $scope.q.stop = false if data.results == undefined return $scope.q.data = data.results.artistmatches.artist $scope.q.query = data.results["opensearch:Query"] $scope.q.query.lm = prm.lm $scope.q.query.total = data.results["opensearch:totalResults"] console.log $scope.q return return $scope.nexPage = -> $scope.q.query.startPage += 1 $scope.search return $scope.addFavorites = LocalStoreService.setDate return
[ { "context": "ate({\n _id: taskId\n },{\n $set: {name: new_name, duration: new_duration, estimate: new_estim", "end": 1956, "score": 0.7141352295875549, "start": 1953, "tag": "NAME", "value": "new" } ]
collections/tasks.coffee
ryleehansen/h
0
@Tasks = new Meteor.Collection 'tasks' Tasks.allow( update: ownsDocument remove: ownsDocument ) Meteor.methods( makeTask: (taskAttributes)-> user = Meteor.user() # user must be logged in if not user throw new Meteor.Error(401, "You need to log in to create tasks") # task must have a name if not taskAttributes.name throw new Meteor.Error(422, "Please fill in task name") # this should not be possible if not taskAttributes.dueDate throw new Meteor.Error(422, "How did you even do that?") # set default task estimate time if not taskAttributes.estimate taskAttributes.estimate = '1 hour' # convert estimate to seconds taskAttributes.duration = parseDuration(taskAttributes.estimate) task = _.extend(_.pick(taskAttributes, 'name', 'dueDate', 'estimate', 'duration'), userId: user._id completed: false planDates: [] ) task.dueDate += 43200 # put it in the middle of the day because fuck DST taskId = Tasks.insert(task) taskId completeTask: (taskId)-> user = Meteor.user() if not user throw new Meteor.Error(401, "You need to login to complete a task") Tasks.update({ _id: taskId },{ $set: {completed: true} }) uncompleteTask: (taskId)-> user = Meteor.user() if not user throw new Meteor.Error(401, "You need to login to uncomplete a task") Tasks.update({ _id: taskId },{ $set: {completed: false} }) update: (taskId, new_name, new_estimate)-> user = Meteor.user() if not user throw new Meteor.Error(401, "You need to login to uncomplete a task") if new_name is '' throw new Meteor.Error(422, "Please fill in task name") if new_estimate is '' new_estimate = '1 hour' new_duration = 3600 else new_duration = parseDuration(new_estimate) Tasks.update({ _id: taskId },{ $set: {name: new_name, duration: new_duration, estimate: new_estimate} }) deleteMe: (taskId)-> user = Meteor.user() if not user throw new Meteor.Error(401, "You need to login to uncomplete a task") Tasks.remove({_id: taskId}) Plans.remove({taskId: taskId}) ) # From http://sj26.com/2011/04/20/parse-natural-duration-javascript # TODO: Write a better one parseDuration = (duration) -> # .75 if match = /^\.\d+$/.exec(duration) parseFloat("0" + match[0]) * 3600 # 4 or 11.75 else if match = /^\d+(?:\.\d+)?$/.exec(duration) parseFloat(match[0]) * 3600 # 01:34 else if match = /^(\d+):(\d+)$/.exec(duration) (parseInt(match[1]) or 0) * 3600 + (parseInt(match[2]) or 0) * 60 # 1h30m or 7 hrs 1 min and 43 seconds else if match = /(?:(\d+)\s*d(?:ay?)?s?)?(?:(?:\s+and|,)?\s+)?(?:(\d+)\s*h(?:(?:ou)?rs?)?)?(?:(?:\s+and|,)?\s+)?(?:(\d+)\s*m(?:in(?:utes?))?)?(?:(?:\s+and|,)?\s+)?(?:(\d)\s*s(?:ec(?:ond)?s?)?)?/.exec(duration) (parseInt(match[1]) or 0) * 86400 + (parseInt(match[2]) or 0) * 3600 + (parseInt(match[3]) or 0) * 60 + (parseInt(match[4]) or 0) # Unknown! else 3600
43424
@Tasks = new Meteor.Collection 'tasks' Tasks.allow( update: ownsDocument remove: ownsDocument ) Meteor.methods( makeTask: (taskAttributes)-> user = Meteor.user() # user must be logged in if not user throw new Meteor.Error(401, "You need to log in to create tasks") # task must have a name if not taskAttributes.name throw new Meteor.Error(422, "Please fill in task name") # this should not be possible if not taskAttributes.dueDate throw new Meteor.Error(422, "How did you even do that?") # set default task estimate time if not taskAttributes.estimate taskAttributes.estimate = '1 hour' # convert estimate to seconds taskAttributes.duration = parseDuration(taskAttributes.estimate) task = _.extend(_.pick(taskAttributes, 'name', 'dueDate', 'estimate', 'duration'), userId: user._id completed: false planDates: [] ) task.dueDate += 43200 # put it in the middle of the day because fuck DST taskId = Tasks.insert(task) taskId completeTask: (taskId)-> user = Meteor.user() if not user throw new Meteor.Error(401, "You need to login to complete a task") Tasks.update({ _id: taskId },{ $set: {completed: true} }) uncompleteTask: (taskId)-> user = Meteor.user() if not user throw new Meteor.Error(401, "You need to login to uncomplete a task") Tasks.update({ _id: taskId },{ $set: {completed: false} }) update: (taskId, new_name, new_estimate)-> user = Meteor.user() if not user throw new Meteor.Error(401, "You need to login to uncomplete a task") if new_name is '' throw new Meteor.Error(422, "Please fill in task name") if new_estimate is '' new_estimate = '1 hour' new_duration = 3600 else new_duration = parseDuration(new_estimate) Tasks.update({ _id: taskId },{ $set: {name: <NAME>_name, duration: new_duration, estimate: new_estimate} }) deleteMe: (taskId)-> user = Meteor.user() if not user throw new Meteor.Error(401, "You need to login to uncomplete a task") Tasks.remove({_id: taskId}) Plans.remove({taskId: taskId}) ) # From http://sj26.com/2011/04/20/parse-natural-duration-javascript # TODO: Write a better one parseDuration = (duration) -> # .75 if match = /^\.\d+$/.exec(duration) parseFloat("0" + match[0]) * 3600 # 4 or 11.75 else if match = /^\d+(?:\.\d+)?$/.exec(duration) parseFloat(match[0]) * 3600 # 01:34 else if match = /^(\d+):(\d+)$/.exec(duration) (parseInt(match[1]) or 0) * 3600 + (parseInt(match[2]) or 0) * 60 # 1h30m or 7 hrs 1 min and 43 seconds else if match = /(?:(\d+)\s*d(?:ay?)?s?)?(?:(?:\s+and|,)?\s+)?(?:(\d+)\s*h(?:(?:ou)?rs?)?)?(?:(?:\s+and|,)?\s+)?(?:(\d+)\s*m(?:in(?:utes?))?)?(?:(?:\s+and|,)?\s+)?(?:(\d)\s*s(?:ec(?:ond)?s?)?)?/.exec(duration) (parseInt(match[1]) or 0) * 86400 + (parseInt(match[2]) or 0) * 3600 + (parseInt(match[3]) or 0) * 60 + (parseInt(match[4]) or 0) # Unknown! else 3600
true
@Tasks = new Meteor.Collection 'tasks' Tasks.allow( update: ownsDocument remove: ownsDocument ) Meteor.methods( makeTask: (taskAttributes)-> user = Meteor.user() # user must be logged in if not user throw new Meteor.Error(401, "You need to log in to create tasks") # task must have a name if not taskAttributes.name throw new Meteor.Error(422, "Please fill in task name") # this should not be possible if not taskAttributes.dueDate throw new Meteor.Error(422, "How did you even do that?") # set default task estimate time if not taskAttributes.estimate taskAttributes.estimate = '1 hour' # convert estimate to seconds taskAttributes.duration = parseDuration(taskAttributes.estimate) task = _.extend(_.pick(taskAttributes, 'name', 'dueDate', 'estimate', 'duration'), userId: user._id completed: false planDates: [] ) task.dueDate += 43200 # put it in the middle of the day because fuck DST taskId = Tasks.insert(task) taskId completeTask: (taskId)-> user = Meteor.user() if not user throw new Meteor.Error(401, "You need to login to complete a task") Tasks.update({ _id: taskId },{ $set: {completed: true} }) uncompleteTask: (taskId)-> user = Meteor.user() if not user throw new Meteor.Error(401, "You need to login to uncomplete a task") Tasks.update({ _id: taskId },{ $set: {completed: false} }) update: (taskId, new_name, new_estimate)-> user = Meteor.user() if not user throw new Meteor.Error(401, "You need to login to uncomplete a task") if new_name is '' throw new Meteor.Error(422, "Please fill in task name") if new_estimate is '' new_estimate = '1 hour' new_duration = 3600 else new_duration = parseDuration(new_estimate) Tasks.update({ _id: taskId },{ $set: {name: PI:NAME:<NAME>END_PI_name, duration: new_duration, estimate: new_estimate} }) deleteMe: (taskId)-> user = Meteor.user() if not user throw new Meteor.Error(401, "You need to login to uncomplete a task") Tasks.remove({_id: taskId}) Plans.remove({taskId: taskId}) ) # From http://sj26.com/2011/04/20/parse-natural-duration-javascript # TODO: Write a better one parseDuration = (duration) -> # .75 if match = /^\.\d+$/.exec(duration) parseFloat("0" + match[0]) * 3600 # 4 or 11.75 else if match = /^\d+(?:\.\d+)?$/.exec(duration) parseFloat(match[0]) * 3600 # 01:34 else if match = /^(\d+):(\d+)$/.exec(duration) (parseInt(match[1]) or 0) * 3600 + (parseInt(match[2]) or 0) * 60 # 1h30m or 7 hrs 1 min and 43 seconds else if match = /(?:(\d+)\s*d(?:ay?)?s?)?(?:(?:\s+and|,)?\s+)?(?:(\d+)\s*h(?:(?:ou)?rs?)?)?(?:(?:\s+and|,)?\s+)?(?:(\d+)\s*m(?:in(?:utes?))?)?(?:(?:\s+and|,)?\s+)?(?:(\d)\s*s(?:ec(?:ond)?s?)?)?/.exec(duration) (parseInt(match[1]) or 0) * 86400 + (parseInt(match[2]) or 0) * 3600 + (parseInt(match[3]) or 0) * 60 + (parseInt(match[4]) or 0) # Unknown! else 3600
[ { "context": "nding_transactions$: KefirCollection([], id_key: 'hash')\n contract_logs$: KefirCollection([], id_key:", "end": 548, "score": 0.8795565366744995, "start": 544, "tag": "KEY", "value": "hash" }, { "context": "\n contract_logs$: KefirCollection([], id_key: 'id_hash')...
static/js/chat.coffee
eth-services/eth-chatter
0
React = require 'react' ReactDOM = require 'react-dom' moment = require 'moment' {Txid, ContractMixin, LogItem} = require './common' KefirCollection = require 'kefir-collection' KefirBus = require 'kefir-bus' fetch$ = require 'kefir-fetch' somata = require 'somata-socketio-client' eve = require 'eve-js' threaded_chat_abi = require './threaded-chat-abi' chat_api = eve.buildAPIWithABI threaded_chat_abi Dispatcher = getRoomLogs: (slug) -> fetch$ 'get', "/c/#{slug}.json" pending_transactions$: KefirCollection([], id_key: 'hash') contract_logs$: KefirCollection([], id_key: 'id_hash') new_username$: KefirBus() Room = React.createClass mixins: [ContractMixin] getInitialState: -> logs: [] loading: true transactions: [] block_number: null message: '' componentDidMount: -> @logs$ = Dispatcher.getRoomLogs(window.chat_slug) @logs$.onValue @foundLogs @transactions$ = Dispatcher.pending_transactions$ @transactions$.onValue @setTransactions @logs$ = Dispatcher.contract_logs$ @logs$.onValue @handleLogs @usernames$ = Dispatcher.new_username$ @usernames$.onValue @handleNewUsername componentWillUnmount: -> @contract$.offValue @foundContract @transactions$.offValue @setTransactions @logs$.offValue @handleNewLog @usernames$.offValue @handleNewUsername setTransactions: (transactions) -> @setState {transactions} foundLogs: (logs) -> console.log logs logs.map (l) -> l.id_hash = l.blockNumber + '-' + l.logIndex @setState loading: false Dispatcher.contract_logs$.setItems logs handleLogs: (logs) -> console.log logs, 'New log' @setState {logs}, => @fixScroll() changeValue: (key, e) -> new_state = {} new_state[key] = e.target.value @setState new_state onKeyPress: (e) -> if e.key == 'Enter' and !e.shiftKey e.preventDefault() @onSubmit(e) onSubmit: (e) -> e.preventDefault() if !@state.message?.trim().length return {message} = @state to = CONTRACT_ADDRESS fn = 'sendChat' room = window.location.pathname.split('/')[2] options = {gas: 30000} chat_api.sendChat to, room, message, options, @handleWeb3Response # eve.execWithABI threaded_chat_abi, to, fn, room, message, options, @handleWeb3Response handleWeb3Response: (err, resp) -> console.log err if err? if resp? @setState message: '' handleNewUsername: ({username, address}) -> logs = @state.logs new_logs = logs.map (l) -> if l.address == address l.username = username return l @setState logs: new_logs render: -> <div className='log-insert'> <div> {@renderActivity()} {if window.web3? <input value=@state.message placeholder='Send a message' onKeyPress=@onKeyPress onChange={@changeValue.bind(null, 'message')} /> else <a className='sender' href='/howto'>Send a message</a> } </div> </div> # <div className='col half'> # <h3>Pending Transactions</h3> # {@state.transactions.map (t, i) -> # <div><Txid txid={t.hash} key=i /></div> # } # </div> renderActivity: -> <div className='logs' id='logs'> {if @state.loading <div className='loading'>loading...</div> else [<div className='log'> eth-chatter.io <a href='http://github.com/eth-services/eth-chatter'>v0.0.1</a> </div> , <div className='log'> furnished by <a href='http://eth-services.io'>eth-services.io</a> </div>] } {@state.logs.map @renderLog} </div> renderLog: (l, i) -> <LogItem l=l key=i /> fixScroll: -> $logs = document.getElementById('logs') $logs?.scrollTop = $logs?.scrollHeight module.exports = Room console.log "rooms:#{window.chat_slug}:events" somata.subscribe 'eth-chatter:events', "rooms:#{window.chat_slug}:events", (data) -> console.log 'test jones ii', data data.id_hash = data.blockNumber + '-' + (data.logIndex + 1) if !data.logIndex? console.log 'Its broken:', data.blockNumber + '-' + (data.logIndex + 1) Dispatcher.contract_logs$.updateItem data.id_hash, data somata.subscribe 'eth-chatter:events', "rooms:#{window.chat_slug}:all_events", (data) -> console.log 'test jones', data data = data.map (d) -> d.id_hash = d.blockNumber + '-' + (d.logIndex + 1) return d Dispatcher.contract_logs$.setItems data somata.subscribe 'ethereum:contracts', "all_blocks", (data) -> text = document.createTextNode("Block ##{data.number}... ") document.getElementById("block_counter").appendChild(text) somata.subscribe 'eth-chatter:events', "all_usernames", (data) -> console.log '[eth-login:events -- all_usernames -- BAD MAN', data # SOmething like this # Dispatcher.all_usernames$.updateItem data.address, data Dispatcher.new_username$.emit data ReactDOM.render(<Room />, document.getElementById('insert'))
179520
React = require 'react' ReactDOM = require 'react-dom' moment = require 'moment' {Txid, ContractMixin, LogItem} = require './common' KefirCollection = require 'kefir-collection' KefirBus = require 'kefir-bus' fetch$ = require 'kefir-fetch' somata = require 'somata-socketio-client' eve = require 'eve-js' threaded_chat_abi = require './threaded-chat-abi' chat_api = eve.buildAPIWithABI threaded_chat_abi Dispatcher = getRoomLogs: (slug) -> fetch$ 'get', "/c/#{slug}.json" pending_transactions$: KefirCollection([], id_key: '<KEY>') contract_logs$: KefirCollection([], id_key: '<KEY>') new_username$: KefirBus() Room = React.createClass mixins: [ContractMixin] getInitialState: -> logs: [] loading: true transactions: [] block_number: null message: '' componentDidMount: -> @logs$ = Dispatcher.getRoomLogs(window.chat_slug) @logs$.onValue @foundLogs @transactions$ = Dispatcher.pending_transactions$ @transactions$.onValue @setTransactions @logs$ = Dispatcher.contract_logs$ @logs$.onValue @handleLogs @usernames$ = Dispatcher.new_username$ @usernames$.onValue @handleNewUsername componentWillUnmount: -> @contract$.offValue @foundContract @transactions$.offValue @setTransactions @logs$.offValue @handleNewLog @usernames$.offValue @handleNewUsername setTransactions: (transactions) -> @setState {transactions} foundLogs: (logs) -> console.log logs logs.map (l) -> l.id_hash = l.blockNumber + '-' + l.logIndex @setState loading: false Dispatcher.contract_logs$.setItems logs handleLogs: (logs) -> console.log logs, 'New log' @setState {logs}, => @fixScroll() changeValue: (key, e) -> new_state = {} new_state[key] = e.target.value @setState new_state onKeyPress: (e) -> if e.key == 'Enter' and !e.shiftKey e.preventDefault() @onSubmit(e) onSubmit: (e) -> e.preventDefault() if !@state.message?.trim().length return {message} = @state to = CONTRACT_ADDRESS fn = 'sendChat' room = window.location.pathname.split('/')[2] options = {gas: 30000} chat_api.sendChat to, room, message, options, @handleWeb3Response # eve.execWithABI threaded_chat_abi, to, fn, room, message, options, @handleWeb3Response handleWeb3Response: (err, resp) -> console.log err if err? if resp? @setState message: '' handleNewUsername: ({username, address}) -> logs = @state.logs new_logs = logs.map (l) -> if l.address == address l.username = username return l @setState logs: new_logs render: -> <div className='log-insert'> <div> {@renderActivity()} {if window.web3? <input value=@state.message placeholder='Send a message' onKeyPress=@onKeyPress onChange={@changeValue.bind(null, 'message')} /> else <a className='sender' href='/howto'>Send a message</a> } </div> </div> # <div className='col half'> # <h3>Pending Transactions</h3> # {@state.transactions.map (t, i) -> # <div><Txid txid={t.hash} key=i /></div> # } # </div> renderActivity: -> <div className='logs' id='logs'> {if @state.loading <div className='loading'>loading...</div> else [<div className='log'> eth-chatter.io <a href='http://github.com/eth-services/eth-chatter'>v0.0.1</a> </div> , <div className='log'> furnished by <a href='http://eth-services.io'>eth-services.io</a> </div>] } {@state.logs.map @renderLog} </div> renderLog: (l, i) -> <LogItem l=l key=i /> fixScroll: -> $logs = document.getElementById('logs') $logs?.scrollTop = $logs?.scrollHeight module.exports = Room console.log "rooms:#{window.chat_slug}:events" somata.subscribe 'eth-chatter:events', "rooms:#{window.chat_slug}:events", (data) -> console.log 'test jones ii', data data.id_hash = data.blockNumber + '-' + (data.logIndex + 1) if !data.logIndex? console.log 'Its broken:', data.blockNumber + '-' + (data.logIndex + 1) Dispatcher.contract_logs$.updateItem data.id_hash, data somata.subscribe 'eth-chatter:events', "rooms:#{window.chat_slug}:all_events", (data) -> console.log 'test jones', data data = data.map (d) -> d.id_hash = d.blockNumber + '-' + (d.logIndex + 1) return d Dispatcher.contract_logs$.setItems data somata.subscribe 'ethereum:contracts', "all_blocks", (data) -> text = document.createTextNode("Block ##{data.number}... ") document.getElementById("block_counter").appendChild(text) somata.subscribe 'eth-chatter:events', "all_usernames", (data) -> console.log '[eth-login:events -- all_usernames -- BAD MAN', data # SOmething like this # Dispatcher.all_usernames$.updateItem data.address, data Dispatcher.new_username$.emit data ReactDOM.render(<Room />, document.getElementById('insert'))
true
React = require 'react' ReactDOM = require 'react-dom' moment = require 'moment' {Txid, ContractMixin, LogItem} = require './common' KefirCollection = require 'kefir-collection' KefirBus = require 'kefir-bus' fetch$ = require 'kefir-fetch' somata = require 'somata-socketio-client' eve = require 'eve-js' threaded_chat_abi = require './threaded-chat-abi' chat_api = eve.buildAPIWithABI threaded_chat_abi Dispatcher = getRoomLogs: (slug) -> fetch$ 'get', "/c/#{slug}.json" pending_transactions$: KefirCollection([], id_key: 'PI:KEY:<KEY>END_PI') contract_logs$: KefirCollection([], id_key: 'PI:KEY:<KEY>END_PI') new_username$: KefirBus() Room = React.createClass mixins: [ContractMixin] getInitialState: -> logs: [] loading: true transactions: [] block_number: null message: '' componentDidMount: -> @logs$ = Dispatcher.getRoomLogs(window.chat_slug) @logs$.onValue @foundLogs @transactions$ = Dispatcher.pending_transactions$ @transactions$.onValue @setTransactions @logs$ = Dispatcher.contract_logs$ @logs$.onValue @handleLogs @usernames$ = Dispatcher.new_username$ @usernames$.onValue @handleNewUsername componentWillUnmount: -> @contract$.offValue @foundContract @transactions$.offValue @setTransactions @logs$.offValue @handleNewLog @usernames$.offValue @handleNewUsername setTransactions: (transactions) -> @setState {transactions} foundLogs: (logs) -> console.log logs logs.map (l) -> l.id_hash = l.blockNumber + '-' + l.logIndex @setState loading: false Dispatcher.contract_logs$.setItems logs handleLogs: (logs) -> console.log logs, 'New log' @setState {logs}, => @fixScroll() changeValue: (key, e) -> new_state = {} new_state[key] = e.target.value @setState new_state onKeyPress: (e) -> if e.key == 'Enter' and !e.shiftKey e.preventDefault() @onSubmit(e) onSubmit: (e) -> e.preventDefault() if !@state.message?.trim().length return {message} = @state to = CONTRACT_ADDRESS fn = 'sendChat' room = window.location.pathname.split('/')[2] options = {gas: 30000} chat_api.sendChat to, room, message, options, @handleWeb3Response # eve.execWithABI threaded_chat_abi, to, fn, room, message, options, @handleWeb3Response handleWeb3Response: (err, resp) -> console.log err if err? if resp? @setState message: '' handleNewUsername: ({username, address}) -> logs = @state.logs new_logs = logs.map (l) -> if l.address == address l.username = username return l @setState logs: new_logs render: -> <div className='log-insert'> <div> {@renderActivity()} {if window.web3? <input value=@state.message placeholder='Send a message' onKeyPress=@onKeyPress onChange={@changeValue.bind(null, 'message')} /> else <a className='sender' href='/howto'>Send a message</a> } </div> </div> # <div className='col half'> # <h3>Pending Transactions</h3> # {@state.transactions.map (t, i) -> # <div><Txid txid={t.hash} key=i /></div> # } # </div> renderActivity: -> <div className='logs' id='logs'> {if @state.loading <div className='loading'>loading...</div> else [<div className='log'> eth-chatter.io <a href='http://github.com/eth-services/eth-chatter'>v0.0.1</a> </div> , <div className='log'> furnished by <a href='http://eth-services.io'>eth-services.io</a> </div>] } {@state.logs.map @renderLog} </div> renderLog: (l, i) -> <LogItem l=l key=i /> fixScroll: -> $logs = document.getElementById('logs') $logs?.scrollTop = $logs?.scrollHeight module.exports = Room console.log "rooms:#{window.chat_slug}:events" somata.subscribe 'eth-chatter:events', "rooms:#{window.chat_slug}:events", (data) -> console.log 'test jones ii', data data.id_hash = data.blockNumber + '-' + (data.logIndex + 1) if !data.logIndex? console.log 'Its broken:', data.blockNumber + '-' + (data.logIndex + 1) Dispatcher.contract_logs$.updateItem data.id_hash, data somata.subscribe 'eth-chatter:events', "rooms:#{window.chat_slug}:all_events", (data) -> console.log 'test jones', data data = data.map (d) -> d.id_hash = d.blockNumber + '-' + (d.logIndex + 1) return d Dispatcher.contract_logs$.setItems data somata.subscribe 'ethereum:contracts', "all_blocks", (data) -> text = document.createTextNode("Block ##{data.number}... ") document.getElementById("block_counter").appendChild(text) somata.subscribe 'eth-chatter:events', "all_usernames", (data) -> console.log '[eth-login:events -- all_usernames -- BAD MAN', data # SOmething like this # Dispatcher.all_usernames$.updateItem data.address, data Dispatcher.new_username$.emit data ReactDOM.render(<Room />, document.getElementById('insert'))
[ { "context": "# Copyright 2012 Joshua Carver \n# \n# Licensed under the Apache License, Versio", "end": 30, "score": 0.9998718500137329, "start": 17, "tag": "NAME", "value": "Joshua Carver" } ]
src/coffeescript/charts/effects.coffee
jcarver989/raphy-charts
5
# Copyright 2012 Joshua Carver # # 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. # @import point.coffee Raphael.fn.triangle = (cx, cy, r) -> r *= 1.75 this.path("M".concat(cx, ",", cy, "m0-", r * .58, "l", r * .5, ",", r * .87, "-", r, ",0z")) # Utility mehtods for visual augmentations like shading, dashed lines etc. class Effects constructor: (@r) -> black_nub: (target, h_padding = 10, v_padding = 8, offset = 0, rounding = 0) -> box = target.getBBox() x = box.x y = box.y box_width = box.width box_height = box.height box_midpoint = (x + box_width/2) width = box_width + (2 * h_padding) height = box_height + (2 * v_padding) popup = @r.set() popup.push @r.rect( box_midpoint - width/2, y - v_padding, width, height, rounding ) popup.push(@r.triangle( x + box_width + h_padding + 2, y + 2 + (0.5 * box_height), 4 ).rotate(90)) popup.attr({ "fill" : "#333" "stroke" : "none" }).toBack() straight_line: (start_point, end_point) -> @r.path("M#{start_point.x},#{start_point.y}L#{end_point.x},#{end_point.y}") vertical_dashed_line: (start_point, end_point, dash_width = 3, spacing = 10) -> height = end_point.y - start_point.y ticks = Math.floor(height / spacing) dashes = @r.set() for i in [0..ticks-1] continue if i % 2 != 0 rect = @r.rect( start_point.x - (0.5 * dash_width), i * spacing + start_point.y, dash_width, spacing ) dashes.push(rect) dashes get_points_along_top_of_bbox: (rect, y_offset = 0) -> bounding_box = rect.getBBox() x1 = bounding_box.x x2 = bounding_box.x + bounding_box.width y1 = bounding_box.y + y_offset y2 = y1 # straight line [new Point(x1, y1), new Point(x2, y2)] # rectangles only one_px_highlight: (rect) -> [start, end] = @get_points_along_top_of_bbox(rect, 2) @straight_line(start, end).attr({ "stroke-width" : 1 "stroke" : "rgba(255,255,255,0.3)" }) @straight_line one_px_shadow: (rect) -> [start, end] = @get_points_along_top_of_bbox(rect) @straight_line(start, end).attr({ "stroke-width" : 0.5 "stroke" : "rgba(0,0,0,0.5)" }) @straight_line exports.Effects = Effects
68333
# Copyright 2012 <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. # @import point.coffee Raphael.fn.triangle = (cx, cy, r) -> r *= 1.75 this.path("M".concat(cx, ",", cy, "m0-", r * .58, "l", r * .5, ",", r * .87, "-", r, ",0z")) # Utility mehtods for visual augmentations like shading, dashed lines etc. class Effects constructor: (@r) -> black_nub: (target, h_padding = 10, v_padding = 8, offset = 0, rounding = 0) -> box = target.getBBox() x = box.x y = box.y box_width = box.width box_height = box.height box_midpoint = (x + box_width/2) width = box_width + (2 * h_padding) height = box_height + (2 * v_padding) popup = @r.set() popup.push @r.rect( box_midpoint - width/2, y - v_padding, width, height, rounding ) popup.push(@r.triangle( x + box_width + h_padding + 2, y + 2 + (0.5 * box_height), 4 ).rotate(90)) popup.attr({ "fill" : "#333" "stroke" : "none" }).toBack() straight_line: (start_point, end_point) -> @r.path("M#{start_point.x},#{start_point.y}L#{end_point.x},#{end_point.y}") vertical_dashed_line: (start_point, end_point, dash_width = 3, spacing = 10) -> height = end_point.y - start_point.y ticks = Math.floor(height / spacing) dashes = @r.set() for i in [0..ticks-1] continue if i % 2 != 0 rect = @r.rect( start_point.x - (0.5 * dash_width), i * spacing + start_point.y, dash_width, spacing ) dashes.push(rect) dashes get_points_along_top_of_bbox: (rect, y_offset = 0) -> bounding_box = rect.getBBox() x1 = bounding_box.x x2 = bounding_box.x + bounding_box.width y1 = bounding_box.y + y_offset y2 = y1 # straight line [new Point(x1, y1), new Point(x2, y2)] # rectangles only one_px_highlight: (rect) -> [start, end] = @get_points_along_top_of_bbox(rect, 2) @straight_line(start, end).attr({ "stroke-width" : 1 "stroke" : "rgba(255,255,255,0.3)" }) @straight_line one_px_shadow: (rect) -> [start, end] = @get_points_along_top_of_bbox(rect) @straight_line(start, end).attr({ "stroke-width" : 0.5 "stroke" : "rgba(0,0,0,0.5)" }) @straight_line exports.Effects = Effects
true
# Copyright 2012 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. # @import point.coffee Raphael.fn.triangle = (cx, cy, r) -> r *= 1.75 this.path("M".concat(cx, ",", cy, "m0-", r * .58, "l", r * .5, ",", r * .87, "-", r, ",0z")) # Utility mehtods for visual augmentations like shading, dashed lines etc. class Effects constructor: (@r) -> black_nub: (target, h_padding = 10, v_padding = 8, offset = 0, rounding = 0) -> box = target.getBBox() x = box.x y = box.y box_width = box.width box_height = box.height box_midpoint = (x + box_width/2) width = box_width + (2 * h_padding) height = box_height + (2 * v_padding) popup = @r.set() popup.push @r.rect( box_midpoint - width/2, y - v_padding, width, height, rounding ) popup.push(@r.triangle( x + box_width + h_padding + 2, y + 2 + (0.5 * box_height), 4 ).rotate(90)) popup.attr({ "fill" : "#333" "stroke" : "none" }).toBack() straight_line: (start_point, end_point) -> @r.path("M#{start_point.x},#{start_point.y}L#{end_point.x},#{end_point.y}") vertical_dashed_line: (start_point, end_point, dash_width = 3, spacing = 10) -> height = end_point.y - start_point.y ticks = Math.floor(height / spacing) dashes = @r.set() for i in [0..ticks-1] continue if i % 2 != 0 rect = @r.rect( start_point.x - (0.5 * dash_width), i * spacing + start_point.y, dash_width, spacing ) dashes.push(rect) dashes get_points_along_top_of_bbox: (rect, y_offset = 0) -> bounding_box = rect.getBBox() x1 = bounding_box.x x2 = bounding_box.x + bounding_box.width y1 = bounding_box.y + y_offset y2 = y1 # straight line [new Point(x1, y1), new Point(x2, y2)] # rectangles only one_px_highlight: (rect) -> [start, end] = @get_points_along_top_of_bbox(rect, 2) @straight_line(start, end).attr({ "stroke-width" : 1 "stroke" : "rgba(255,255,255,0.3)" }) @straight_line one_px_shadow: (rect) -> [start, end] = @get_points_along_top_of_bbox(rect) @straight_line(start, end).attr({ "stroke-width" : 0.5 "stroke" : "rgba(0,0,0,0.5)" }) @straight_line exports.Effects = Effects
[ { "context": "###\n Copyright (c) 2013 Stanley Shyiko\n Licensed under the MIT license.\n https://g", "end": 41, "score": 0.9998122453689575, "start": 27, "tag": "NAME", "value": "Stanley Shyiko" }, { "context": "sed under the MIT license.\n https://github.com/openproxy/o...
src/chrome-extension/scripts/background.coffee
openproxy/openproxy-chrome-extension
1
### Copyright (c) 2013 Stanley Shyiko Licensed under the MIT license. https://github.com/openproxy/openproxy-chrome-extension ### # @settings {host, port, scheme (default - 'http'), whitelist (optional), blacklist (optional)} configureProxy = (settings) -> scheme = settings.scheme or 'http' # or "https", "socks4", "socks5" proxyConfig = "#{if scheme.indexOf('http') is 0 then 'PROXY' else 'SOCKS'} #{settings.host}:#{settings.port}" mode: 'pac_script', pacScript: data: """ function FindProxyForURL(url, host) { var bypassProxy = true; if (!isPlainHostName(host) && !shExpMatch(host, '*.local') && !isInNet(dnsResolve(host), '10.0.0.0', '255.0.0.0') && !isInNet(dnsResolve(host), '172.16.0.0', '255.240.0.0') && !isInNet(dnsResolve(host), '192.168.0.0', '255.255.0.0') && !isInNet(dnsResolve(host), '127.0.0.0', '255.255.255.0')) { var blacklist = #{JSON.stringify(settings.blacklist or [])}, blacklisted = false; for (var j = 0, je = blacklist.length; j < je; j++) { if (shExpMatch(host, blacklist[j])) { blacklisted = true; break; } } if (!blacklisted) { var whitelist = #{JSON.stringify(settings.whitelist or [])}; if (whitelist.length) { for (var i = 0, ie = whitelist.length; i < ie; i++) { if (shExpMatch(host, whitelist[i])) { bypassProxy = false; break; } } } else { bypassProxy = false; } } } return bypassProxy ? 'DIRECT' : '#{proxyConfig}'; } """ # use alert() + chrome://net-internals/#events to debug # @event {type, body} eventHandler = (event) -> switch event.type when 'OP_PROXY_ON' chrome.proxy.settings.set scope: 'regular', value: configureProxy(event.body) when 'OP_PROXY_OFF' chrome.proxy.settings.set scope: 'regular', value: mode: 'direct' else return false return true # registering listener for OP_PROXY_* events chrome.runtime.onConnect.addListener (port) -> port.onMessage.addListener (event) -> if (eventHandler(event)) port.postMessage type: 'OP_COMPLETED', body: event chrome.runtime.onMessage.addListener eventHandler
97825
### Copyright (c) 2013 <NAME> Licensed under the MIT license. https://github.com/openproxy/openproxy-chrome-extension ### # @settings {host, port, scheme (default - 'http'), whitelist (optional), blacklist (optional)} configureProxy = (settings) -> scheme = settings.scheme or 'http' # or "https", "socks4", "socks5" proxyConfig = "#{if scheme.indexOf('http') is 0 then 'PROXY' else 'SOCKS'} #{settings.host}:#{settings.port}" mode: 'pac_script', pacScript: data: """ function FindProxyForURL(url, host) { var bypassProxy = true; if (!isPlainHostName(host) && !shExpMatch(host, '*.local') && !isInNet(dnsResolve(host), '10.0.0.0', '255.0.0.0') && !isInNet(dnsResolve(host), '172.16.0.0', '255.240.0.0') && !isInNet(dnsResolve(host), '192.168.0.0', '255.255.0.0') && !isInNet(dnsResolve(host), '127.0.0.0', '255.255.255.0')) { var blacklist = #{JSON.stringify(settings.blacklist or [])}, blacklisted = false; for (var j = 0, je = blacklist.length; j < je; j++) { if (shExpMatch(host, blacklist[j])) { blacklisted = true; break; } } if (!blacklisted) { var whitelist = #{JSON.stringify(settings.whitelist or [])}; if (whitelist.length) { for (var i = 0, ie = whitelist.length; i < ie; i++) { if (shExpMatch(host, whitelist[i])) { bypassProxy = false; break; } } } else { bypassProxy = false; } } } return bypassProxy ? 'DIRECT' : '#{proxyConfig}'; } """ # use alert() + chrome://net-internals/#events to debug # @event {type, body} eventHandler = (event) -> switch event.type when 'OP_PROXY_ON' chrome.proxy.settings.set scope: 'regular', value: configureProxy(event.body) when 'OP_PROXY_OFF' chrome.proxy.settings.set scope: 'regular', value: mode: 'direct' else return false return true # registering listener for OP_PROXY_* events chrome.runtime.onConnect.addListener (port) -> port.onMessage.addListener (event) -> if (eventHandler(event)) port.postMessage type: 'OP_COMPLETED', body: event chrome.runtime.onMessage.addListener eventHandler
true
### Copyright (c) 2013 PI:NAME:<NAME>END_PI Licensed under the MIT license. https://github.com/openproxy/openproxy-chrome-extension ### # @settings {host, port, scheme (default - 'http'), whitelist (optional), blacklist (optional)} configureProxy = (settings) -> scheme = settings.scheme or 'http' # or "https", "socks4", "socks5" proxyConfig = "#{if scheme.indexOf('http') is 0 then 'PROXY' else 'SOCKS'} #{settings.host}:#{settings.port}" mode: 'pac_script', pacScript: data: """ function FindProxyForURL(url, host) { var bypassProxy = true; if (!isPlainHostName(host) && !shExpMatch(host, '*.local') && !isInNet(dnsResolve(host), '10.0.0.0', '255.0.0.0') && !isInNet(dnsResolve(host), '172.16.0.0', '255.240.0.0') && !isInNet(dnsResolve(host), '192.168.0.0', '255.255.0.0') && !isInNet(dnsResolve(host), '127.0.0.0', '255.255.255.0')) { var blacklist = #{JSON.stringify(settings.blacklist or [])}, blacklisted = false; for (var j = 0, je = blacklist.length; j < je; j++) { if (shExpMatch(host, blacklist[j])) { blacklisted = true; break; } } if (!blacklisted) { var whitelist = #{JSON.stringify(settings.whitelist or [])}; if (whitelist.length) { for (var i = 0, ie = whitelist.length; i < ie; i++) { if (shExpMatch(host, whitelist[i])) { bypassProxy = false; break; } } } else { bypassProxy = false; } } } return bypassProxy ? 'DIRECT' : '#{proxyConfig}'; } """ # use alert() + chrome://net-internals/#events to debug # @event {type, body} eventHandler = (event) -> switch event.type when 'OP_PROXY_ON' chrome.proxy.settings.set scope: 'regular', value: configureProxy(event.body) when 'OP_PROXY_OFF' chrome.proxy.settings.set scope: 'regular', value: mode: 'direct' else return false return true # registering listener for OP_PROXY_* events chrome.runtime.onConnect.addListener (port) -> port.onMessage.addListener (event) -> if (eventHandler(event)) port.postMessage type: 'OP_COMPLETED', body: event chrome.runtime.onMessage.addListener eventHandler
[ { "context": "# Copyright (c) 2014 Michele Bini\n\n# MIT license\n\nmodule.exports =\n magic: 'PHP'\n ", "end": 33, "score": 0.999873161315918, "start": 21, "tag": "NAME", "value": "Michele Bini" } ]
phpLib.coffee
rev22/html2cup
0
# Copyright (c) 2014 Michele Bini # MIT license module.exports = magic: 'PHP' chunks: { } hash: do (md5 = require('MD5')) -> (x)-> md5(x).substr(0,8) strip: (x)-> if false x.replace /<[?]([^?]+|[?]+[^?>])*[?]>/g, (x)=> h = @hash(x); @chunks[h] = x; @magic + h else chunks = x.split /(<[?]|[?]>)/ stripped = [] php = [] in_php = 0 php_introns = 0 for c in chunks if c is "<?" php_introns++ in_php++ if in_php > 0 php.push c else if in_php is 0 stripped.push c else throw "A PHP terminator code was found in excess" if c is "?>" in_php-- if in_php is 0 x = php.join '' php = [] h = @hash x @chunks[h] = x stripped.push @magic + h if in_php is 1 and php_introns is 1 in_php = 0 x = php.join '' php = [] h = @hash x @chunks[h] = x stripped.push @magic + h if in_php isnt 0 throw "PHP code was not terminated" stripped.join '' apply: (x)-> x.apply @ memberp: (x)-> @chunks[x]? dress: (x)-> x = x.replace /php[0-9a-z]{8}=""/g, (x)=> @chunks[x.substring(3,11)] ? "FAIL#{x}" x = x.replace /PHP[0-9a-z]{8}/ig, (x)=> @chunks[x.substring(3,11)] ? "FAIL#{x}" x idp: (x)-> /^PHP[0-9a-z]{8}/i.test(x) and @memberp(x.substring(3,11)) idp_strict: (x)-> /^PHP[0-9a-z]{8}$/i.test(x) and @memberp(x.substring(3,11)) id2key: (x)-> if /PHP[0-9a-z]{8}/i.test(x) x.substring(3,11) split: (x)-> l = [] p = "" for y in x.split /(PHP[0-9a-z]{8})/i if @memberp(y) p = p + y throw p if p.length l.push p p = y if p.length l.push p l hasAnyChunk: (x)-> for y in x.split /PHP([0-9a-z]{8})/i if @memberp(y) return true return false idToChunk: (x)-> if @idp_strict x if y = @id2key(x) @chunks[y]
166194
# Copyright (c) 2014 <NAME> # MIT license module.exports = magic: 'PHP' chunks: { } hash: do (md5 = require('MD5')) -> (x)-> md5(x).substr(0,8) strip: (x)-> if false x.replace /<[?]([^?]+|[?]+[^?>])*[?]>/g, (x)=> h = @hash(x); @chunks[h] = x; @magic + h else chunks = x.split /(<[?]|[?]>)/ stripped = [] php = [] in_php = 0 php_introns = 0 for c in chunks if c is "<?" php_introns++ in_php++ if in_php > 0 php.push c else if in_php is 0 stripped.push c else throw "A PHP terminator code was found in excess" if c is "?>" in_php-- if in_php is 0 x = php.join '' php = [] h = @hash x @chunks[h] = x stripped.push @magic + h if in_php is 1 and php_introns is 1 in_php = 0 x = php.join '' php = [] h = @hash x @chunks[h] = x stripped.push @magic + h if in_php isnt 0 throw "PHP code was not terminated" stripped.join '' apply: (x)-> x.apply @ memberp: (x)-> @chunks[x]? dress: (x)-> x = x.replace /php[0-9a-z]{8}=""/g, (x)=> @chunks[x.substring(3,11)] ? "FAIL#{x}" x = x.replace /PHP[0-9a-z]{8}/ig, (x)=> @chunks[x.substring(3,11)] ? "FAIL#{x}" x idp: (x)-> /^PHP[0-9a-z]{8}/i.test(x) and @memberp(x.substring(3,11)) idp_strict: (x)-> /^PHP[0-9a-z]{8}$/i.test(x) and @memberp(x.substring(3,11)) id2key: (x)-> if /PHP[0-9a-z]{8}/i.test(x) x.substring(3,11) split: (x)-> l = [] p = "" for y in x.split /(PHP[0-9a-z]{8})/i if @memberp(y) p = p + y throw p if p.length l.push p p = y if p.length l.push p l hasAnyChunk: (x)-> for y in x.split /PHP([0-9a-z]{8})/i if @memberp(y) return true return false idToChunk: (x)-> if @idp_strict x if y = @id2key(x) @chunks[y]
true
# Copyright (c) 2014 PI:NAME:<NAME>END_PI # MIT license module.exports = magic: 'PHP' chunks: { } hash: do (md5 = require('MD5')) -> (x)-> md5(x).substr(0,8) strip: (x)-> if false x.replace /<[?]([^?]+|[?]+[^?>])*[?]>/g, (x)=> h = @hash(x); @chunks[h] = x; @magic + h else chunks = x.split /(<[?]|[?]>)/ stripped = [] php = [] in_php = 0 php_introns = 0 for c in chunks if c is "<?" php_introns++ in_php++ if in_php > 0 php.push c else if in_php is 0 stripped.push c else throw "A PHP terminator code was found in excess" if c is "?>" in_php-- if in_php is 0 x = php.join '' php = [] h = @hash x @chunks[h] = x stripped.push @magic + h if in_php is 1 and php_introns is 1 in_php = 0 x = php.join '' php = [] h = @hash x @chunks[h] = x stripped.push @magic + h if in_php isnt 0 throw "PHP code was not terminated" stripped.join '' apply: (x)-> x.apply @ memberp: (x)-> @chunks[x]? dress: (x)-> x = x.replace /php[0-9a-z]{8}=""/g, (x)=> @chunks[x.substring(3,11)] ? "FAIL#{x}" x = x.replace /PHP[0-9a-z]{8}/ig, (x)=> @chunks[x.substring(3,11)] ? "FAIL#{x}" x idp: (x)-> /^PHP[0-9a-z]{8}/i.test(x) and @memberp(x.substring(3,11)) idp_strict: (x)-> /^PHP[0-9a-z]{8}$/i.test(x) and @memberp(x.substring(3,11)) id2key: (x)-> if /PHP[0-9a-z]{8}/i.test(x) x.substring(3,11) split: (x)-> l = [] p = "" for y in x.split /(PHP[0-9a-z]{8})/i if @memberp(y) p = p + y throw p if p.length l.push p p = y if p.length l.push p l hasAnyChunk: (x)-> for y in x.split /PHP([0-9a-z]{8})/i if @memberp(y) return true return false idToChunk: (x)-> if @idp_strict x if y = @id2key(x) @chunks[y]
[ { "context": "(done) ->\n options =\n localName: 'hello'\n @sut.setup options, done\n\n it 'shou", "end": 780, "score": 0.663425087928772, "start": 775, "tag": "NAME", "value": "hello" }, { "context": " beforeEach (done) ->\n @sut.localName = 'hel...
test/bean-manager-spec.coffee
octoblu/meshblu-connector-bean
0
{EventEmitter} = require 'events' BeanManager = require '../src/bean-manager' describe 'BeanManager', -> beforeEach -> @bean = new EventEmitter @bean.notifyOne = sinon.stub() @bean.notifyTwo = sinon.stub() @bean.notifyThree = sinon.stub() @bean.notifyFour = sinon.stub() @bean.notifyFive = sinon.stub() @bean._peripheral = {} @bean._peripheral.advertisement = localName: 'hello' @bean.connectAndSetup = sinon.stub().yields null @sut = new BeanManager @sut.BLEBean = {} {@BLEBean} = @sut @BLEBean.discover = sinon.stub().yields @bean afterEach (done) -> @sut.close done describe '->setup', -> context 'when starting for the first time', -> beforeEach (done) -> options = localName: 'hello' @sut.setup options, done it 'should connect to a bean', -> expect(@sut.bean).to.exist context 'when localName is the same', -> beforeEach (done) -> @sut.localName = 'hello' @sut.bean = @bean options = localName: 'hello' @sut.setup options, done it 'should connect to a bean', -> expect(@sut.bean).to.equal @bean context 'when localName is the has changed', -> beforeEach (done) -> @oldBean = _peripheral: advertisement: localName: 'oldBean' disconnect: sinon.stub().yields null @sut.localName = 'oldBean' @sut.bean = @oldBean options = localName: 'hello' @sut.setup options, done it 'should disconnect the old bean', -> expect(@oldBean.disconnect).to.have.been.called it 'should connect to a bean', -> expect(@sut.bean).to.equal @bean describe '->_initializeOnRssi', -> context 'when interval.rssi is set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'rssi' interval: rssi_enable: true rssi: 1 @sut.setup options, done it 'should create @intervalPollForRssi', -> expect(@sut.intervalPollForRssi).to.exist context 'when interval.rssi is not set', -> beforeEach (done) -> options = localName: 'rssi' @sut.setup options, done it 'should not create an interval', -> expect(@sut.intervalPollForRssi).not.to.exist describe '->_initializeOnAccelerometer', -> context 'when interval.accelerometer is set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'accelerometer' interval: accel_enable: true accelerometer: 1 @sut.setup options, done beforeEach 'emitting accell', (done) -> @bean.once 'accell', => done() @bean.emit 'accell', 1, 2, 3 it 'should call emit', -> data = accelerometer: x: 1 y: 2 z: 3 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when interval.accelerometer is not set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'accelerometer' @sut.setup options, done beforeEach 'emitting accell', (done) -> @bean.once 'accell', => done() @bean.emit 'accell', 1, 2, 3 it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeOnTemperature', -> context 'when interval.temperature is set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'temperature' interval: temp_enable: true temperature: 1 @sut.setup options, done beforeEach 'emitting temp', (done) -> @bean.once 'temp', => done() @bean.emit 'temp', 90 it 'should call emit', -> data = temperature: degrees: 90 unit: 'Celsius' expect(@sut.emit).to.have.been.calledWith 'data', data context 'when interval.temperature is not set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'temperature' @sut.setup options, done beforeEach 'emitting temp', (done) -> @bean.once 'temp', => done() @bean.emit 'temp', 1, 2, 3 it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch1', -> context 'when notify.scratch1 is set', -> beforeEach (done) -> @bean.notifyOne = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch1' notify: scratch1: true @sut.setup options, done it 'should call emit', -> data = scratch1: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch1 is not set', -> beforeEach (done) -> @bean.notifyOne = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch1' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch2', -> context 'when notify.scratch2 is set', -> beforeEach (done) -> @bean.notifyTwo = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch2' notify: scratch2: true @sut.setup options, done it 'should call emit', -> data = scratch2: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch2 is not set', -> beforeEach (done) -> @bean.notifyTwo = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch2' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch3', -> context 'when notify.scratch3 is set', -> beforeEach (done) -> @bean.notifyThree = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch3' notify: scratch3: true @sut.setup options, done it 'should call emit', -> data = scratch3: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch3 is not set', -> beforeEach (done) -> @bean.notifyThree = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch3' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch4', -> context 'when notify.scratch4 is set', -> beforeEach (done) -> @bean.notifyFour = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch4' notify: scratch4: true @sut.setup options, done it 'should call emit', -> data = scratch4: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch4 is not set', -> beforeEach (done) -> @bean.notifyFour = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch4' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch5', -> context 'when notify.scratch5 is set', -> beforeEach (done) -> @bean.notifyFive = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch5' notify: scratch5: true @sut.setup options, done it 'should call emit', -> data = scratch5: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch5 is not set', -> beforeEach (done) -> @bean.notifyFive = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch5' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->changeLight', -> beforeEach (done) -> @sut.setup {}, done beforeEach (done) -> @bean.setColor = sinon.stub().yields null @sut.changeLight 'white', done it 'should call bean.setColor', -> expect(@bean.setColor).to.have.been.called describe '->turnLightOff', -> beforeEach (done) -> @sut.setup {}, done beforeEach (done) -> @bean.setColor = sinon.stub().yields null @sut.turnLightOff done it 'should call bean.setColor', -> expect(@bean.setColor).to.have.been.called
4549
{EventEmitter} = require 'events' BeanManager = require '../src/bean-manager' describe 'BeanManager', -> beforeEach -> @bean = new EventEmitter @bean.notifyOne = sinon.stub() @bean.notifyTwo = sinon.stub() @bean.notifyThree = sinon.stub() @bean.notifyFour = sinon.stub() @bean.notifyFive = sinon.stub() @bean._peripheral = {} @bean._peripheral.advertisement = localName: 'hello' @bean.connectAndSetup = sinon.stub().yields null @sut = new BeanManager @sut.BLEBean = {} {@BLEBean} = @sut @BLEBean.discover = sinon.stub().yields @bean afterEach (done) -> @sut.close done describe '->setup', -> context 'when starting for the first time', -> beforeEach (done) -> options = localName: '<NAME>' @sut.setup options, done it 'should connect to a bean', -> expect(@sut.bean).to.exist context 'when localName is the same', -> beforeEach (done) -> @sut.localName = '<NAME>' @sut.bean = @bean options = localName: 'hello' @sut.setup options, done it 'should connect to a bean', -> expect(@sut.bean).to.equal @bean context 'when localName is the has changed', -> beforeEach (done) -> @oldBean = _peripheral: advertisement: localName: '<NAME>Bean' disconnect: sinon.stub().yields null @sut.localName = '<NAME>' @sut.bean = @oldBean options = localName: '<NAME>' @sut.setup options, done it 'should disconnect the old bean', -> expect(@oldBean.disconnect).to.have.been.called it 'should connect to a bean', -> expect(@sut.bean).to.equal @bean describe '->_initializeOnRssi', -> context 'when interval.rssi is set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'rssi' interval: rssi_enable: true rssi: 1 @sut.setup options, done it 'should create @intervalPollForRssi', -> expect(@sut.intervalPollForRssi).to.exist context 'when interval.rssi is not set', -> beforeEach (done) -> options = localName: 'rssi' @sut.setup options, done it 'should not create an interval', -> expect(@sut.intervalPollForRssi).not.to.exist describe '->_initializeOnAccelerometer', -> context 'when interval.accelerometer is set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'accelerometer' interval: accel_enable: true accelerometer: 1 @sut.setup options, done beforeEach 'emitting accell', (done) -> @bean.once 'accell', => done() @bean.emit 'accell', 1, 2, 3 it 'should call emit', -> data = accelerometer: x: 1 y: 2 z: 3 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when interval.accelerometer is not set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'accelerometer' @sut.setup options, done beforeEach 'emitting accell', (done) -> @bean.once 'accell', => done() @bean.emit 'accell', 1, 2, 3 it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeOnTemperature', -> context 'when interval.temperature is set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'temperature' interval: temp_enable: true temperature: 1 @sut.setup options, done beforeEach 'emitting temp', (done) -> @bean.once 'temp', => done() @bean.emit 'temp', 90 it 'should call emit', -> data = temperature: degrees: 90 unit: 'Celsius' expect(@sut.emit).to.have.been.calledWith 'data', data context 'when interval.temperature is not set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'temperature' @sut.setup options, done beforeEach 'emitting temp', (done) -> @bean.once 'temp', => done() @bean.emit 'temp', 1, 2, 3 it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch1', -> context 'when notify.scratch1 is set', -> beforeEach (done) -> @bean.notifyOne = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch1' notify: scratch1: true @sut.setup options, done it 'should call emit', -> data = scratch1: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch1 is not set', -> beforeEach (done) -> @bean.notifyOne = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch1' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch2', -> context 'when notify.scratch2 is set', -> beforeEach (done) -> @bean.notifyTwo = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch2' notify: scratch2: true @sut.setup options, done it 'should call emit', -> data = scratch2: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch2 is not set', -> beforeEach (done) -> @bean.notifyTwo = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch2' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch3', -> context 'when notify.scratch3 is set', -> beforeEach (done) -> @bean.notifyThree = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch3' notify: scratch3: true @sut.setup options, done it 'should call emit', -> data = scratch3: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch3 is not set', -> beforeEach (done) -> @bean.notifyThree = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch3' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch4', -> context 'when notify.scratch4 is set', -> beforeEach (done) -> @bean.notifyFour = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch4' notify: scratch4: true @sut.setup options, done it 'should call emit', -> data = scratch4: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch4 is not set', -> beforeEach (done) -> @bean.notifyFour = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch4' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch5', -> context 'when notify.scratch5 is set', -> beforeEach (done) -> @bean.notifyFive = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch5' notify: scratch5: true @sut.setup options, done it 'should call emit', -> data = scratch5: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch5 is not set', -> beforeEach (done) -> @bean.notifyFive = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch5' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->changeLight', -> beforeEach (done) -> @sut.setup {}, done beforeEach (done) -> @bean.setColor = sinon.stub().yields null @sut.changeLight 'white', done it 'should call bean.setColor', -> expect(@bean.setColor).to.have.been.called describe '->turnLightOff', -> beforeEach (done) -> @sut.setup {}, done beforeEach (done) -> @bean.setColor = sinon.stub().yields null @sut.turnLightOff done it 'should call bean.setColor', -> expect(@bean.setColor).to.have.been.called
true
{EventEmitter} = require 'events' BeanManager = require '../src/bean-manager' describe 'BeanManager', -> beforeEach -> @bean = new EventEmitter @bean.notifyOne = sinon.stub() @bean.notifyTwo = sinon.stub() @bean.notifyThree = sinon.stub() @bean.notifyFour = sinon.stub() @bean.notifyFive = sinon.stub() @bean._peripheral = {} @bean._peripheral.advertisement = localName: 'hello' @bean.connectAndSetup = sinon.stub().yields null @sut = new BeanManager @sut.BLEBean = {} {@BLEBean} = @sut @BLEBean.discover = sinon.stub().yields @bean afterEach (done) -> @sut.close done describe '->setup', -> context 'when starting for the first time', -> beforeEach (done) -> options = localName: 'PI:NAME:<NAME>END_PI' @sut.setup options, done it 'should connect to a bean', -> expect(@sut.bean).to.exist context 'when localName is the same', -> beforeEach (done) -> @sut.localName = 'PI:NAME:<NAME>END_PI' @sut.bean = @bean options = localName: 'hello' @sut.setup options, done it 'should connect to a bean', -> expect(@sut.bean).to.equal @bean context 'when localName is the has changed', -> beforeEach (done) -> @oldBean = _peripheral: advertisement: localName: 'PI:NAME:<NAME>END_PIBean' disconnect: sinon.stub().yields null @sut.localName = 'PI:NAME:<NAME>END_PI' @sut.bean = @oldBean options = localName: 'PI:NAME:<NAME>END_PI' @sut.setup options, done it 'should disconnect the old bean', -> expect(@oldBean.disconnect).to.have.been.called it 'should connect to a bean', -> expect(@sut.bean).to.equal @bean describe '->_initializeOnRssi', -> context 'when interval.rssi is set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'rssi' interval: rssi_enable: true rssi: 1 @sut.setup options, done it 'should create @intervalPollForRssi', -> expect(@sut.intervalPollForRssi).to.exist context 'when interval.rssi is not set', -> beforeEach (done) -> options = localName: 'rssi' @sut.setup options, done it 'should not create an interval', -> expect(@sut.intervalPollForRssi).not.to.exist describe '->_initializeOnAccelerometer', -> context 'when interval.accelerometer is set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'accelerometer' interval: accel_enable: true accelerometer: 1 @sut.setup options, done beforeEach 'emitting accell', (done) -> @bean.once 'accell', => done() @bean.emit 'accell', 1, 2, 3 it 'should call emit', -> data = accelerometer: x: 1 y: 2 z: 3 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when interval.accelerometer is not set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'accelerometer' @sut.setup options, done beforeEach 'emitting accell', (done) -> @bean.once 'accell', => done() @bean.emit 'accell', 1, 2, 3 it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeOnTemperature', -> context 'when interval.temperature is set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'temperature' interval: temp_enable: true temperature: 1 @sut.setup options, done beforeEach 'emitting temp', (done) -> @bean.once 'temp', => done() @bean.emit 'temp', 90 it 'should call emit', -> data = temperature: degrees: 90 unit: 'Celsius' expect(@sut.emit).to.have.been.calledWith 'data', data context 'when interval.temperature is not set', -> beforeEach (done) -> @sut.emit = sinon.stub() options = localName: 'temperature' @sut.setup options, done beforeEach 'emitting temp', (done) -> @bean.once 'temp', => done() @bean.emit 'temp', 1, 2, 3 it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch1', -> context 'when notify.scratch1 is set', -> beforeEach (done) -> @bean.notifyOne = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch1' notify: scratch1: true @sut.setup options, done it 'should call emit', -> data = scratch1: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch1 is not set', -> beforeEach (done) -> @bean.notifyOne = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch1' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch2', -> context 'when notify.scratch2 is set', -> beforeEach (done) -> @bean.notifyTwo = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch2' notify: scratch2: true @sut.setup options, done it 'should call emit', -> data = scratch2: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch2 is not set', -> beforeEach (done) -> @bean.notifyTwo = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch2' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch3', -> context 'when notify.scratch3 is set', -> beforeEach (done) -> @bean.notifyThree = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch3' notify: scratch3: true @sut.setup options, done it 'should call emit', -> data = scratch3: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch3 is not set', -> beforeEach (done) -> @bean.notifyThree = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch3' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch4', -> context 'when notify.scratch4 is set', -> beforeEach (done) -> @bean.notifyFour = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch4' notify: scratch4: true @sut.setup options, done it 'should call emit', -> data = scratch4: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch4 is not set', -> beforeEach (done) -> @bean.notifyFour = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch4' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->_initializeNotifyScratch scratch5', -> context 'when notify.scratch5 is set', -> beforeEach (done) -> @bean.notifyFive = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch5' notify: scratch5: true @sut.setup options, done it 'should call emit', -> data = scratch5: 0 expect(@sut.emit).to.have.been.calledWith 'data', data context 'when notify.scratch5 is not set', -> beforeEach (done) -> @bean.notifyFive = sinon.stub().yields [0,0,0,0] @sut.emit = sinon.stub() options = localName: 'scratch5' @sut.setup options, done it 'should not call emit', -> expect(@sut.emit).not.to.have.been.called describe '->changeLight', -> beforeEach (done) -> @sut.setup {}, done beforeEach (done) -> @bean.setColor = sinon.stub().yields null @sut.changeLight 'white', done it 'should call bean.setColor', -> expect(@bean.setColor).to.have.been.called describe '->turnLightOff', -> beforeEach (done) -> @sut.setup {}, done beforeEach (done) -> @bean.setColor = sinon.stub().yields null @sut.turnLightOff done it 'should call bean.setColor', -> expect(@bean.setColor).to.have.been.called
[ { "context": "', (err, user) ->\n user.name.should.equal 'Craig Spaeth'\n done()\n\n it 'gets partner_ids', (done", "end": 1179, "score": 0.9998725652694702, "start": 1167, "tag": "NAME", "value": "Craig Spaeth" }, { "context": " (err, user) ->\n user.name.s...
src/api/apps/users/test/model.test.coffee
ashleyjelks/positron
0
_ = require 'underscore' sinon = require 'sinon' rewire = require 'rewire' { db, fabricate, empty, fixtures } = require '../../../test/helpers/db' User = rewire '../model' { ObjectId } = require 'mongojs' gravity = require('antigravity').server gravityFabricate = require('antigravity').fabricate express = require 'express' app = express() app.get '/__gravity/api/v1/user/563d08e6275b247014000026', (req, res, next) -> user = gravityFabricate 'user', type: 'User', id: '563d08e6275b247014000026' res.send user app.use '/__gravity', gravity describe 'User', -> beforeEach (done) -> empty => User.__set__ 'ARTSY_URL', 'http://localhost:5000/__gravity' User.__set__ 'jwtDecode', @jwtDecode = sinon.stub().returns({ partner_ids: ['5086df098523e60002000012'] }) fabricate 'channels', { id: '5086df098523e60002000018' }, (err, @channel) => @server = app.listen 5000, => done() afterEach -> @server.close() describe '#fromAccessToken', -> it 'flattens & merges gravity user data into a nicer format', (done) -> User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal 'Craig Spaeth' done() it 'gets partner_ids', (done) -> User.fromAccessToken 'foobar', (err, user) -> user.partner_ids[0].toString().should.equal '5086df098523e60002000012' done() it 'inserts a non-existing user', (done) -> User.fromAccessToken 'foobar', (err, user) -> db.users.findOne (err, user) -> user.name.should.equal 'Craig Spaeth' done() it 'finds an existing user', (done) -> user = fixtures().users db.users.insert user, -> User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal 'Craig Spaeth' done() it 'returns the user if partner_ids have not changed', (done) -> user = _.extend {}, fixtures().users, { name: 'Kana Abe' partner_ids: ['5086df098523e60002000012'] access_token: '$2a$10$PJrPMBadu1NPdmnshBgFbeZG5cyzJHBLK8D73niNWb7bPz5GyKH.u' } db.users.insert user, (err, result) -> User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal 'Kana Abe' done() it 'creates a user if there is no user', (done) -> User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal 'Craig Spaeth' done() it 'updates a user if partner_ids have changed', (done) -> user = _.extend {}, fixtures().users, partner_ids: [] db.users.insert user, -> User.fromAccessToken 'foobar', (err, user) -> user.partner_ids[0].toString().should.equal '5086df098523e60002000012' done() describe '#present', -> it 'converts _id to id', -> data = User.present _.extend fixtures().users, _id: 'foo' (data._id?).should.not.be.ok data.id.should.equal 'foo' describe '#refresh', -> it 'refreshes the user basic info', (done) -> user = _.extend fixtures().users, {name: 'Nah'} db.users.insert user, -> User.refresh 'foobar', (err, user) -> user.name.should.equal 'Craig Spaeth' User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal 'Craig Spaeth' done() it 'refreshes the user partner access', (done) -> user = _.extend fixtures().users, { has_access_token: true, partner_ids: ['123'] } db.users.insert user, (err, user) -> user.partner_ids.length.should.equal 1 user.partner_ids[0].should.equal '123' User.refresh 'foobar', (err, user) -> user.partner_ids[0].toString().should.equal '5086df098523e60002000012' User.fromAccessToken 'foobar', (err, user) -> user.partner_ids[0].toString().should.equal '5086df098523e60002000012' done() it 'refreshes the user channel access', (done) -> user = _.extend fixtures().users, { has_access_token: true, channel_ids: ['123'] } db.users.insert user, (err, user) -> user.channel_ids.length.should.equal 1 User.refresh 'foobar', (err, user) -> user.channel_ids.length.should.equal 0 User.fromAccessToken 'foobar', (err, user) -> user.channel_ids.length.should.equal 0 done() describe '#hasChannelAccess', -> it 'returns true for a channel member', (done) -> user = _.extend fixtures().users, { channel_ids: [ ObjectId '5086df098523e60002000018' ] } channel = _.extend fixtures().channels, { _id: ObjectId('5086df098523e60002000018') } db.channels.insert channel , (err, channel) -> User.hasChannelAccess(user, '5086df098523e60002000018').should.be.true() done() it 'returns true for a partner channel member', (done) -> user = _.extend fixtures().users, { partner_ids: [ '5086df098523e60002000012' ] } User.hasChannelAccess(user, '5086df098523e60002000012').should.be.true() done() it 'returns true for a non-partner or non-channel member but admin on a partner channel', (done) -> user = _.extend fixtures().users, { channel_ids: [], partner_ids: [] } User.hasChannelAccess(user, '5086df098523e60002000012').should.be.true() done() it 'returns true for a non-partner or non-channel member but admin when no channel_id', (done) -> user = _.extend fixtures().users, { channel_ids: [], partner_ids: [], type: 'Admin' } User.hasChannelAccess(user).should.be.true() done() it 'returns false for a non-partner or non-channel member', (done) -> user = _.extend fixtures().users, { channel_ids: [], partner_ids: [], type: 'User' } User.hasChannelAccess(user, '5086df098523e60002000012').should.be.false() done()
25499
_ = require 'underscore' sinon = require 'sinon' rewire = require 'rewire' { db, fabricate, empty, fixtures } = require '../../../test/helpers/db' User = rewire '../model' { ObjectId } = require 'mongojs' gravity = require('antigravity').server gravityFabricate = require('antigravity').fabricate express = require 'express' app = express() app.get '/__gravity/api/v1/user/563d08e6275b247014000026', (req, res, next) -> user = gravityFabricate 'user', type: 'User', id: '563d08e6275b247014000026' res.send user app.use '/__gravity', gravity describe 'User', -> beforeEach (done) -> empty => User.__set__ 'ARTSY_URL', 'http://localhost:5000/__gravity' User.__set__ 'jwtDecode', @jwtDecode = sinon.stub().returns({ partner_ids: ['5086df098523e60002000012'] }) fabricate 'channels', { id: '5086df098523e60002000018' }, (err, @channel) => @server = app.listen 5000, => done() afterEach -> @server.close() describe '#fromAccessToken', -> it 'flattens & merges gravity user data into a nicer format', (done) -> User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal '<NAME>' done() it 'gets partner_ids', (done) -> User.fromAccessToken 'foobar', (err, user) -> user.partner_ids[0].toString().should.equal '5086df098523e60002000012' done() it 'inserts a non-existing user', (done) -> User.fromAccessToken 'foobar', (err, user) -> db.users.findOne (err, user) -> user.name.should.equal '<NAME>' done() it 'finds an existing user', (done) -> user = fixtures().users db.users.insert user, -> User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal '<NAME>' done() it 'returns the user if partner_ids have not changed', (done) -> user = _.extend {}, fixtures().users, { name: '<NAME>' partner_ids: ['5086df098523e60002000012'] access_token: <PASSWORD>' } db.users.insert user, (err, result) -> User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal '<NAME>' done() it 'creates a user if there is no user', (done) -> User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal '<NAME>' done() it 'updates a user if partner_ids have changed', (done) -> user = _.extend {}, fixtures().users, partner_ids: [] db.users.insert user, -> User.fromAccessToken 'foobar', (err, user) -> user.partner_ids[0].toString().should.equal '5086df098523e60002000012' done() describe '#present', -> it 'converts _id to id', -> data = User.present _.extend fixtures().users, _id: 'foo' (data._id?).should.not.be.ok data.id.should.equal 'foo' describe '#refresh', -> it 'refreshes the user basic info', (done) -> user = _.extend fixtures().users, {name: '<NAME>'} db.users.insert user, -> User.refresh 'foobar', (err, user) -> user.name.should.equal '<NAME>' User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal '<NAME>' done() it 'refreshes the user partner access', (done) -> user = _.extend fixtures().users, { has_access_token: true, partner_ids: ['123'] } db.users.insert user, (err, user) -> user.partner_ids.length.should.equal 1 user.partner_ids[0].should.equal '123' User.refresh 'foobar', (err, user) -> user.partner_ids[0].toString().should.equal '5086df098523e60002000012' User.fromAccessToken 'foobar', (err, user) -> user.partner_ids[0].toString().should.equal '5086df098523e60002000012' done() it 'refreshes the user channel access', (done) -> user = _.extend fixtures().users, { has_access_token: true, channel_ids: ['123'] } db.users.insert user, (err, user) -> user.channel_ids.length.should.equal 1 User.refresh 'foobar', (err, user) -> user.channel_ids.length.should.equal 0 User.fromAccessToken 'foobar', (err, user) -> user.channel_ids.length.should.equal 0 done() describe '#hasChannelAccess', -> it 'returns true for a channel member', (done) -> user = _.extend fixtures().users, { channel_ids: [ ObjectId '5086df098523e60002000018' ] } channel = _.extend fixtures().channels, { _id: ObjectId('5086df098523e60002000018') } db.channels.insert channel , (err, channel) -> User.hasChannelAccess(user, '5086df098523e60002000018').should.be.true() done() it 'returns true for a partner channel member', (done) -> user = _.extend fixtures().users, { partner_ids: [ '5086df098523e60002000012' ] } User.hasChannelAccess(user, '5086df098523e60002000012').should.be.true() done() it 'returns true for a non-partner or non-channel member but admin on a partner channel', (done) -> user = _.extend fixtures().users, { channel_ids: [], partner_ids: [] } User.hasChannelAccess(user, '5086df098523e60002000012').should.be.true() done() it 'returns true for a non-partner or non-channel member but admin when no channel_id', (done) -> user = _.extend fixtures().users, { channel_ids: [], partner_ids: [], type: 'Admin' } User.hasChannelAccess(user).should.be.true() done() it 'returns false for a non-partner or non-channel member', (done) -> user = _.extend fixtures().users, { channel_ids: [], partner_ids: [], type: 'User' } User.hasChannelAccess(user, '5086df098523e60002000012').should.be.false() done()
true
_ = require 'underscore' sinon = require 'sinon' rewire = require 'rewire' { db, fabricate, empty, fixtures } = require '../../../test/helpers/db' User = rewire '../model' { ObjectId } = require 'mongojs' gravity = require('antigravity').server gravityFabricate = require('antigravity').fabricate express = require 'express' app = express() app.get '/__gravity/api/v1/user/563d08e6275b247014000026', (req, res, next) -> user = gravityFabricate 'user', type: 'User', id: '563d08e6275b247014000026' res.send user app.use '/__gravity', gravity describe 'User', -> beforeEach (done) -> empty => User.__set__ 'ARTSY_URL', 'http://localhost:5000/__gravity' User.__set__ 'jwtDecode', @jwtDecode = sinon.stub().returns({ partner_ids: ['5086df098523e60002000012'] }) fabricate 'channels', { id: '5086df098523e60002000018' }, (err, @channel) => @server = app.listen 5000, => done() afterEach -> @server.close() describe '#fromAccessToken', -> it 'flattens & merges gravity user data into a nicer format', (done) -> User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal 'PI:NAME:<NAME>END_PI' done() it 'gets partner_ids', (done) -> User.fromAccessToken 'foobar', (err, user) -> user.partner_ids[0].toString().should.equal '5086df098523e60002000012' done() it 'inserts a non-existing user', (done) -> User.fromAccessToken 'foobar', (err, user) -> db.users.findOne (err, user) -> user.name.should.equal 'PI:NAME:<NAME>END_PI' done() it 'finds an existing user', (done) -> user = fixtures().users db.users.insert user, -> User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal 'PI:NAME:<NAME>END_PI' done() it 'returns the user if partner_ids have not changed', (done) -> user = _.extend {}, fixtures().users, { name: 'PI:NAME:<NAME>END_PI' partner_ids: ['5086df098523e60002000012'] access_token: PI:PASSWORD:<PASSWORD>END_PI' } db.users.insert user, (err, result) -> User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal 'PI:NAME:<NAME>END_PI' done() it 'creates a user if there is no user', (done) -> User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal 'PI:NAME:<NAME>END_PI' done() it 'updates a user if partner_ids have changed', (done) -> user = _.extend {}, fixtures().users, partner_ids: [] db.users.insert user, -> User.fromAccessToken 'foobar', (err, user) -> user.partner_ids[0].toString().should.equal '5086df098523e60002000012' done() describe '#present', -> it 'converts _id to id', -> data = User.present _.extend fixtures().users, _id: 'foo' (data._id?).should.not.be.ok data.id.should.equal 'foo' describe '#refresh', -> it 'refreshes the user basic info', (done) -> user = _.extend fixtures().users, {name: 'PI:NAME:<NAME>END_PI'} db.users.insert user, -> User.refresh 'foobar', (err, user) -> user.name.should.equal 'PI:NAME:<NAME>END_PI' User.fromAccessToken 'foobar', (err, user) -> user.name.should.equal 'PI:NAME:<NAME>END_PI' done() it 'refreshes the user partner access', (done) -> user = _.extend fixtures().users, { has_access_token: true, partner_ids: ['123'] } db.users.insert user, (err, user) -> user.partner_ids.length.should.equal 1 user.partner_ids[0].should.equal '123' User.refresh 'foobar', (err, user) -> user.partner_ids[0].toString().should.equal '5086df098523e60002000012' User.fromAccessToken 'foobar', (err, user) -> user.partner_ids[0].toString().should.equal '5086df098523e60002000012' done() it 'refreshes the user channel access', (done) -> user = _.extend fixtures().users, { has_access_token: true, channel_ids: ['123'] } db.users.insert user, (err, user) -> user.channel_ids.length.should.equal 1 User.refresh 'foobar', (err, user) -> user.channel_ids.length.should.equal 0 User.fromAccessToken 'foobar', (err, user) -> user.channel_ids.length.should.equal 0 done() describe '#hasChannelAccess', -> it 'returns true for a channel member', (done) -> user = _.extend fixtures().users, { channel_ids: [ ObjectId '5086df098523e60002000018' ] } channel = _.extend fixtures().channels, { _id: ObjectId('5086df098523e60002000018') } db.channels.insert channel , (err, channel) -> User.hasChannelAccess(user, '5086df098523e60002000018').should.be.true() done() it 'returns true for a partner channel member', (done) -> user = _.extend fixtures().users, { partner_ids: [ '5086df098523e60002000012' ] } User.hasChannelAccess(user, '5086df098523e60002000012').should.be.true() done() it 'returns true for a non-partner or non-channel member but admin on a partner channel', (done) -> user = _.extend fixtures().users, { channel_ids: [], partner_ids: [] } User.hasChannelAccess(user, '5086df098523e60002000012').should.be.true() done() it 'returns true for a non-partner or non-channel member but admin when no channel_id', (done) -> user = _.extend fixtures().users, { channel_ids: [], partner_ids: [], type: 'Admin' } User.hasChannelAccess(user).should.be.true() done() it 'returns false for a non-partner or non-channel member', (done) -> user = _.extend fixtures().users, { channel_ids: [], partner_ids: [], type: 'User' } User.hasChannelAccess(user, '5086df098523e60002000012').should.be.false() done()
[ { "context": "\n * @namespace KINOUT\n * @class Boot\n *\n * @author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\n$$(document).r", "end": 111, "score": 0.99988853931427, "start": 90, "tag": "NAME", "value": "Javier Jimenez Villar" }, { "context": " @class Boot\n *\n * ...
src/js.script.coffee
biojazzard/kirbout
2
### * Description or Responsability * * @namespace KINOUT * @class Boot * * @author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi ### $$(document).ready -> KINOUT.init() return
42489
### * Description or Responsability * * @namespace KINOUT * @class Boot * * @author <NAME> <<EMAIL>> || @soyjavi ### $$(document).ready -> KINOUT.init() return
true
### * Description or Responsability * * @namespace KINOUT * @class Boot * * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @soyjavi ### $$(document).ready -> KINOUT.init() return
[ { "context": ")\n modifier.should.equal 0x14CD\n\n describe \"Kee Berry\", ->\n it \"raises defense if hit by a physical ", "end": 3383, "score": 0.9004330635070801, "start": 3374, "tag": "NAME", "value": "Kee Berry" }, { "context": ": 'xy'\n team1: [Factory('Magikarp...
test/xy/items.coffee
sarenji/pokebattle-sim
5
{Item} = require('../../server/xy/data/items') {Pokemon} = require '../../server/xy/pokemon' {Weather} = require('../../shared/weather') {Attachment, Status} = require '../../server/xy/attachment' {Move} = require '../../server/xy/move' {Factory} = require '../factory' util = require '../../server/xy/util' should = require 'should' {_} = require 'underscore' shared = require '../shared' require '../helpers' describe "XY Items:", -> describe "Weakness Policy", -> it "raises Attack and Sp. Attack by 2 if hit by a super-effective move", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] thunderbolt = @battle.getMove("Thunderbolt") @p1.stages.should.containEql(attack: 0, specialAttack: 0) @battle.performMove(@p2, thunderbolt) @p1.stages.should.containEql(attack: 2, specialAttack: 2) it "is consumed after use", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] thunderbolt = @battle.getMove("Thunderbolt") @battle.performMove(@p2, thunderbolt) @p1.hasItem().should.be.false it "is not used if hit by a non-super-effective move", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] ember = @battle.getMove("Ember") @battle.performMove(@p2, ember) @p1.hasItem().should.be.true @p1.stages.should.containEql(attack: 0, specialAttack: 0) it "is not used if hit by a super-effective move that is non-damaging", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] thunderWave = @battle.getMove("Thunder Wave") @battle.performMove(@p2, thunderWave) @p1.hasItem().should.be.true @p1.stages.should.containEql(attack: 0, specialAttack: 0) it "not used if the wearer is behind a substitute", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] @p1.attach(Attachment.Substitute, hp: 1) thunderbolt = @battle.getMove("Thunderbolt") @battle.performMove(@p2, thunderbolt) @p1.hasItem().should.be.true @p1.stages.should.containEql(attack: 0, specialAttack: 0) describe "Assault Vest", -> it "blocks non-damaging moves", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Assault Vest')] splash = @battle.getMove("Splash") @p1.isMoveBlocked(splash).should.be.true it "doesn't block damaging moves", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Assault Vest')] tackle = @battle.getMove("Tackle") @p1.isMoveBlocked(tackle).should.be.false it "raises special defense by 1.5", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp')] spDef = @p1.stat('specialDefense') @p1.setItem(Item.AssaultVest) @p1.stat('specialDefense').should.equal Math.floor(spDef * 1.5) describe "Gems", -> it "now only boosts their respective type by x1.3", -> shared.create.call(this, gen: 'xy') move = @battle.getMove('Acrobatics') modifier = Item.FlyingGem::modifyBasePower(move, @p1, @p2) modifier.should.equal 0x14CD describe "Kee Berry", -> it "raises defense if hit by a physical attack", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Kee Berry')] @p1.stages.should.containEql(defense: 0) @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.stages.should.containEql(defense: 1) it "is consumed after use", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Kee Berry')] @p1.hasItem().should.be.true @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.hasItem().should.be.false describe "Maranga Berry", -> it "raises defense if hit by a special attack", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Maranga Berry')] @p1.stages.should.containEql(specialDefense: 0) @battle.performMove(@p2, @battle.getMove("Ember")) @p1.stages.should.containEql(specialDefense: 1) it "is consumed after use", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Maranga Berry')] @p1.hasItem().should.be.true @battle.performMove(@p2, @battle.getMove("Ember")) @p1.hasItem().should.be.false describe "Safety Goggles", -> it "makes the user immune to weather", -> shared.create.call this, gen: 'xy' team1: [Factory("Magikarp", item: "Safety Goggles")] @p1.isWeatherDamageImmune(Weather.SAND).should.be.true @p1.isWeatherDamageImmune(Weather.HAIL).should.be.true it "makes the user immune to powder moves", -> shared.create.call this, gen: 'xy' team1: [Factory("Magikarp", item: "Safety Goggles")] spore = @battle.getMove("Spore") mock = @sandbox.mock(spore).expects('hit').never() @battle.performMove(@p2, spore) mock.verify()
45674
{Item} = require('../../server/xy/data/items') {Pokemon} = require '../../server/xy/pokemon' {Weather} = require('../../shared/weather') {Attachment, Status} = require '../../server/xy/attachment' {Move} = require '../../server/xy/move' {Factory} = require '../factory' util = require '../../server/xy/util' should = require 'should' {_} = require 'underscore' shared = require '../shared' require '../helpers' describe "XY Items:", -> describe "Weakness Policy", -> it "raises Attack and Sp. Attack by 2 if hit by a super-effective move", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] thunderbolt = @battle.getMove("Thunderbolt") @p1.stages.should.containEql(attack: 0, specialAttack: 0) @battle.performMove(@p2, thunderbolt) @p1.stages.should.containEql(attack: 2, specialAttack: 2) it "is consumed after use", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] thunderbolt = @battle.getMove("Thunderbolt") @battle.performMove(@p2, thunderbolt) @p1.hasItem().should.be.false it "is not used if hit by a non-super-effective move", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] ember = @battle.getMove("Ember") @battle.performMove(@p2, ember) @p1.hasItem().should.be.true @p1.stages.should.containEql(attack: 0, specialAttack: 0) it "is not used if hit by a super-effective move that is non-damaging", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] thunderWave = @battle.getMove("Thunder Wave") @battle.performMove(@p2, thunderWave) @p1.hasItem().should.be.true @p1.stages.should.containEql(attack: 0, specialAttack: 0) it "not used if the wearer is behind a substitute", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] @p1.attach(Attachment.Substitute, hp: 1) thunderbolt = @battle.getMove("Thunderbolt") @battle.performMove(@p2, thunderbolt) @p1.hasItem().should.be.true @p1.stages.should.containEql(attack: 0, specialAttack: 0) describe "Assault Vest", -> it "blocks non-damaging moves", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Assault Vest')] splash = @battle.getMove("Splash") @p1.isMoveBlocked(splash).should.be.true it "doesn't block damaging moves", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Assault Vest')] tackle = @battle.getMove("Tackle") @p1.isMoveBlocked(tackle).should.be.false it "raises special defense by 1.5", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp')] spDef = @p1.stat('specialDefense') @p1.setItem(Item.AssaultVest) @p1.stat('specialDefense').should.equal Math.floor(spDef * 1.5) describe "Gems", -> it "now only boosts their respective type by x1.3", -> shared.create.call(this, gen: 'xy') move = @battle.getMove('Acrobatics') modifier = Item.FlyingGem::modifyBasePower(move, @p1, @p2) modifier.should.equal 0x14CD describe "<NAME>", -> it "raises defense if hit by a physical attack", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: '<NAME>')] @p1.stages.should.containEql(defense: 0) @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.stages.should.containEql(defense: 1) it "is consumed after use", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: '<NAME>')] @p1.hasItem().should.be.true @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.hasItem().should.be.false describe "<NAME>", -> it "raises defense if hit by a special attack", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: '<NAME>')] @p1.stages.should.containEql(specialDefense: 0) @battle.performMove(@p2, @battle.getMove("Ember")) @p1.stages.should.containEql(specialDefense: 1) it "is consumed after use", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: '<NAME>')] @p1.hasItem().should.be.true @battle.performMove(@p2, @battle.getMove("Ember")) @p1.hasItem().should.be.false describe "Safety Goggles", -> it "makes the user immune to weather", -> shared.create.call this, gen: 'xy' team1: [Factory("Magikarp", item: "Safety Goggles")] @p1.isWeatherDamageImmune(Weather.SAND).should.be.true @p1.isWeatherDamageImmune(Weather.HAIL).should.be.true it "makes the user immune to powder moves", -> shared.create.call this, gen: 'xy' team1: [Factory("Magikarp", item: "Safety Goggles")] spore = @battle.getMove("Spore") mock = @sandbox.mock(spore).expects('hit').never() @battle.performMove(@p2, spore) mock.verify()
true
{Item} = require('../../server/xy/data/items') {Pokemon} = require '../../server/xy/pokemon' {Weather} = require('../../shared/weather') {Attachment, Status} = require '../../server/xy/attachment' {Move} = require '../../server/xy/move' {Factory} = require '../factory' util = require '../../server/xy/util' should = require 'should' {_} = require 'underscore' shared = require '../shared' require '../helpers' describe "XY Items:", -> describe "Weakness Policy", -> it "raises Attack and Sp. Attack by 2 if hit by a super-effective move", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] thunderbolt = @battle.getMove("Thunderbolt") @p1.stages.should.containEql(attack: 0, specialAttack: 0) @battle.performMove(@p2, thunderbolt) @p1.stages.should.containEql(attack: 2, specialAttack: 2) it "is consumed after use", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] thunderbolt = @battle.getMove("Thunderbolt") @battle.performMove(@p2, thunderbolt) @p1.hasItem().should.be.false it "is not used if hit by a non-super-effective move", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] ember = @battle.getMove("Ember") @battle.performMove(@p2, ember) @p1.hasItem().should.be.true @p1.stages.should.containEql(attack: 0, specialAttack: 0) it "is not used if hit by a super-effective move that is non-damaging", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] thunderWave = @battle.getMove("Thunder Wave") @battle.performMove(@p2, thunderWave) @p1.hasItem().should.be.true @p1.stages.should.containEql(attack: 0, specialAttack: 0) it "not used if the wearer is behind a substitute", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Weakness Policy')] @p1.attach(Attachment.Substitute, hp: 1) thunderbolt = @battle.getMove("Thunderbolt") @battle.performMove(@p2, thunderbolt) @p1.hasItem().should.be.true @p1.stages.should.containEql(attack: 0, specialAttack: 0) describe "Assault Vest", -> it "blocks non-damaging moves", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Assault Vest')] splash = @battle.getMove("Splash") @p1.isMoveBlocked(splash).should.be.true it "doesn't block damaging moves", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'Assault Vest')] tackle = @battle.getMove("Tackle") @p1.isMoveBlocked(tackle).should.be.false it "raises special defense by 1.5", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp')] spDef = @p1.stat('specialDefense') @p1.setItem(Item.AssaultVest) @p1.stat('specialDefense').should.equal Math.floor(spDef * 1.5) describe "Gems", -> it "now only boosts their respective type by x1.3", -> shared.create.call(this, gen: 'xy') move = @battle.getMove('Acrobatics') modifier = Item.FlyingGem::modifyBasePower(move, @p1, @p2) modifier.should.equal 0x14CD describe "PI:NAME:<NAME>END_PI", -> it "raises defense if hit by a physical attack", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'PI:NAME:<NAME>END_PI')] @p1.stages.should.containEql(defense: 0) @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.stages.should.containEql(defense: 1) it "is consumed after use", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'PI:NAME:<NAME>END_PI')] @p1.hasItem().should.be.true @battle.performMove(@p2, @battle.getMove("Tackle")) @p1.hasItem().should.be.false describe "PI:NAME:<NAME>END_PI", -> it "raises defense if hit by a special attack", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'PI:NAME:<NAME>END_PI')] @p1.stages.should.containEql(specialDefense: 0) @battle.performMove(@p2, @battle.getMove("Ember")) @p1.stages.should.containEql(specialDefense: 1) it "is consumed after use", -> shared.create.call this, gen: 'xy' team1: [Factory('Magikarp', item: 'PI:NAME:<NAME>END_PI')] @p1.hasItem().should.be.true @battle.performMove(@p2, @battle.getMove("Ember")) @p1.hasItem().should.be.false describe "Safety Goggles", -> it "makes the user immune to weather", -> shared.create.call this, gen: 'xy' team1: [Factory("Magikarp", item: "Safety Goggles")] @p1.isWeatherDamageImmune(Weather.SAND).should.be.true @p1.isWeatherDamageImmune(Weather.HAIL).should.be.true it "makes the user immune to powder moves", -> shared.create.call this, gen: 'xy' team1: [Factory("Magikarp", item: "Safety Goggles")] spore = @battle.getMove("Spore") mock = @sandbox.mock(spore).expects('hit').never() @battle.performMove(@p2, spore) mock.verify()
[ { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri", "end": 42, "score": 0.9998378753662109, "start": 24, "tag": "NAME", "value": "Alexander Cherniuk" }, { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmai...
library/semantic/dialogue.coffee
ts33kr/granite
6
### Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" teacup = require "teacup" assert = require "assert" {Widget} = require "./abstract" {Coloring} = require "./coloring" {Archetype} = require "../nucleus/arche" {remote, cc} = require "../membrane/remote" # This frontend widget implements a simple dialogue, rendered as a # modal window. The HTML markup (and therefore the exterior looks) # is driven by the Semantic-UI framework. The widget provides not # just the markup skeleton, but also some cultivation of dialogue # with the necessary events being emited and the required routine # for the usage and configuration being provided out-of-the-box. # Needs to be reconfigured with the service to satisfy the deps. module.exports.Dialogue = cc -> class Dialogue extends Widget # Bring the tags definitions of the `Teacup` template engine # to the current class scope on the client and server sites. # Remember, that the `teacup` symbol is constantly available # on both sites, respecitvely. Also, take into consideration # that when you need a client-site template in the service, # this is all done automatically and there if no need for it. # Please see the `TemplateToolkit` class for more information. {div} = teacup # These declarations below are implantations of the abstracted # components by the means of the dynamic recomposition system. # Please take a look at the `Composition` class implementation # for all sorts of information on the composition system itself. # Each of these will be dynamicall integrated in class hierarchy. @implanting Coloring # This prototype definition is a template-function driven by # the `Teacup` templating engine. When widget instantiated, # this defintion is used to render the root DOM element of # the widget and store it in the widget instance under the # instance variable with the same name of `element`. Please # refer to the `TemplateToolkit` class for an information. # Also, please refer to the `Teacup` manual for reference. element: -> div ".ui.modal.dialogue-widget" # Create and insert a new action button. The buttin will be # placed within the actions container, where all the buttons # reside by the default. This method is a subwidget, which # means it will return a fully fledged widget object for it. # When button is pressed, a corresponding event is going to # be fired on the instance of this widget. If no event name # is explicitly given, the name of the button will be used. @subwidget actionButton: (name, icon, side, event) -> event = name unless _.isString event or null assert side = "right" unless _.isString side assert _.isString(name), "missing button name" assert _.isString(side), "missing an icon side" assert _.isString(event), "no event name given" assert action = try $ "<div>", class: "ui button" action.addClass "#{side} labeled icon action-button" assert s = (text) -> return $("<span>").text(text) assert mnemonic = $ "<i>", class: "#{icon} icon" mnemonic = undefined unless _.isString icon or 0 action.removeClass "#{side} icon" unless mnemonic assert texting = $("<span>").html s this.t name assert action.prepend(texting).append(mnemonic) stop = (e) -> try e.stopImmediatePropagation() action.click (e) -> stop e if $(@).is ".disabled" action.click (e) => stop e unless @setInOrder() action.click (e) => @emit event, action; stop e this.actions.prepend action; return action # The auto-runned method that uses algorithmic approach for # building the helpers for the dialogue. The helpers are an # HTML structure that supplements modal window with all parts # necessary to implement a dialogue. The implementation uses # the Semantic-UI modal window components to build a helpers # up. So the semantics of an HTML tree conforms entirely to. assembleHelpers: @autorun axis: +102, -> @negative = $ "<div>", class: "ui negative button" @positive = $ "<div>", class: "ui positive button" assert s = (text) -> return $("<span>").text(text) assert stop = (e) -> try e.stopImmediatePropagation() $(@negative).click (e) -> stop e if $(@).is ".disabled" $(@positive).click (e) -> stop e if $(@).is ".disabled" $(@negative).click (e) => stop e unless @setInOrder() $(@positive).click (e) => stop e unless @setInOrder() $(@negative).click (e) => @emit "negative"; stop e $(@positive).click (e) => @emit "positive"; stop e this.negative.prepend $("<span>").html s @t "dismiss" this.positive.prepend $("<span>").html s @t "confirm" this.positive.append $ "<i>", class: "checkmark icon" assert this.title = => @headers.text _.head arguments assert this.positive.addClass "right labeled icon" assert this.actions.append @negative, @positive this.emit "configure-helpers", @element; this # The auto-runned method that uses algorithmic approach for # building the skeleton of the dialogue. The skeleton is an # HTML structure that composes a modal window with all parts # necessary being already installed. The implementation uses # the Semantic-UI modal window components to build an window # up. So the semantics of an HTML tree conforms entirely to. assembleSkeleton: @autorun axis: +101, -> unConfigured = "dialogue have to be configured" assert @constructor.$reconfigured, unConfigured assert this.headers = $ "<div>", class: "header" assert this.content = $ "<div>", class: "content" assert this.actions = $ "<div>", class: "actions" assert this.closing = $ "<i>", class: "close icon" assert _.isObject cross = @closing # the shorthand this.element.prepend @actions; @emit "set-actions" this.element.prepend @closing, @headers, @content cr = (f) => if f then cross.show() else cross.hide() cs = (f) => @element.modal "setting", "closable", f cf = (o) => @emit "settings", this # emit re-config assert this.show = => return @element.modal "show" assert this.hide = => return @element.modal "hide" assert this.toggle = => @element.modal "toggle" assert this.closable = (f) => cs f; cr f; cf @ this.emit "configure-skeleton", @element; this
36021
### Copyright (c) 2013, <NAME> <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" teacup = require "teacup" assert = require "assert" {Widget} = require "./abstract" {Coloring} = require "./coloring" {Archetype} = require "../nucleus/arche" {remote, cc} = require "../membrane/remote" # This frontend widget implements a simple dialogue, rendered as a # modal window. The HTML markup (and therefore the exterior looks) # is driven by the Semantic-UI framework. The widget provides not # just the markup skeleton, but also some cultivation of dialogue # with the necessary events being emited and the required routine # for the usage and configuration being provided out-of-the-box. # Needs to be reconfigured with the service to satisfy the deps. module.exports.Dialogue = cc -> class Dialogue extends Widget # Bring the tags definitions of the `Teacup` template engine # to the current class scope on the client and server sites. # Remember, that the `teacup` symbol is constantly available # on both sites, respecitvely. Also, take into consideration # that when you need a client-site template in the service, # this is all done automatically and there if no need for it. # Please see the `TemplateToolkit` class for more information. {div} = teacup # These declarations below are implantations of the abstracted # components by the means of the dynamic recomposition system. # Please take a look at the `Composition` class implementation # for all sorts of information on the composition system itself. # Each of these will be dynamicall integrated in class hierarchy. @implanting Coloring # This prototype definition is a template-function driven by # the `Teacup` templating engine. When widget instantiated, # this defintion is used to render the root DOM element of # the widget and store it in the widget instance under the # instance variable with the same name of `element`. Please # refer to the `TemplateToolkit` class for an information. # Also, please refer to the `Teacup` manual for reference. element: -> div ".ui.modal.dialogue-widget" # Create and insert a new action button. The buttin will be # placed within the actions container, where all the buttons # reside by the default. This method is a subwidget, which # means it will return a fully fledged widget object for it. # When button is pressed, a corresponding event is going to # be fired on the instance of this widget. If no event name # is explicitly given, the name of the button will be used. @subwidget actionButton: (name, icon, side, event) -> event = name unless _.isString event or null assert side = "right" unless _.isString side assert _.isString(name), "missing button name" assert _.isString(side), "missing an icon side" assert _.isString(event), "no event name given" assert action = try $ "<div>", class: "ui button" action.addClass "#{side} labeled icon action-button" assert s = (text) -> return $("<span>").text(text) assert mnemonic = $ "<i>", class: "#{icon} icon" mnemonic = undefined unless _.isString icon or 0 action.removeClass "#{side} icon" unless mnemonic assert texting = $("<span>").html s this.t name assert action.prepend(texting).append(mnemonic) stop = (e) -> try e.stopImmediatePropagation() action.click (e) -> stop e if $(@).is ".disabled" action.click (e) => stop e unless @setInOrder() action.click (e) => @emit event, action; stop e this.actions.prepend action; return action # The auto-runned method that uses algorithmic approach for # building the helpers for the dialogue. The helpers are an # HTML structure that supplements modal window with all parts # necessary to implement a dialogue. The implementation uses # the Semantic-UI modal window components to build a helpers # up. So the semantics of an HTML tree conforms entirely to. assembleHelpers: @autorun axis: +102, -> @negative = $ "<div>", class: "ui negative button" @positive = $ "<div>", class: "ui positive button" assert s = (text) -> return $("<span>").text(text) assert stop = (e) -> try e.stopImmediatePropagation() $(@negative).click (e) -> stop e if $(@).is ".disabled" $(@positive).click (e) -> stop e if $(@).is ".disabled" $(@negative).click (e) => stop e unless @setInOrder() $(@positive).click (e) => stop e unless @setInOrder() $(@negative).click (e) => @emit "negative"; stop e $(@positive).click (e) => @emit "positive"; stop e this.negative.prepend $("<span>").html s @t "dismiss" this.positive.prepend $("<span>").html s @t "confirm" this.positive.append $ "<i>", class: "checkmark icon" assert this.title = => @headers.text _.head arguments assert this.positive.addClass "right labeled icon" assert this.actions.append @negative, @positive this.emit "configure-helpers", @element; this # The auto-runned method that uses algorithmic approach for # building the skeleton of the dialogue. The skeleton is an # HTML structure that composes a modal window with all parts # necessary being already installed. The implementation uses # the Semantic-UI modal window components to build an window # up. So the semantics of an HTML tree conforms entirely to. assembleSkeleton: @autorun axis: +101, -> unConfigured = "dialogue have to be configured" assert @constructor.$reconfigured, unConfigured assert this.headers = $ "<div>", class: "header" assert this.content = $ "<div>", class: "content" assert this.actions = $ "<div>", class: "actions" assert this.closing = $ "<i>", class: "close icon" assert _.isObject cross = @closing # the shorthand this.element.prepend @actions; @emit "set-actions" this.element.prepend @closing, @headers, @content cr = (f) => if f then cross.show() else cross.hide() cs = (f) => @element.modal "setting", "closable", f cf = (o) => @emit "settings", this # emit re-config assert this.show = => return @element.modal "show" assert this.hide = => return @element.modal "hide" assert this.toggle = => @element.modal "toggle" assert this.closable = (f) => cs f; cr f; cf @ this.emit "configure-skeleton", @element; this
true
### Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" teacup = require "teacup" assert = require "assert" {Widget} = require "./abstract" {Coloring} = require "./coloring" {Archetype} = require "../nucleus/arche" {remote, cc} = require "../membrane/remote" # This frontend widget implements a simple dialogue, rendered as a # modal window. The HTML markup (and therefore the exterior looks) # is driven by the Semantic-UI framework. The widget provides not # just the markup skeleton, but also some cultivation of dialogue # with the necessary events being emited and the required routine # for the usage and configuration being provided out-of-the-box. # Needs to be reconfigured with the service to satisfy the deps. module.exports.Dialogue = cc -> class Dialogue extends Widget # Bring the tags definitions of the `Teacup` template engine # to the current class scope on the client and server sites. # Remember, that the `teacup` symbol is constantly available # on both sites, respecitvely. Also, take into consideration # that when you need a client-site template in the service, # this is all done automatically and there if no need for it. # Please see the `TemplateToolkit` class for more information. {div} = teacup # These declarations below are implantations of the abstracted # components by the means of the dynamic recomposition system. # Please take a look at the `Composition` class implementation # for all sorts of information on the composition system itself. # Each of these will be dynamicall integrated in class hierarchy. @implanting Coloring # This prototype definition is a template-function driven by # the `Teacup` templating engine. When widget instantiated, # this defintion is used to render the root DOM element of # the widget and store it in the widget instance under the # instance variable with the same name of `element`. Please # refer to the `TemplateToolkit` class for an information. # Also, please refer to the `Teacup` manual for reference. element: -> div ".ui.modal.dialogue-widget" # Create and insert a new action button. The buttin will be # placed within the actions container, where all the buttons # reside by the default. This method is a subwidget, which # means it will return a fully fledged widget object for it. # When button is pressed, a corresponding event is going to # be fired on the instance of this widget. If no event name # is explicitly given, the name of the button will be used. @subwidget actionButton: (name, icon, side, event) -> event = name unless _.isString event or null assert side = "right" unless _.isString side assert _.isString(name), "missing button name" assert _.isString(side), "missing an icon side" assert _.isString(event), "no event name given" assert action = try $ "<div>", class: "ui button" action.addClass "#{side} labeled icon action-button" assert s = (text) -> return $("<span>").text(text) assert mnemonic = $ "<i>", class: "#{icon} icon" mnemonic = undefined unless _.isString icon or 0 action.removeClass "#{side} icon" unless mnemonic assert texting = $("<span>").html s this.t name assert action.prepend(texting).append(mnemonic) stop = (e) -> try e.stopImmediatePropagation() action.click (e) -> stop e if $(@).is ".disabled" action.click (e) => stop e unless @setInOrder() action.click (e) => @emit event, action; stop e this.actions.prepend action; return action # The auto-runned method that uses algorithmic approach for # building the helpers for the dialogue. The helpers are an # HTML structure that supplements modal window with all parts # necessary to implement a dialogue. The implementation uses # the Semantic-UI modal window components to build a helpers # up. So the semantics of an HTML tree conforms entirely to. assembleHelpers: @autorun axis: +102, -> @negative = $ "<div>", class: "ui negative button" @positive = $ "<div>", class: "ui positive button" assert s = (text) -> return $("<span>").text(text) assert stop = (e) -> try e.stopImmediatePropagation() $(@negative).click (e) -> stop e if $(@).is ".disabled" $(@positive).click (e) -> stop e if $(@).is ".disabled" $(@negative).click (e) => stop e unless @setInOrder() $(@positive).click (e) => stop e unless @setInOrder() $(@negative).click (e) => @emit "negative"; stop e $(@positive).click (e) => @emit "positive"; stop e this.negative.prepend $("<span>").html s @t "dismiss" this.positive.prepend $("<span>").html s @t "confirm" this.positive.append $ "<i>", class: "checkmark icon" assert this.title = => @headers.text _.head arguments assert this.positive.addClass "right labeled icon" assert this.actions.append @negative, @positive this.emit "configure-helpers", @element; this # The auto-runned method that uses algorithmic approach for # building the skeleton of the dialogue. The skeleton is an # HTML structure that composes a modal window with all parts # necessary being already installed. The implementation uses # the Semantic-UI modal window components to build an window # up. So the semantics of an HTML tree conforms entirely to. assembleSkeleton: @autorun axis: +101, -> unConfigured = "dialogue have to be configured" assert @constructor.$reconfigured, unConfigured assert this.headers = $ "<div>", class: "header" assert this.content = $ "<div>", class: "content" assert this.actions = $ "<div>", class: "actions" assert this.closing = $ "<i>", class: "close icon" assert _.isObject cross = @closing # the shorthand this.element.prepend @actions; @emit "set-actions" this.element.prepend @closing, @headers, @content cr = (f) => if f then cross.show() else cross.hide() cs = (f) => @element.modal "setting", "closable", f cf = (o) => @emit "settings", this # emit re-config assert this.show = => return @element.modal "show" assert this.hide = => return @element.modal "hide" assert this.toggle = => @element.modal "toggle" assert this.closable = (f) => cs f; cr f; cf @ this.emit "configure-skeleton", @element; this
[ { "context": "export default\n name: 'Sedna'\n type: 'dwarfPlanet'\n radius: 497.5\n elements", "end": 29, "score": 0.9997825622558594, "start": 24, "tag": "NAME", "value": "Sedna" } ]
src/data/bodies/sedna.coffee
skepticalimagination/solaris-model
5
export default name: 'Sedna' type: 'dwarfPlanet' radius: 497.5 elements: format: 'jpl-sbdb' base: {a: 493.1571900553549, e: 0.8458267179852279, i: 11.92883369990435, L: 814.12651433, lp: 456.0846992128, node: 144.4983343551347} day: {M: 8.999658288375152e-5}
177904
export default name: '<NAME>' type: 'dwarfPlanet' radius: 497.5 elements: format: 'jpl-sbdb' base: {a: 493.1571900553549, e: 0.8458267179852279, i: 11.92883369990435, L: 814.12651433, lp: 456.0846992128, node: 144.4983343551347} day: {M: 8.999658288375152e-5}
true
export default name: 'PI:NAME:<NAME>END_PI' type: 'dwarfPlanet' radius: 497.5 elements: format: 'jpl-sbdb' base: {a: 493.1571900553549, e: 0.8458267179852279, i: 11.92883369990435, L: 814.12651433, lp: 456.0846992128, node: 144.4983343551347} day: {M: 8.999658288375152e-5}
[ { "context": "./../src/coffee/linq'\n\ndata = [\n { id: 1, name: 'one', category: 'fruits', countries: ['lxsbw', 'xliec", "end": 70, "score": 0.8422536253929138, "start": 67, "tag": "NAME", "value": "one" }, { "context": "ntries: ['Italy', 'Austria'] },\n { id: 2, name: 'two', cate...
test/coffee/groupby.coffee
Lxsbw/linqjs
0
Linq = require '../../src/coffee/linq' data = [ { id: 1, name: 'one', category: 'fruits', countries: ['lxsbw', 'xliecz'] }, { id: 1, name: 'one', category: 'fruits', countries: ['Italy', 'Austria'] }, { id: 2, name: 'two', category: 'vegetables', countries: ['Italy', 'Germany'] }, # { id: 3, name: 'three', category: 'vegetables', countries: ['Germany'] }, # { id: 4, name: 'four', category: 'fruits', countries: ['Japan'] }, # { id: 5, name: 'five', category: 'fruits', countries: ['Japan', 'Italy'] }, ] # 分组 # console.log 'this:', new Linq(data) result = new Linq(data).GroupBy((el) -> el.category) # result = new Linq(data).GroupBy((el) -> el.id) # result = new Linq(data).GroupBy((el) -> { id: el.id, category: el.category }) # 去重 # result = new Linq(data).DistinctBy((x) -> x.category).toArray() # result = new Linq(data).DistinctBy((el) -> { id: el.id, category: el.category }).toArray() console.log 'result:', result
36299
Linq = require '../../src/coffee/linq' data = [ { id: 1, name: '<NAME>', category: 'fruits', countries: ['lxsbw', 'xliecz'] }, { id: 1, name: 'one', category: 'fruits', countries: ['Italy', 'Austria'] }, { id: 2, name: '<NAME>', category: 'vegetables', countries: ['Italy', 'Germany'] }, # { id: 3, name: 'three', category: 'vegetables', countries: ['Germany'] }, # { id: 4, name: '<NAME>', category: 'fruits', countries: ['Japan'] }, # { id: 5, name: '<NAME>', category: 'fruits', countries: ['Japan', 'Italy'] }, ] # 分组 # console.log 'this:', new Linq(data) result = new Linq(data).GroupBy((el) -> el.category) # result = new Linq(data).GroupBy((el) -> el.id) # result = new Linq(data).GroupBy((el) -> { id: el.id, category: el.category }) # 去重 # result = new Linq(data).DistinctBy((x) -> x.category).toArray() # result = new Linq(data).DistinctBy((el) -> { id: el.id, category: el.category }).toArray() console.log 'result:', result
true
Linq = require '../../src/coffee/linq' data = [ { id: 1, name: 'PI:NAME:<NAME>END_PI', category: 'fruits', countries: ['lxsbw', 'xliecz'] }, { id: 1, name: 'one', category: 'fruits', countries: ['Italy', 'Austria'] }, { id: 2, name: 'PI:NAME:<NAME>END_PI', category: 'vegetables', countries: ['Italy', 'Germany'] }, # { id: 3, name: 'three', category: 'vegetables', countries: ['Germany'] }, # { id: 4, name: 'PI:NAME:<NAME>END_PI', category: 'fruits', countries: ['Japan'] }, # { id: 5, name: 'PI:NAME:<NAME>END_PI', category: 'fruits', countries: ['Japan', 'Italy'] }, ] # 分组 # console.log 'this:', new Linq(data) result = new Linq(data).GroupBy((el) -> el.category) # result = new Linq(data).GroupBy((el) -> el.id) # result = new Linq(data).GroupBy((el) -> { id: el.id, category: el.category }) # 去重 # result = new Linq(data).DistinctBy((x) -> x.category).toArray() # result = new Linq(data).DistinctBy((el) -> { id: el.id, category: el.category }).toArray() console.log 'result:', result
[ { "context": "eneca'\ncredentials = \"#{process.env.PH_RABBIT_USER}:#{process.env.PH_RABBIT_PASS}\"\noptions =\n intern", "end": 69, "score": 0.5885485410690308, "start": 69, "tag": "KEY", "value": "" } ]
src/seneca/instance.coffee
PinkHippos/ph-todo-db
1
seneca = require 'seneca' credentials = "#{process.env.PH_RABBIT_USER}:#{process.env.PH_RABBIT_PASS}" options = internal: logger: require 'seneca-legacy-logger' tag: 'db' log: level: 'error' debug: short_logs: true seneca = seneca options .use 'seneca-amqp-transport', { amqp: url: "amqp://#{credentials}@rabbitmq:5672" } module.exports = seneca
101466
seneca = require 'seneca' credentials = "#{process.env.PH_RABBIT_USER<KEY>}:#{process.env.PH_RABBIT_PASS}" options = internal: logger: require 'seneca-legacy-logger' tag: 'db' log: level: 'error' debug: short_logs: true seneca = seneca options .use 'seneca-amqp-transport', { amqp: url: "amqp://#{credentials}@rabbitmq:5672" } module.exports = seneca
true
seneca = require 'seneca' credentials = "#{process.env.PH_RABBIT_USERPI:KEY:<KEY>END_PI}:#{process.env.PH_RABBIT_PASS}" options = internal: logger: require 'seneca-legacy-logger' tag: 'db' log: level: 'error' debug: short_logs: true seneca = seneca options .use 'seneca-amqp-transport', { amqp: url: "amqp://#{credentials}@rabbitmq:5672" } module.exports = seneca
[ { "context": " @owner = owner\n @name = key = name\n \n if typeof options == 'string'\n opti", "end": 2288, "score": 0.8663350939750671, "start": 2284, "tag": "NAME", "value": "name" } ]
src/tower/model/attribute.coffee
vjsingh/tower
1
class Tower.Model.Attribute @string: from: (serialized) -> if Tower.none(serialized) then null else String(serialized) to: (deserialized) -> if Tower.none(deserialized) then null else String(deserialized) @number: from: (serialized) -> if Tower.none(serialized) then null else Number(serialized) to: (deserialized) -> if Tower.none(deserialized) then null else Number(deserialized) @integer: from: (serialized) -> if Tower.none(serialized) then null else parseInt(serialized) to: (deserialized) -> if Tower.none(deserialized) then null else parseInt(deserialized) @float: from: (serialized) -> parseFloat(serialized) to: (deserialized) -> deserialized @decimal: @float @boolean: from: (serialized) -> if typeof serialized == "string" !!(serialized != "false") else Boolean(serialized) to: (deserialized) -> Tower.Model.Attribute.boolean.from(deserialized) @date: # from ember.js, tmp from: (date) -> date to: (date) -> date @time: @date @datetime: @date @geo: from: (serialized) -> serialized to: (deserialized) -> switch _.kind(deserialized) when "array" lat: deserialized[0], lng: deserialized[1] when "object" lat: deserialized.lat || deserialized.latitude lng: deserialized.lng || deserialized.longitude else deserialized = deserialized.split(/,\ */) lat: parseFloat(deserialized[0]), lng: parseFloat(deserialized[1]) @array: from: (serialized) -> if Tower.none(serialized) then null else _.castArray(serialized) to: (deserialized) -> Tower.Model.Attribute.array.from(deserialized) # @option options [Boolean|String|Function] set If `set` is a boolean, it will look for a method # named `"set#{field.name}"` on the prototype. If it's a string, it will call that method on the prototype. # If it's a function, it will call that function as if it were on the prototype. constructor: (owner, name, options = {}, block) -> @owner = owner @name = key = name if typeof options == 'string' options = type: options else if typeof options == 'function' block = options options = {} @type = options.type || "String" if typeof @type != "string" @itemType = @type[0] @type = "Array" @encodingType = switch @type when "Id", "Date", "Array", "String", "Integer", "Float", "BigDecimal", "Time", "DateTime", "Boolean", "Object", "Number", "Geo" @type else "Model" serializer = Tower.Model.Attribute[Tower.Support.String.camelize(@type, true)] @_default = options.default unless @_default if @type == "Geo" @_default = lat: null, lng: null else if @type == 'Array' @_default = [] if @type == 'Geo' && !options.index index = {} index[name] = "2d" options.index = index @get = options.get || (serializer.from if serializer) @set = options.set || (serializer.to if serializer) @get = "get#{Tower.Support.String.camelize(name)}" if @get == true @set = "set#{Tower.Support.String.camelize(name)}" if @set == true if Tower.accessors Object.defineProperty @owner.prototype, name, enumerable: true configurable: true get: -> @get(key) set: (value) -> @set(key, value) validations = {} for key, normalizedKey of Tower.Model.Validator.keys validations[normalizedKey] = options[key] if options.hasOwnProperty(key) @owner.validates name, validations if _.isPresent(validations) if options.index if options.index == true @owner.index(name) else @owner.index(options.index) validators: -> result = [] for validator in @owner.validators() result.push(validator) if validator.attributes.indexOf(@name) != -1 result defaultValue: (record) -> _default = @_default if _.isArray(_default) _default.concat() else if _.isHash(_default) _.extend({}, _default) else if typeof(_default) == "function" _default.call(record) else _default encode: (value, binding) -> @code @set, value, binding decode: (value, binding) -> @code @get, value, binding code: (type, value, binding) -> switch typeof type when "string" binding[type].call binding[type], value when "function" type.call binding, value else value module.exports = Tower.Model.Attribute
167420
class Tower.Model.Attribute @string: from: (serialized) -> if Tower.none(serialized) then null else String(serialized) to: (deserialized) -> if Tower.none(deserialized) then null else String(deserialized) @number: from: (serialized) -> if Tower.none(serialized) then null else Number(serialized) to: (deserialized) -> if Tower.none(deserialized) then null else Number(deserialized) @integer: from: (serialized) -> if Tower.none(serialized) then null else parseInt(serialized) to: (deserialized) -> if Tower.none(deserialized) then null else parseInt(deserialized) @float: from: (serialized) -> parseFloat(serialized) to: (deserialized) -> deserialized @decimal: @float @boolean: from: (serialized) -> if typeof serialized == "string" !!(serialized != "false") else Boolean(serialized) to: (deserialized) -> Tower.Model.Attribute.boolean.from(deserialized) @date: # from ember.js, tmp from: (date) -> date to: (date) -> date @time: @date @datetime: @date @geo: from: (serialized) -> serialized to: (deserialized) -> switch _.kind(deserialized) when "array" lat: deserialized[0], lng: deserialized[1] when "object" lat: deserialized.lat || deserialized.latitude lng: deserialized.lng || deserialized.longitude else deserialized = deserialized.split(/,\ */) lat: parseFloat(deserialized[0]), lng: parseFloat(deserialized[1]) @array: from: (serialized) -> if Tower.none(serialized) then null else _.castArray(serialized) to: (deserialized) -> Tower.Model.Attribute.array.from(deserialized) # @option options [Boolean|String|Function] set If `set` is a boolean, it will look for a method # named `"set#{field.name}"` on the prototype. If it's a string, it will call that method on the prototype. # If it's a function, it will call that function as if it were on the prototype. constructor: (owner, name, options = {}, block) -> @owner = owner @name = key = <NAME> if typeof options == 'string' options = type: options else if typeof options == 'function' block = options options = {} @type = options.type || "String" if typeof @type != "string" @itemType = @type[0] @type = "Array" @encodingType = switch @type when "Id", "Date", "Array", "String", "Integer", "Float", "BigDecimal", "Time", "DateTime", "Boolean", "Object", "Number", "Geo" @type else "Model" serializer = Tower.Model.Attribute[Tower.Support.String.camelize(@type, true)] @_default = options.default unless @_default if @type == "Geo" @_default = lat: null, lng: null else if @type == 'Array' @_default = [] if @type == 'Geo' && !options.index index = {} index[name] = "2d" options.index = index @get = options.get || (serializer.from if serializer) @set = options.set || (serializer.to if serializer) @get = "get#{Tower.Support.String.camelize(name)}" if @get == true @set = "set#{Tower.Support.String.camelize(name)}" if @set == true if Tower.accessors Object.defineProperty @owner.prototype, name, enumerable: true configurable: true get: -> @get(key) set: (value) -> @set(key, value) validations = {} for key, normalizedKey of Tower.Model.Validator.keys validations[normalizedKey] = options[key] if options.hasOwnProperty(key) @owner.validates name, validations if _.isPresent(validations) if options.index if options.index == true @owner.index(name) else @owner.index(options.index) validators: -> result = [] for validator in @owner.validators() result.push(validator) if validator.attributes.indexOf(@name) != -1 result defaultValue: (record) -> _default = @_default if _.isArray(_default) _default.concat() else if _.isHash(_default) _.extend({}, _default) else if typeof(_default) == "function" _default.call(record) else _default encode: (value, binding) -> @code @set, value, binding decode: (value, binding) -> @code @get, value, binding code: (type, value, binding) -> switch typeof type when "string" binding[type].call binding[type], value when "function" type.call binding, value else value module.exports = Tower.Model.Attribute
true
class Tower.Model.Attribute @string: from: (serialized) -> if Tower.none(serialized) then null else String(serialized) to: (deserialized) -> if Tower.none(deserialized) then null else String(deserialized) @number: from: (serialized) -> if Tower.none(serialized) then null else Number(serialized) to: (deserialized) -> if Tower.none(deserialized) then null else Number(deserialized) @integer: from: (serialized) -> if Tower.none(serialized) then null else parseInt(serialized) to: (deserialized) -> if Tower.none(deserialized) then null else parseInt(deserialized) @float: from: (serialized) -> parseFloat(serialized) to: (deserialized) -> deserialized @decimal: @float @boolean: from: (serialized) -> if typeof serialized == "string" !!(serialized != "false") else Boolean(serialized) to: (deserialized) -> Tower.Model.Attribute.boolean.from(deserialized) @date: # from ember.js, tmp from: (date) -> date to: (date) -> date @time: @date @datetime: @date @geo: from: (serialized) -> serialized to: (deserialized) -> switch _.kind(deserialized) when "array" lat: deserialized[0], lng: deserialized[1] when "object" lat: deserialized.lat || deserialized.latitude lng: deserialized.lng || deserialized.longitude else deserialized = deserialized.split(/,\ */) lat: parseFloat(deserialized[0]), lng: parseFloat(deserialized[1]) @array: from: (serialized) -> if Tower.none(serialized) then null else _.castArray(serialized) to: (deserialized) -> Tower.Model.Attribute.array.from(deserialized) # @option options [Boolean|String|Function] set If `set` is a boolean, it will look for a method # named `"set#{field.name}"` on the prototype. If it's a string, it will call that method on the prototype. # If it's a function, it will call that function as if it were on the prototype. constructor: (owner, name, options = {}, block) -> @owner = owner @name = key = PI:NAME:<NAME>END_PI if typeof options == 'string' options = type: options else if typeof options == 'function' block = options options = {} @type = options.type || "String" if typeof @type != "string" @itemType = @type[0] @type = "Array" @encodingType = switch @type when "Id", "Date", "Array", "String", "Integer", "Float", "BigDecimal", "Time", "DateTime", "Boolean", "Object", "Number", "Geo" @type else "Model" serializer = Tower.Model.Attribute[Tower.Support.String.camelize(@type, true)] @_default = options.default unless @_default if @type == "Geo" @_default = lat: null, lng: null else if @type == 'Array' @_default = [] if @type == 'Geo' && !options.index index = {} index[name] = "2d" options.index = index @get = options.get || (serializer.from if serializer) @set = options.set || (serializer.to if serializer) @get = "get#{Tower.Support.String.camelize(name)}" if @get == true @set = "set#{Tower.Support.String.camelize(name)}" if @set == true if Tower.accessors Object.defineProperty @owner.prototype, name, enumerable: true configurable: true get: -> @get(key) set: (value) -> @set(key, value) validations = {} for key, normalizedKey of Tower.Model.Validator.keys validations[normalizedKey] = options[key] if options.hasOwnProperty(key) @owner.validates name, validations if _.isPresent(validations) if options.index if options.index == true @owner.index(name) else @owner.index(options.index) validators: -> result = [] for validator in @owner.validators() result.push(validator) if validator.attributes.indexOf(@name) != -1 result defaultValue: (record) -> _default = @_default if _.isArray(_default) _default.concat() else if _.isHash(_default) _.extend({}, _default) else if typeof(_default) == "function" _default.call(record) else _default encode: (value, binding) -> @code @set, value, binding decode: (value, binding) -> @code @get, value, binding code: (type, value, binding) -> switch typeof type when "string" binding[type].call binding[type], value when "function" type.call binding, value else value module.exports = Tower.Model.Attribute
[ { "context": "merModal()\n\t\t.fillForm('#add-customer',\n\t\t\tname: 'TEST',\n\t\t\temail: 'nick@example.com',\n\t\t\taddress_line1:", "end": 914, "score": 0.9994764924049377, "start": 910, "tag": "NAME", "value": "TEST" }, { "context": "Form('#add-customer',\n\t\t\tname: 'TEST',\n\...
tests/integration/add-customer-test.coffee
dk-dev/balanced-dashboard
169
`import startApp from '../helpers/start-app';` `import Testing from "../helpers/testing";` `import checkElements from "../helpers/check-elements";` `import helpers from "../helpers/helpers";` `import Customer from "balanced-dashboard/models/customer";` App = undefined Adapter = undefined visitAddACustomerModal = -> route = Testing.MARKETPLACE_ROUTE + "/customers" selector = ".page-navigation a:contains(Add a customer)" visit(route).click(selector) module 'Integration - AddCustomer', setup: -> App = startApp() Adapter = App.__container__.lookup("adapter:main") Testing.setupMarketplace() teardown: -> Testing.restoreMethods(jQuery.ajax) Ember.run(App, 'destroy') test 'can visit page', -> visitAddACustomerModal() .checkText("#add-customer h2", "Add a customer") test 'can create person customer', -> $spy = null visitAddACustomerModal() .fillForm('#add-customer', name: 'TEST', email: 'nick@example.com', address_line1: '1234 main street', address_line2: 'Ste 400', address_city: 'oakland', address_state: 'ca', address_postal_code: '94612', phone: '1231231234', dob_month: '12', dob_year: '1930', ssn_last4: '1234', meta_facebook: 'kleinsch', meta_twitter: 'kleinsch', country_code: "US" ) .then -> $spy = sinon.spy(jQuery, "ajax") .click('button[name=modal-submit]') .then -> args = $spy.firstCall.args data = JSON.parse(args[1].data) deepEqual(args[0], "https://api.balancedpayments.com/customers") matchesProperties(data.address, city: "oakland" country_code: "US" line1: "1234 main street" line2: "Ste 400" postal_code: "94612" state: "ca" ) matchesProperties(data.meta, facebook: "kleinsch" twitter: "kleinsch" ) matchesProperties(data, dob_month: "12" dob_year: "1930" email: "nick@example.com" name: 'TEST' phone: "1231231234" ssn_last4: "1234" ) test 'can create business customer', -> $spy = null visitAddACustomerModal() .fillForm('#add-customer', business_name: 'Something Inc' ein: '123123123' name: 'TEST' email: 'nick@example.com' address_line1: '1234 main street' address_line2: 'Ste 200' address_city: 'oakland' address_state: 'ca' address_postal_code: '94612' phone: '1231231234' dob_month: '12' dob_year: '1930' ssn_last4: '1234' meta_facebook: 'kleinsch' meta_twitter: 'kleinsch' country_code: "US" ) .then -> $spy = sinon.spy(jQuery, "ajax") .click('button[name=modal-submit]') .then -> args = $spy.firstCall.args data = JSON.parse(args[1].data) deepEqual(args[0], "https://api.balancedpayments.com/customers") matchesProperties(data, name: "TEST" business_name: "Something Inc" dob_month: "12" dob_year: "1930" ein: "123123123" email: "nick@example.com" ssn_last4: "1234" phone: "1231231234" ) matchesProperties(data.meta, facebook: "kleinsch" twitter: "kleinsch" ) matchesProperties(data.address, city: "oakland" line1: "1234 main street" line2: "Ste 200" postal_code: "94612" state: "ca" )
155504
`import startApp from '../helpers/start-app';` `import Testing from "../helpers/testing";` `import checkElements from "../helpers/check-elements";` `import helpers from "../helpers/helpers";` `import Customer from "balanced-dashboard/models/customer";` App = undefined Adapter = undefined visitAddACustomerModal = -> route = Testing.MARKETPLACE_ROUTE + "/customers" selector = ".page-navigation a:contains(Add a customer)" visit(route).click(selector) module 'Integration - AddCustomer', setup: -> App = startApp() Adapter = App.__container__.lookup("adapter:main") Testing.setupMarketplace() teardown: -> Testing.restoreMethods(jQuery.ajax) Ember.run(App, 'destroy') test 'can visit page', -> visitAddACustomerModal() .checkText("#add-customer h2", "Add a customer") test 'can create person customer', -> $spy = null visitAddACustomerModal() .fillForm('#add-customer', name: '<NAME>', email: '<EMAIL>', address_line1: '1234 main street', address_line2: 'Ste 400', address_city: 'oakland', address_state: 'ca', address_postal_code: '94612', phone: '1231231234', dob_month: '12', dob_year: '1930', ssn_last4: '1234', meta_facebook: 'kleinsch', meta_twitter: 'kleinsch', country_code: "US" ) .then -> $spy = sinon.spy(jQuery, "ajax") .click('button[name=modal-submit]') .then -> args = $spy.firstCall.args data = JSON.parse(args[1].data) deepEqual(args[0], "https://api.balancedpayments.<EMAIL>/customers") matchesProperties(data.address, city: "oakland" country_code: "US" line1: "1234 main street" line2: "Ste 400" postal_code: "94612" state: "ca" ) matchesProperties(data.meta, facebook: "kleinsch" twitter: "kleinsch" ) matchesProperties(data, dob_month: "12" dob_year: "1930" email: "<EMAIL>" name: '<NAME>' phone: "1231231234" ssn_last4: "1234" ) test 'can create business customer', -> $spy = null visitAddACustomerModal() .fillForm('#add-customer', business_name: 'Something Inc' ein: '123123123' name: '<NAME>' email: '<EMAIL>' address_line1: '1234 main street' address_line2: 'Ste 200' address_city: 'oakland' address_state: 'ca' address_postal_code: '94612' phone: '1231231234' dob_month: '12' dob_year: '1930' ssn_last4: '1234' meta_facebook: 'kleinsch' meta_twitter: 'kleinsch' country_code: "US" ) .then -> $spy = sinon.spy(jQuery, "ajax") .click('button[name=modal-submit]') .then -> args = $spy.firstCall.args data = JSON.parse(args[1].data) deepEqual(args[0], "https://api.balancedpayments.com/customers") matchesProperties(data, name: "TEST" business_name: "<NAME>" dob_month: "12" dob_year: "1930" ein: "123123123" email: "<EMAIL>" ssn_last4: "1234" phone: "1231231234" ) matchesProperties(data.meta, facebook: "kleinsch" twitter: "kleinsch" ) matchesProperties(data.address, city: "oakland" line1: "1234 main street" line2: "Ste 200" postal_code: "94612" state: "ca" )
true
`import startApp from '../helpers/start-app';` `import Testing from "../helpers/testing";` `import checkElements from "../helpers/check-elements";` `import helpers from "../helpers/helpers";` `import Customer from "balanced-dashboard/models/customer";` App = undefined Adapter = undefined visitAddACustomerModal = -> route = Testing.MARKETPLACE_ROUTE + "/customers" selector = ".page-navigation a:contains(Add a customer)" visit(route).click(selector) module 'Integration - AddCustomer', setup: -> App = startApp() Adapter = App.__container__.lookup("adapter:main") Testing.setupMarketplace() teardown: -> Testing.restoreMethods(jQuery.ajax) Ember.run(App, 'destroy') test 'can visit page', -> visitAddACustomerModal() .checkText("#add-customer h2", "Add a customer") test 'can create person customer', -> $spy = null visitAddACustomerModal() .fillForm('#add-customer', name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI', address_line1: '1234 main street', address_line2: 'Ste 400', address_city: 'oakland', address_state: 'ca', address_postal_code: '94612', phone: '1231231234', dob_month: '12', dob_year: '1930', ssn_last4: '1234', meta_facebook: 'kleinsch', meta_twitter: 'kleinsch', country_code: "US" ) .then -> $spy = sinon.spy(jQuery, "ajax") .click('button[name=modal-submit]') .then -> args = $spy.firstCall.args data = JSON.parse(args[1].data) deepEqual(args[0], "https://api.balancedpayments.PI:EMAIL:<EMAIL>END_PI/customers") matchesProperties(data.address, city: "oakland" country_code: "US" line1: "1234 main street" line2: "Ste 400" postal_code: "94612" state: "ca" ) matchesProperties(data.meta, facebook: "kleinsch" twitter: "kleinsch" ) matchesProperties(data, dob_month: "12" dob_year: "1930" email: "PI:EMAIL:<EMAIL>END_PI" name: 'PI:NAME:<NAME>END_PI' phone: "1231231234" ssn_last4: "1234" ) test 'can create business customer', -> $spy = null visitAddACustomerModal() .fillForm('#add-customer', business_name: 'Something Inc' ein: '123123123' name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' address_line1: '1234 main street' address_line2: 'Ste 200' address_city: 'oakland' address_state: 'ca' address_postal_code: '94612' phone: '1231231234' dob_month: '12' dob_year: '1930' ssn_last4: '1234' meta_facebook: 'kleinsch' meta_twitter: 'kleinsch' country_code: "US" ) .then -> $spy = sinon.spy(jQuery, "ajax") .click('button[name=modal-submit]') .then -> args = $spy.firstCall.args data = JSON.parse(args[1].data) deepEqual(args[0], "https://api.balancedpayments.com/customers") matchesProperties(data, name: "TEST" business_name: "PI:NAME:<NAME>END_PI" dob_month: "12" dob_year: "1930" ein: "123123123" email: "PI:EMAIL:<EMAIL>END_PI" ssn_last4: "1234" phone: "1231231234" ) matchesProperties(data.meta, facebook: "kleinsch" twitter: "kleinsch" ) matchesProperties(data.address, city: "oakland" line1: "1234 main street" line2: "Ste 200" postal_code: "94612" state: "ca" )
[ { "context": " 'sd', { USER: { type: 'Admin', id: '123', name: 'Kana'} }\n sinon.stub @AutocompleteChannels.pro", "end": 850, "score": 0.7591054439544678, "start": 849, "tag": "NAME", "value": "K" }, { "context": "hannels\n view.user.get('name').should.equal 'Kana'\n\n x...
src/client/components/autocomplete_channels/test/index.test.coffee
artsyjian/positron
76
Backbone = require 'backbone' benv = require 'benv' sinon = require 'sinon' { resolve } = require 'path' { fabricate } = require '@artsy/antigravity' User = require '../../../models/user.coffee' describe 'AutocompleteChannels', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' Bloodhound: (Bloodhound = sinon.stub()).returns( initialize: -> ttAdapter: -> ) window.jQuery = $ require 'typeahead.js' Backbone.$ = $ Bloodhound.tokenizers = { obj: { whitespace: sinon.stub() } } sinon.stub Backbone, 'sync' @AutocompleteChannels = benv.require resolve __dirname, '../index' @AutocompleteChannels.__set__ 'Modal', sinon.stub().returns {m: ''} @AutocompleteChannels.__set__ 'sd', { USER: { type: 'Admin', id: '123', name: 'Kana'} } sinon.stub @AutocompleteChannels.prototype, 'setupTypeahead' sinon.stub(User.prototype, 'fetchPartners').yields [fabricate 'partner'] done() afterEach (done) -> Backbone.sync.restore() @AutocompleteChannels.prototype.setupTypeahead.restore() User.prototype.fetchPartners.restore() benv.teardown() done() describe '#initialize', -> it 'sets the user', -> view = new @AutocompleteChannels view.user.get('name').should.equal 'Kana' xit 'sets Bloodhound args for channel source', -> view = new @AutocompleteChannels view.channels.remote.url.should.containEql '/channels?user_id=123' xit 'sets Bloodhound args for partner source as an Admin', -> view = new @AutocompleteChannels view.adminPartners.remote.url.should.containEql '/api/v1/match/partners?term=%QUERY' xit 'sets Bloodhound args for partner source as a partner', -> @AutocompleteChannels.__set__ 'sd', { USER: { type: 'User', id: '123', name: 'Kana'} } view = new @AutocompleteChannels view.partners.local.length.should.equal 1 view.partners.local[0].value.should.equal 'Gagosian Gallery'
200413
Backbone = require 'backbone' benv = require 'benv' sinon = require 'sinon' { resolve } = require 'path' { fabricate } = require '@artsy/antigravity' User = require '../../../models/user.coffee' describe 'AutocompleteChannels', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' Bloodhound: (Bloodhound = sinon.stub()).returns( initialize: -> ttAdapter: -> ) window.jQuery = $ require 'typeahead.js' Backbone.$ = $ Bloodhound.tokenizers = { obj: { whitespace: sinon.stub() } } sinon.stub Backbone, 'sync' @AutocompleteChannels = benv.require resolve __dirname, '../index' @AutocompleteChannels.__set__ 'Modal', sinon.stub().returns {m: ''} @AutocompleteChannels.__set__ 'sd', { USER: { type: 'Admin', id: '123', name: '<NAME>ana'} } sinon.stub @AutocompleteChannels.prototype, 'setupTypeahead' sinon.stub(User.prototype, 'fetchPartners').yields [fabricate 'partner'] done() afterEach (done) -> Backbone.sync.restore() @AutocompleteChannels.prototype.setupTypeahead.restore() User.prototype.fetchPartners.restore() benv.teardown() done() describe '#initialize', -> it 'sets the user', -> view = new @AutocompleteChannels view.user.get('name').should.equal '<NAME>' xit 'sets Bloodhound args for channel source', -> view = new @AutocompleteChannels view.channels.remote.url.should.containEql '/channels?user_id=123' xit 'sets Bloodhound args for partner source as an Admin', -> view = new @AutocompleteChannels view.adminPartners.remote.url.should.containEql '/api/v1/match/partners?term=%QUERY' xit 'sets Bloodhound args for partner source as a partner', -> @AutocompleteChannels.__set__ 'sd', { USER: { type: 'User', id: '123', name: '<NAME>ana'} } view = new @AutocompleteChannels view.partners.local.length.should.equal 1 view.partners.local[0].value.should.equal 'Gagosian Gallery'
true
Backbone = require 'backbone' benv = require 'benv' sinon = require 'sinon' { resolve } = require 'path' { fabricate } = require '@artsy/antigravity' User = require '../../../models/user.coffee' describe 'AutocompleteChannels', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' Bloodhound: (Bloodhound = sinon.stub()).returns( initialize: -> ttAdapter: -> ) window.jQuery = $ require 'typeahead.js' Backbone.$ = $ Bloodhound.tokenizers = { obj: { whitespace: sinon.stub() } } sinon.stub Backbone, 'sync' @AutocompleteChannels = benv.require resolve __dirname, '../index' @AutocompleteChannels.__set__ 'Modal', sinon.stub().returns {m: ''} @AutocompleteChannels.__set__ 'sd', { USER: { type: 'Admin', id: '123', name: 'PI:NAME:<NAME>END_PIana'} } sinon.stub @AutocompleteChannels.prototype, 'setupTypeahead' sinon.stub(User.prototype, 'fetchPartners').yields [fabricate 'partner'] done() afterEach (done) -> Backbone.sync.restore() @AutocompleteChannels.prototype.setupTypeahead.restore() User.prototype.fetchPartners.restore() benv.teardown() done() describe '#initialize', -> it 'sets the user', -> view = new @AutocompleteChannels view.user.get('name').should.equal 'PI:NAME:<NAME>END_PI' xit 'sets Bloodhound args for channel source', -> view = new @AutocompleteChannels view.channels.remote.url.should.containEql '/channels?user_id=123' xit 'sets Bloodhound args for partner source as an Admin', -> view = new @AutocompleteChannels view.adminPartners.remote.url.should.containEql '/api/v1/match/partners?term=%QUERY' xit 'sets Bloodhound args for partner source as a partner', -> @AutocompleteChannels.__set__ 'sd', { USER: { type: 'User', id: '123', name: 'PI:NAME:<NAME>END_PIana'} } view = new @AutocompleteChannels view.partners.local.length.should.equal 1 view.partners.local[0].value.should.equal 'Gagosian Gallery'
[ { "context": "ouch:1234'\n\n expect(db.auth.username).toEqual 'bob'\n expect(db.auth.password).toEqual 'thebuilder", "end": 966, "score": 0.9595069289207458, "start": 963, "tag": "USERNAME", "value": "bob" }, { "context": "Equal 'bob'\n expect(db.auth.password).toEqual 'theb...
spec/database.spec.coffee
brianewing/footrest
1
footrest = require '../lib/index' describe 'database management', -> beforeEach -> @database = footrest.database('footrest') @database.destroy => @destroyed = true waitsFor -> @destroyed? it 'should not exist by default', -> @database.exists (err, @exists) => waitsFor -> @exists? runs -> expect(@exists).toEqual false it 'should create a database', -> @database.create (err, db) => @created = (db.ok == true) waitsFor -> @created? runs -> expect(@created).toEqual true it 'should destroy a database', -> @database.create => @database.destroy => @database.exists (err, @exists) => waitsFor -> @exists? runs -> expect(@exists).toEqual false describe 'database object creation', -> it 'should parse various options from database URI', -> db = footrest.createConnection url: 'https://bob:thebuilder@remote.couch:1234' expect(db.auth.username).toEqual 'bob' expect(db.auth.password).toEqual 'thebuilder' expect(db.host).toEqual 'remote.couch' expect(db.port.toString()).toEqual '1234' it 'should parse options from database URI without auth and port', -> db = footrest.createConnection url: 'http://remote.couch' expect(db.auth.username).toEqual null expect(db.auth.password).toEqual null expect(db.host).toEqual 'remote.couch' expect(db.port.toString()).toEqual '5984'
216858
footrest = require '../lib/index' describe 'database management', -> beforeEach -> @database = footrest.database('footrest') @database.destroy => @destroyed = true waitsFor -> @destroyed? it 'should not exist by default', -> @database.exists (err, @exists) => waitsFor -> @exists? runs -> expect(@exists).toEqual false it 'should create a database', -> @database.create (err, db) => @created = (db.ok == true) waitsFor -> @created? runs -> expect(@created).toEqual true it 'should destroy a database', -> @database.create => @database.destroy => @database.exists (err, @exists) => waitsFor -> @exists? runs -> expect(@exists).toEqual false describe 'database object creation', -> it 'should parse various options from database URI', -> db = footrest.createConnection url: 'https://bob:thebuilder@remote.couch:1234' expect(db.auth.username).toEqual 'bob' expect(db.auth.password).toEqual '<PASSWORD>' expect(db.host).toEqual 'remote.couch' expect(db.port.toString()).toEqual '1234' it 'should parse options from database URI without auth and port', -> db = footrest.createConnection url: 'http://remote.couch' expect(db.auth.username).toEqual null expect(db.auth.password).toEqual null expect(db.host).toEqual 'remote.couch' expect(db.port.toString()).toEqual '5984'
true
footrest = require '../lib/index' describe 'database management', -> beforeEach -> @database = footrest.database('footrest') @database.destroy => @destroyed = true waitsFor -> @destroyed? it 'should not exist by default', -> @database.exists (err, @exists) => waitsFor -> @exists? runs -> expect(@exists).toEqual false it 'should create a database', -> @database.create (err, db) => @created = (db.ok == true) waitsFor -> @created? runs -> expect(@created).toEqual true it 'should destroy a database', -> @database.create => @database.destroy => @database.exists (err, @exists) => waitsFor -> @exists? runs -> expect(@exists).toEqual false describe 'database object creation', -> it 'should parse various options from database URI', -> db = footrest.createConnection url: 'https://bob:thebuilder@remote.couch:1234' expect(db.auth.username).toEqual 'bob' expect(db.auth.password).toEqual 'PI:PASSWORD:<PASSWORD>END_PI' expect(db.host).toEqual 'remote.couch' expect(db.port.toString()).toEqual '1234' it 'should parse options from database URI without auth and port', -> db = footrest.createConnection url: 'http://remote.couch' expect(db.auth.username).toEqual null expect(db.auth.password).toEqual null expect(db.host).toEqual 'remote.couch' expect(db.port.toString()).toEqual '5984'
[ { "context": "asmine.createSpy())\n replace(/Some text/gi, 'kittens', scanner, replacer, finishedHandler = jasmine.cr", "end": 2465, "score": 0.9912243485450745, "start": 2458, "tag": "NAME", "value": "kittens" }, { "context": " = jasmine.createSpy())\n replace(/items/gi, '...
spec/single-process-search-spec.coffee
vergenzt/scandal
39
fs = require 'fs' path = require 'path' PathScanner = require '../src/path-scanner' PathSearcher = require '../src/path-searcher' PathReplacer = require '../src/path-replacer' {search, replace, replacePaths} = require '../src/single-process-search' describe "search", -> [scanner, searcher, rootPath] = [] beforeEach -> rootPath = fs.realpathSync(path.join("spec", "fixtures", "many-files")) scanner = new PathScanner(rootPath) searcher = new PathSearcher() describe "when there is no error", -> it "finds matches in a file", -> searcher.on('results-found', resultsHandler = jasmine.createSpy()) search(/items/gi, scanner, searcher, finishedHandler = jasmine.createSpy()) waitsFor -> finishedHandler.callCount > 0 runs -> expect(resultsHandler.callCount).toBe 3 regex = /many-files\/sample(-)?.*\.js/g expect(resultsHandler.argsForCall[0][0].filePath).toMatch regex expect(resultsHandler.argsForCall[1][0].filePath).toMatch regex expect(resultsHandler.argsForCall[2][0].filePath).toMatch regex describe "when there is an error", -> it "finishes searching and properly emits the error event", -> scanSpy = spyOn(scanner, 'scan') searcher.on('file-error', errorHandler = jasmine.createSpy()) searcher.on('results-found', resultsHandler = jasmine.createSpy()) search(/items/gi, scanner, searcher, finishedHandler = jasmine.createSpy()) scanner.emit('path-found', '/this-doesnt-exist.js') scanner.emit('path-found', '/nope-not-this-either.js') scanner.emit('finished-scanning') waitsFor -> finishedHandler.callCount > 0 runs -> expect(errorHandler.callCount).toBe 2 expect(resultsHandler).not.toHaveBeenCalled() describe "replace", -> [scanner, replacer, rootPath] = [] beforeEach -> rootPath = fs.realpathSync(path.join("spec", "fixtures", "many-files")) scanner = new PathScanner(rootPath) replacer = new PathReplacer() describe "when a replacement is made", -> [filePath, sampleContent] = [] beforeEach -> filePath = path.join(rootPath, 'sample.txt') sampleContent = fs.readFileSync(filePath).toString() afterEach -> fs.writeFileSync(filePath, sampleContent) it "finds matches and replaces said matches", -> replacer.on('path-replaced', resultsHandler = jasmine.createSpy()) replace(/Some text/gi, 'kittens', scanner, replacer, finishedHandler = jasmine.createSpy()) waitsFor -> finishedHandler.callCount > 0 runs -> expect(resultsHandler.callCount).toBe 1 expect(resultsHandler.argsForCall[0][0].filePath).toContain 'sample.txt' describe "when there is an error", -> it "emits proper error events", -> scanSpy = spyOn(scanner, 'scan') replacer.on('file-error', errorHandler = jasmine.createSpy()) replacer.on('path-replaced', resultsHandler = jasmine.createSpy()) replace(/items/gi, 'kittens', scanner, replacer, finishedHandler = jasmine.createSpy()) scanner.emit('path-found', '/this-doesnt-exist.js') scanner.emit('path-found', '/nope-not-this-either.js') scanner.emit('finished-scanning') waitsFor -> finishedHandler.callCount > 0 runs -> expect(errorHandler.callCount).toBe 2 expect(resultsHandler).not.toHaveBeenCalled()
131557
fs = require 'fs' path = require 'path' PathScanner = require '../src/path-scanner' PathSearcher = require '../src/path-searcher' PathReplacer = require '../src/path-replacer' {search, replace, replacePaths} = require '../src/single-process-search' describe "search", -> [scanner, searcher, rootPath] = [] beforeEach -> rootPath = fs.realpathSync(path.join("spec", "fixtures", "many-files")) scanner = new PathScanner(rootPath) searcher = new PathSearcher() describe "when there is no error", -> it "finds matches in a file", -> searcher.on('results-found', resultsHandler = jasmine.createSpy()) search(/items/gi, scanner, searcher, finishedHandler = jasmine.createSpy()) waitsFor -> finishedHandler.callCount > 0 runs -> expect(resultsHandler.callCount).toBe 3 regex = /many-files\/sample(-)?.*\.js/g expect(resultsHandler.argsForCall[0][0].filePath).toMatch regex expect(resultsHandler.argsForCall[1][0].filePath).toMatch regex expect(resultsHandler.argsForCall[2][0].filePath).toMatch regex describe "when there is an error", -> it "finishes searching and properly emits the error event", -> scanSpy = spyOn(scanner, 'scan') searcher.on('file-error', errorHandler = jasmine.createSpy()) searcher.on('results-found', resultsHandler = jasmine.createSpy()) search(/items/gi, scanner, searcher, finishedHandler = jasmine.createSpy()) scanner.emit('path-found', '/this-doesnt-exist.js') scanner.emit('path-found', '/nope-not-this-either.js') scanner.emit('finished-scanning') waitsFor -> finishedHandler.callCount > 0 runs -> expect(errorHandler.callCount).toBe 2 expect(resultsHandler).not.toHaveBeenCalled() describe "replace", -> [scanner, replacer, rootPath] = [] beforeEach -> rootPath = fs.realpathSync(path.join("spec", "fixtures", "many-files")) scanner = new PathScanner(rootPath) replacer = new PathReplacer() describe "when a replacement is made", -> [filePath, sampleContent] = [] beforeEach -> filePath = path.join(rootPath, 'sample.txt') sampleContent = fs.readFileSync(filePath).toString() afterEach -> fs.writeFileSync(filePath, sampleContent) it "finds matches and replaces said matches", -> replacer.on('path-replaced', resultsHandler = jasmine.createSpy()) replace(/Some text/gi, '<NAME>', scanner, replacer, finishedHandler = jasmine.createSpy()) waitsFor -> finishedHandler.callCount > 0 runs -> expect(resultsHandler.callCount).toBe 1 expect(resultsHandler.argsForCall[0][0].filePath).toContain 'sample.txt' describe "when there is an error", -> it "emits proper error events", -> scanSpy = spyOn(scanner, 'scan') replacer.on('file-error', errorHandler = jasmine.createSpy()) replacer.on('path-replaced', resultsHandler = jasmine.createSpy()) replace(/items/gi, '<NAME>', scanner, replacer, finishedHandler = jasmine.createSpy()) scanner.emit('path-found', '/this-doesnt-exist.js') scanner.emit('path-found', '/nope-not-this-either.js') scanner.emit('finished-scanning') waitsFor -> finishedHandler.callCount > 0 runs -> expect(errorHandler.callCount).toBe 2 expect(resultsHandler).not.toHaveBeenCalled()
true
fs = require 'fs' path = require 'path' PathScanner = require '../src/path-scanner' PathSearcher = require '../src/path-searcher' PathReplacer = require '../src/path-replacer' {search, replace, replacePaths} = require '../src/single-process-search' describe "search", -> [scanner, searcher, rootPath] = [] beforeEach -> rootPath = fs.realpathSync(path.join("spec", "fixtures", "many-files")) scanner = new PathScanner(rootPath) searcher = new PathSearcher() describe "when there is no error", -> it "finds matches in a file", -> searcher.on('results-found', resultsHandler = jasmine.createSpy()) search(/items/gi, scanner, searcher, finishedHandler = jasmine.createSpy()) waitsFor -> finishedHandler.callCount > 0 runs -> expect(resultsHandler.callCount).toBe 3 regex = /many-files\/sample(-)?.*\.js/g expect(resultsHandler.argsForCall[0][0].filePath).toMatch regex expect(resultsHandler.argsForCall[1][0].filePath).toMatch regex expect(resultsHandler.argsForCall[2][0].filePath).toMatch regex describe "when there is an error", -> it "finishes searching and properly emits the error event", -> scanSpy = spyOn(scanner, 'scan') searcher.on('file-error', errorHandler = jasmine.createSpy()) searcher.on('results-found', resultsHandler = jasmine.createSpy()) search(/items/gi, scanner, searcher, finishedHandler = jasmine.createSpy()) scanner.emit('path-found', '/this-doesnt-exist.js') scanner.emit('path-found', '/nope-not-this-either.js') scanner.emit('finished-scanning') waitsFor -> finishedHandler.callCount > 0 runs -> expect(errorHandler.callCount).toBe 2 expect(resultsHandler).not.toHaveBeenCalled() describe "replace", -> [scanner, replacer, rootPath] = [] beforeEach -> rootPath = fs.realpathSync(path.join("spec", "fixtures", "many-files")) scanner = new PathScanner(rootPath) replacer = new PathReplacer() describe "when a replacement is made", -> [filePath, sampleContent] = [] beforeEach -> filePath = path.join(rootPath, 'sample.txt') sampleContent = fs.readFileSync(filePath).toString() afterEach -> fs.writeFileSync(filePath, sampleContent) it "finds matches and replaces said matches", -> replacer.on('path-replaced', resultsHandler = jasmine.createSpy()) replace(/Some text/gi, 'PI:NAME:<NAME>END_PI', scanner, replacer, finishedHandler = jasmine.createSpy()) waitsFor -> finishedHandler.callCount > 0 runs -> expect(resultsHandler.callCount).toBe 1 expect(resultsHandler.argsForCall[0][0].filePath).toContain 'sample.txt' describe "when there is an error", -> it "emits proper error events", -> scanSpy = spyOn(scanner, 'scan') replacer.on('file-error', errorHandler = jasmine.createSpy()) replacer.on('path-replaced', resultsHandler = jasmine.createSpy()) replace(/items/gi, 'PI:NAME:<NAME>END_PI', scanner, replacer, finishedHandler = jasmine.createSpy()) scanner.emit('path-found', '/this-doesnt-exist.js') scanner.emit('path-found', '/nope-not-this-either.js') scanner.emit('finished-scanning') waitsFor -> finishedHandler.callCount > 0 runs -> expect(errorHandler.callCount).toBe 2 expect(resultsHandler).not.toHaveBeenCalled()
[ { "context": "1.0\n\nSlide control for Touchy.\n\n(c) 2015 Copyright Stardotstar.\nproject located at https://github.com/stardotsta", "end": 92, "score": 0.9849526882171631, "start": 81, "tag": "NAME", "value": "Stardotstar" }, { "context": "tardotstar.\nproject located at https://gi...
touchy_slider.coffee
stardotstar/Touchy
0
### touchy_slider.js, version 1.0 Slide control for Touchy. (c) 2015 Copyright Stardotstar. project located at https://github.com/stardotstar/TouchySlider.js. Licenced under the Apache license (see LICENSE file) ### ((window) -> # helper methods extend = (object, properties) -> for key, val of properties object[key] = val object noop = -> TouchySliderDefinition = (Touchy,$,EventEmitter,TweenMax) -> class TouchySlider constructor: (elm,options) -> @elm = $(elm).first() @options = $.extend {}, _default_options, options @handle = $(@options.handle).first() if @options.handle # console.log('Initialized TouchySlider on', @elm ,@options) @_createSlider() @_setupResize() @_setupTouchyInstance() @_configureValues() @_createLabels(@options.labels) @value(@options.initial_value) @_updateHandlePosition() @_createBubble() if @options.show_bubble @_updateBubble() @emitEvent('init', [ @, @_value ] ) @elm.css('opacity',1) _default_options = vertical: false min_value: 0 max_value: 100 initial_value: 0 handle: null show_bubble: true bubble_suffix: '' bubble_prefix: '' values: null labels: [] _setupTouchyInstance: -> @_touchy = new Touchy @elm, cancel_on_scroll: false @_touchy.on 'start', (event,t,pointer) => @_update() @_setHandleClass(true) @emitEvent('start', [ event, @, @_value ] ) @_touchy.on 'move', (event,t,pointer) => @_update() @_setHandleClass(true) @_touchy.on 'end', (event,t,pointer) => @_update() @_setHandleClass(false) @emitEvent('end', [ event, @, @_value ] ) _createSlider: -> @elm.addClass('slider') @elm.addClass(if @options.vertical then 'slider_v' else 'slider_h') @elm.css position: 'relative' # create the bar @bar_elm = $("<div class='slider_bar'>") @elm.append(@bar_elm) # create the handle if not @handle @handle = $("<div class='slider_handle'>") @elm.append(@handle) _createLabels: (labels) -> label_width = (100 / labels.length).toFixed(4) @label_elm = $("<div class='slider_labels'>") for label,i in labels newelm = $("<div class='slider_label'>") newelm.css width: label_width + '%' float: 'left' textAlign: 'center' if i == 0 newelm.css 'textAlign', 'left' else if i == labels.length-1 newelm.css float: 'right' textAlign: 'right' newelm.text(label) @label_elm.append(newelm) @elm.append(@label_elm) _createBubble: -> return unless @options.show_bubble @bubble_elm = $("<div class='slider_bubble'>") @bubble_elm.css position: 'absolute' @elm.append(@bubble_elm) _configureValues: -> if @options.values and @options.values.length @options.min_value = 0 @options.max_value = @options.values.length-1 _setHandleClass: (add = false) -> if add @handle.addClass('touching') else @handle.removeClass('touching') value: (val) -> if val? @_value = val @_value_pct = @_valueToPercent(val) @ else @_value valuePercent: (val) -> if val? @_value_pct = val @_value = @_percentToValue(val) @ else @_value_pct _update: -> if @options.vertical pos = @_touchy.current_point.y else pos = @_touchy.current_point.x pct = Math.round(((pos - @_offset) / @_length) * 100) pct = 0 if pct < 0 pct = 100 if pct > 100 val = @_percentToValue(pct) val = @_trimAlignValue(val) if val != @_value # value has changed @value(val) @_updateHandlePosition() @_updateBubble() @emitEvent('update', [ @, event, @_value ] ) _updateHandlePosition: -> if @handle # move the handle handle_pos = (@_value_pct / 100) * @_length handle_pos -= @_handleLength / 2 if @options.vertical @handle.css('top',handle_pos) else @handle.css('left',handle_pos) return true false _updateBubble: -> if @options.show_bubble and @bubble_elm bubble_text = if @options.values and @options.values.length then @options.values[@_value] else @_value # set value @bubble_elm.text('' + @options.bubble_prefix + bubble_text + @options.bubble_suffix) # move the handle bubble_pos = (@_value_pct / 100) * @_length bubble_pos -= @bubble_elm.outerWidth() / 2 if @options.vertical @bubble_elm.css('top',bubble_pos) else @bubble_elm.css('left',bubble_pos) _valueToPercent: (val) -> ((val - @options.min_value) / (@options.max_value - @options.min_value)) * 100 _percentToValue: (pct) -> ((pct / 100) * (@options.max_value - @options.min_value)) + @options.min_value _trimAlignValue: (val) -> if val <= @options.min_value return @options.min_value if val >= @options.max_value return @options.max_value step = if @options.step > 0 then @options.step else 1 valModStep = (val - @options.min_value) % step alignValue = val - valModStep if Math.abs(valModStep) * 2 >= step alignValue += if valModStep > 0 then step else -step # Since JavaScript has problems with large floats, round # the final value to 5 digits after the decimal point return parseFloat(alignValue.toFixed(5)) _setupResize: -> $(window).on 'resize', => @_resize() @_resize() _resize: -> if @options.vertical @_length = @elm.height() @_offset = @elm.offset().top @_handleLength = @handle.height() if @handle else @_length = @elm.width() @_offset = @elm.offset().left @_handleLength = @handle.width() if @handle @_updateHandlePosition() true extend TouchySlider.prototype, EventEmitter.prototype return TouchySlider if typeof define == 'function' and define.amd # amd define([ 'touchy', 'jquery', 'eventEmitter', 'gsap', 'jquery-transform' ], TouchySliderDefinition) else if typeof exports == 'object' # commonjs module.exports = TouchySliderDefinition( require('touchy'), require('jquery'), require('wolfy87-eventemitter'), require('gsap'), require('jquery-transform') ) else # global window.TouchySlider = TouchySliderDefinition( window.Touchy, window.jQuery, window.EventEmitter, window.TweenMax ) )(window)
10074
### touchy_slider.js, version 1.0 Slide control for Touchy. (c) 2015 Copyright <NAME>. project located at https://github.com/stardotstar/TouchySlider.js. Licenced under the Apache license (see LICENSE file) ### ((window) -> # helper methods extend = (object, properties) -> for key, val of properties object[key] = val object noop = -> TouchySliderDefinition = (Touchy,$,EventEmitter,TweenMax) -> class TouchySlider constructor: (elm,options) -> @elm = $(elm).first() @options = $.extend {}, _default_options, options @handle = $(@options.handle).first() if @options.handle # console.log('Initialized TouchySlider on', @elm ,@options) @_createSlider() @_setupResize() @_setupTouchyInstance() @_configureValues() @_createLabels(@options.labels) @value(@options.initial_value) @_updateHandlePosition() @_createBubble() if @options.show_bubble @_updateBubble() @emitEvent('init', [ @, @_value ] ) @elm.css('opacity',1) _default_options = vertical: false min_value: 0 max_value: 100 initial_value: 0 handle: null show_bubble: true bubble_suffix: '' bubble_prefix: '' values: null labels: [] _setupTouchyInstance: -> @_touchy = new Touchy @elm, cancel_on_scroll: false @_touchy.on 'start', (event,t,pointer) => @_update() @_setHandleClass(true) @emitEvent('start', [ event, @, @_value ] ) @_touchy.on 'move', (event,t,pointer) => @_update() @_setHandleClass(true) @_touchy.on 'end', (event,t,pointer) => @_update() @_setHandleClass(false) @emitEvent('end', [ event, @, @_value ] ) _createSlider: -> @elm.addClass('slider') @elm.addClass(if @options.vertical then 'slider_v' else 'slider_h') @elm.css position: 'relative' # create the bar @bar_elm = $("<div class='slider_bar'>") @elm.append(@bar_elm) # create the handle if not @handle @handle = $("<div class='slider_handle'>") @elm.append(@handle) _createLabels: (labels) -> label_width = (100 / labels.length).toFixed(4) @label_elm = $("<div class='slider_labels'>") for label,i in labels newelm = $("<div class='slider_label'>") newelm.css width: label_width + '%' float: 'left' textAlign: 'center' if i == 0 newelm.css 'textAlign', 'left' else if i == labels.length-1 newelm.css float: 'right' textAlign: 'right' newelm.text(label) @label_elm.append(newelm) @elm.append(@label_elm) _createBubble: -> return unless @options.show_bubble @bubble_elm = $("<div class='slider_bubble'>") @bubble_elm.css position: 'absolute' @elm.append(@bubble_elm) _configureValues: -> if @options.values and @options.values.length @options.min_value = 0 @options.max_value = @options.values.length-1 _setHandleClass: (add = false) -> if add @handle.addClass('touching') else @handle.removeClass('touching') value: (val) -> if val? @_value = val @_value_pct = @_valueToPercent(val) @ else @_value valuePercent: (val) -> if val? @_value_pct = val @_value = @_percentToValue(val) @ else @_value_pct _update: -> if @options.vertical pos = @_touchy.current_point.y else pos = @_touchy.current_point.x pct = Math.round(((pos - @_offset) / @_length) * 100) pct = 0 if pct < 0 pct = 100 if pct > 100 val = @_percentToValue(pct) val = @_trimAlignValue(val) if val != @_value # value has changed @value(val) @_updateHandlePosition() @_updateBubble() @emitEvent('update', [ @, event, @_value ] ) _updateHandlePosition: -> if @handle # move the handle handle_pos = (@_value_pct / 100) * @_length handle_pos -= @_handleLength / 2 if @options.vertical @handle.css('top',handle_pos) else @handle.css('left',handle_pos) return true false _updateBubble: -> if @options.show_bubble and @bubble_elm bubble_text = if @options.values and @options.values.length then @options.values[@_value] else @_value # set value @bubble_elm.text('' + @options.bubble_prefix + bubble_text + @options.bubble_suffix) # move the handle bubble_pos = (@_value_pct / 100) * @_length bubble_pos -= @bubble_elm.outerWidth() / 2 if @options.vertical @bubble_elm.css('top',bubble_pos) else @bubble_elm.css('left',bubble_pos) _valueToPercent: (val) -> ((val - @options.min_value) / (@options.max_value - @options.min_value)) * 100 _percentToValue: (pct) -> ((pct / 100) * (@options.max_value - @options.min_value)) + @options.min_value _trimAlignValue: (val) -> if val <= @options.min_value return @options.min_value if val >= @options.max_value return @options.max_value step = if @options.step > 0 then @options.step else 1 valModStep = (val - @options.min_value) % step alignValue = val - valModStep if Math.abs(valModStep) * 2 >= step alignValue += if valModStep > 0 then step else -step # Since JavaScript has problems with large floats, round # the final value to 5 digits after the decimal point return parseFloat(alignValue.toFixed(5)) _setupResize: -> $(window).on 'resize', => @_resize() @_resize() _resize: -> if @options.vertical @_length = @elm.height() @_offset = @elm.offset().top @_handleLength = @handle.height() if @handle else @_length = @elm.width() @_offset = @elm.offset().left @_handleLength = @handle.width() if @handle @_updateHandlePosition() true extend TouchySlider.prototype, EventEmitter.prototype return TouchySlider if typeof define == 'function' and define.amd # amd define([ 'touchy', 'jquery', 'eventEmitter', 'gsap', 'jquery-transform' ], TouchySliderDefinition) else if typeof exports == 'object' # commonjs module.exports = TouchySliderDefinition( require('touchy'), require('jquery'), require('wolfy87-eventemitter'), require('gsap'), require('jquery-transform') ) else # global window.TouchySlider = TouchySliderDefinition( window.Touchy, window.jQuery, window.EventEmitter, window.TweenMax ) )(window)
true
### touchy_slider.js, version 1.0 Slide control for Touchy. (c) 2015 Copyright PI:NAME:<NAME>END_PI. project located at https://github.com/stardotstar/TouchySlider.js. Licenced under the Apache license (see LICENSE file) ### ((window) -> # helper methods extend = (object, properties) -> for key, val of properties object[key] = val object noop = -> TouchySliderDefinition = (Touchy,$,EventEmitter,TweenMax) -> class TouchySlider constructor: (elm,options) -> @elm = $(elm).first() @options = $.extend {}, _default_options, options @handle = $(@options.handle).first() if @options.handle # console.log('Initialized TouchySlider on', @elm ,@options) @_createSlider() @_setupResize() @_setupTouchyInstance() @_configureValues() @_createLabels(@options.labels) @value(@options.initial_value) @_updateHandlePosition() @_createBubble() if @options.show_bubble @_updateBubble() @emitEvent('init', [ @, @_value ] ) @elm.css('opacity',1) _default_options = vertical: false min_value: 0 max_value: 100 initial_value: 0 handle: null show_bubble: true bubble_suffix: '' bubble_prefix: '' values: null labels: [] _setupTouchyInstance: -> @_touchy = new Touchy @elm, cancel_on_scroll: false @_touchy.on 'start', (event,t,pointer) => @_update() @_setHandleClass(true) @emitEvent('start', [ event, @, @_value ] ) @_touchy.on 'move', (event,t,pointer) => @_update() @_setHandleClass(true) @_touchy.on 'end', (event,t,pointer) => @_update() @_setHandleClass(false) @emitEvent('end', [ event, @, @_value ] ) _createSlider: -> @elm.addClass('slider') @elm.addClass(if @options.vertical then 'slider_v' else 'slider_h') @elm.css position: 'relative' # create the bar @bar_elm = $("<div class='slider_bar'>") @elm.append(@bar_elm) # create the handle if not @handle @handle = $("<div class='slider_handle'>") @elm.append(@handle) _createLabels: (labels) -> label_width = (100 / labels.length).toFixed(4) @label_elm = $("<div class='slider_labels'>") for label,i in labels newelm = $("<div class='slider_label'>") newelm.css width: label_width + '%' float: 'left' textAlign: 'center' if i == 0 newelm.css 'textAlign', 'left' else if i == labels.length-1 newelm.css float: 'right' textAlign: 'right' newelm.text(label) @label_elm.append(newelm) @elm.append(@label_elm) _createBubble: -> return unless @options.show_bubble @bubble_elm = $("<div class='slider_bubble'>") @bubble_elm.css position: 'absolute' @elm.append(@bubble_elm) _configureValues: -> if @options.values and @options.values.length @options.min_value = 0 @options.max_value = @options.values.length-1 _setHandleClass: (add = false) -> if add @handle.addClass('touching') else @handle.removeClass('touching') value: (val) -> if val? @_value = val @_value_pct = @_valueToPercent(val) @ else @_value valuePercent: (val) -> if val? @_value_pct = val @_value = @_percentToValue(val) @ else @_value_pct _update: -> if @options.vertical pos = @_touchy.current_point.y else pos = @_touchy.current_point.x pct = Math.round(((pos - @_offset) / @_length) * 100) pct = 0 if pct < 0 pct = 100 if pct > 100 val = @_percentToValue(pct) val = @_trimAlignValue(val) if val != @_value # value has changed @value(val) @_updateHandlePosition() @_updateBubble() @emitEvent('update', [ @, event, @_value ] ) _updateHandlePosition: -> if @handle # move the handle handle_pos = (@_value_pct / 100) * @_length handle_pos -= @_handleLength / 2 if @options.vertical @handle.css('top',handle_pos) else @handle.css('left',handle_pos) return true false _updateBubble: -> if @options.show_bubble and @bubble_elm bubble_text = if @options.values and @options.values.length then @options.values[@_value] else @_value # set value @bubble_elm.text('' + @options.bubble_prefix + bubble_text + @options.bubble_suffix) # move the handle bubble_pos = (@_value_pct / 100) * @_length bubble_pos -= @bubble_elm.outerWidth() / 2 if @options.vertical @bubble_elm.css('top',bubble_pos) else @bubble_elm.css('left',bubble_pos) _valueToPercent: (val) -> ((val - @options.min_value) / (@options.max_value - @options.min_value)) * 100 _percentToValue: (pct) -> ((pct / 100) * (@options.max_value - @options.min_value)) + @options.min_value _trimAlignValue: (val) -> if val <= @options.min_value return @options.min_value if val >= @options.max_value return @options.max_value step = if @options.step > 0 then @options.step else 1 valModStep = (val - @options.min_value) % step alignValue = val - valModStep if Math.abs(valModStep) * 2 >= step alignValue += if valModStep > 0 then step else -step # Since JavaScript has problems with large floats, round # the final value to 5 digits after the decimal point return parseFloat(alignValue.toFixed(5)) _setupResize: -> $(window).on 'resize', => @_resize() @_resize() _resize: -> if @options.vertical @_length = @elm.height() @_offset = @elm.offset().top @_handleLength = @handle.height() if @handle else @_length = @elm.width() @_offset = @elm.offset().left @_handleLength = @handle.width() if @handle @_updateHandlePosition() true extend TouchySlider.prototype, EventEmitter.prototype return TouchySlider if typeof define == 'function' and define.amd # amd define([ 'touchy', 'jquery', 'eventEmitter', 'gsap', 'jquery-transform' ], TouchySliderDefinition) else if typeof exports == 'object' # commonjs module.exports = TouchySliderDefinition( require('touchy'), require('jquery'), require('wolfy87-eventemitter'), require('gsap'), require('jquery-transform') ) else # global window.TouchySlider = TouchySliderDefinition( window.Touchy, window.jQuery, window.EventEmitter, window.TweenMax ) )(window)
[ { "context": "present junk', (assert) ->\n model = \n email: \"foxnewsnetwork@gmail.com\"\n username: \"foxnewsnetwork\"\n\n absence(\"email", "end": 365, "score": 0.9999149441719055, "start": 341, "tag": "EMAIL", "value": "foxnewsnetwork@gmail.com" }, { "context": " email: \...
tests/unit/validators/absence-test.coffee
foxnewsnetwork/ember-functional-validation
4
`import Ember from 'ember'` `import { module, test } from 'qunit'` `import absence from 'ember-functional-validation/validators/absence'` module 'Validators: Absence' test 'it should exist', (assert) -> assert.ok absence assert.equal typeof absence, 'function' test 'it should reject present junk', (assert) -> model = email: "foxnewsnetwork@gmail.com" username: "foxnewsnetwork" absence("email", true, model).then (checkedModel) -> assert.ok false, "it should not get here" .catch (errors) -> assert.equal errors.size, 1 assert.deepEqual errors.get("email"), ["cannot be present"] test 'it should resolve absent junk', (assert) -> model = null absence "email", true, model .then (model) -> assert.deepEqual model, {} .catch (error) -> assert.ok false, "it should not reject a good object"
46927
`import Ember from 'ember'` `import { module, test } from 'qunit'` `import absence from 'ember-functional-validation/validators/absence'` module 'Validators: Absence' test 'it should exist', (assert) -> assert.ok absence assert.equal typeof absence, 'function' test 'it should reject present junk', (assert) -> model = email: "<EMAIL>" username: "foxnewsnetwork" absence("email", true, model).then (checkedModel) -> assert.ok false, "it should not get here" .catch (errors) -> assert.equal errors.size, 1 assert.deepEqual errors.get("email"), ["cannot be present"] test 'it should resolve absent junk', (assert) -> model = null absence "email", true, model .then (model) -> assert.deepEqual model, {} .catch (error) -> assert.ok false, "it should not reject a good object"
true
`import Ember from 'ember'` `import { module, test } from 'qunit'` `import absence from 'ember-functional-validation/validators/absence'` module 'Validators: Absence' test 'it should exist', (assert) -> assert.ok absence assert.equal typeof absence, 'function' test 'it should reject present junk', (assert) -> model = email: "PI:EMAIL:<EMAIL>END_PI" username: "foxnewsnetwork" absence("email", true, model).then (checkedModel) -> assert.ok false, "it should not get here" .catch (errors) -> assert.equal errors.size, 1 assert.deepEqual errors.get("email"), ["cannot be present"] test 'it should resolve absent junk', (assert) -> model = null absence "email", true, model .then (model) -> assert.deepEqual model, {} .catch (error) -> assert.ok false, "it should not reject a good object"
[ { "context": "e 'name', presence: yes\n\n p = new Product name: 'nick'\n p.validate (result, errors) ->\n ok result\n ", "end": 903, "score": 0.7848004698753357, "start": 899, "tag": "NAME", "value": "nick" } ]
tests/batman/model/validations_test.coffee
nickjs/batman
1
QUnit.module "Batman.Model: validations" asyncTest "validation shouldn leave the model in the same state it left it", -> class Product extends Batman.Model @validate 'name', presence: yes p = new Product oldState = p.state() p.validate (result, errors) -> equal p.state(), oldState QUnit.start() asyncTest "length", 3, -> class Product extends Batman.Model @validate 'exact', length: 5 @validate 'max', maxLength: 4 @validate 'range', lengthWithin: [3, 5] p = new Product exact: '12345', max: '1234', range: '1234' p.validate (result) -> ok result p.set 'exact', '123' p.set 'max', '12345' p.set 'range', '12' p.validate (result, errors) -> ok !result equal errors.length, 3 QUnit.start() asyncTest "presence", 2, -> class Product extends Batman.Model @validate 'name', presence: yes p = new Product name: 'nick' p.validate (result, errors) -> ok result p.unset 'name' p.validate (result, errors) -> ok !result QUnit.start() asyncTest "custom async validations", -> letItPass = true class Product extends Batman.Model @validate 'name', (errors, record, key, callback) -> setTimeout -> errors.add 'name', "didn't validate" unless letItPass callback() , 0 p = new Product p.validate (result, errors) -> ok result letItPass = false p.validate (result, errors) -> ok !result QUnit.start() QUnit.module "Batman.Model: binding to errors" setup: -> class @Product extends Batman.Model @validate 'name', presence: yes @product = new @Product @someObject = Batman product: @product asyncTest "errors hash length should be observable", 3, -> @product.get('errors').meta.observe 'length', (newLength, oldLength) -> return if newLength == oldLength # Prevents the assertion below when the errors hash is cleared and its length goes from 0 to 0 equal newLength, 1 @product.validate (result, errors) -> equal errors.meta.get('length'), 1 equal errors.length, 1 QUnit.start() asyncTest "errors hash contents should be observable", 3, -> x = @product.get('errors.name') x.observe 'length', (newLength, oldLength) -> equal newLength, 1 @product.validate (result, errors) => equal errors.meta.get('length'), 1 equal errors.length, 1 x QUnit.start() asyncTest "errors hash length should be bindable", 4, -> @someObject.accessor 'productErrorsLength', -> errors = @get('product.errors') errors.meta.get('length') equal @someObject.get('productErrorsLength'), 0, 'the errors should start empty' @someObject.observe 'productErrorsLength', (newVal, oldVal) -> return if newVal == oldVal # Prevents the assertion below when the errors hash is cleared and its length goes from 0 to 0 equal newVal, 1, 'the foreign observer should fire when errors are added' @product.validate (result, errors) => equal errors.length, 1, 'the validation shouldn\'t succeed' equal @someObject.get('productErrorsLength'), 1, 'the foreign key should have updated' QUnit.start() asyncTest "errors hash contents should be bindable", 4, -> @someObject.accessor 'productNameErrorsLength', -> errors = @get('product.errors.name.length') equal @someObject.get('productNameErrorsLength'), 0, 'the errors should start empty' @someObject.observe 'productNameErrorsLength', (newVal, oldVal) -> return if newVal == oldVal # Prevents the assertion below when the errors hash is cleared and its length goes from 0 to 0 equal newVal, 1, 'the foreign observer should fire when errors are added' @product.validate (result, errors) => equal errors.length, 1, 'the validation shouldn\'t succeed' equal @someObject.get('productNameErrorsLength'), 1, 'the foreign key should have updated' QUnit.start()
187526
QUnit.module "Batman.Model: validations" asyncTest "validation shouldn leave the model in the same state it left it", -> class Product extends Batman.Model @validate 'name', presence: yes p = new Product oldState = p.state() p.validate (result, errors) -> equal p.state(), oldState QUnit.start() asyncTest "length", 3, -> class Product extends Batman.Model @validate 'exact', length: 5 @validate 'max', maxLength: 4 @validate 'range', lengthWithin: [3, 5] p = new Product exact: '12345', max: '1234', range: '1234' p.validate (result) -> ok result p.set 'exact', '123' p.set 'max', '12345' p.set 'range', '12' p.validate (result, errors) -> ok !result equal errors.length, 3 QUnit.start() asyncTest "presence", 2, -> class Product extends Batman.Model @validate 'name', presence: yes p = new Product name: '<NAME>' p.validate (result, errors) -> ok result p.unset 'name' p.validate (result, errors) -> ok !result QUnit.start() asyncTest "custom async validations", -> letItPass = true class Product extends Batman.Model @validate 'name', (errors, record, key, callback) -> setTimeout -> errors.add 'name', "didn't validate" unless letItPass callback() , 0 p = new Product p.validate (result, errors) -> ok result letItPass = false p.validate (result, errors) -> ok !result QUnit.start() QUnit.module "Batman.Model: binding to errors" setup: -> class @Product extends Batman.Model @validate 'name', presence: yes @product = new @Product @someObject = Batman product: @product asyncTest "errors hash length should be observable", 3, -> @product.get('errors').meta.observe 'length', (newLength, oldLength) -> return if newLength == oldLength # Prevents the assertion below when the errors hash is cleared and its length goes from 0 to 0 equal newLength, 1 @product.validate (result, errors) -> equal errors.meta.get('length'), 1 equal errors.length, 1 QUnit.start() asyncTest "errors hash contents should be observable", 3, -> x = @product.get('errors.name') x.observe 'length', (newLength, oldLength) -> equal newLength, 1 @product.validate (result, errors) => equal errors.meta.get('length'), 1 equal errors.length, 1 x QUnit.start() asyncTest "errors hash length should be bindable", 4, -> @someObject.accessor 'productErrorsLength', -> errors = @get('product.errors') errors.meta.get('length') equal @someObject.get('productErrorsLength'), 0, 'the errors should start empty' @someObject.observe 'productErrorsLength', (newVal, oldVal) -> return if newVal == oldVal # Prevents the assertion below when the errors hash is cleared and its length goes from 0 to 0 equal newVal, 1, 'the foreign observer should fire when errors are added' @product.validate (result, errors) => equal errors.length, 1, 'the validation shouldn\'t succeed' equal @someObject.get('productErrorsLength'), 1, 'the foreign key should have updated' QUnit.start() asyncTest "errors hash contents should be bindable", 4, -> @someObject.accessor 'productNameErrorsLength', -> errors = @get('product.errors.name.length') equal @someObject.get('productNameErrorsLength'), 0, 'the errors should start empty' @someObject.observe 'productNameErrorsLength', (newVal, oldVal) -> return if newVal == oldVal # Prevents the assertion below when the errors hash is cleared and its length goes from 0 to 0 equal newVal, 1, 'the foreign observer should fire when errors are added' @product.validate (result, errors) => equal errors.length, 1, 'the validation shouldn\'t succeed' equal @someObject.get('productNameErrorsLength'), 1, 'the foreign key should have updated' QUnit.start()
true
QUnit.module "Batman.Model: validations" asyncTest "validation shouldn leave the model in the same state it left it", -> class Product extends Batman.Model @validate 'name', presence: yes p = new Product oldState = p.state() p.validate (result, errors) -> equal p.state(), oldState QUnit.start() asyncTest "length", 3, -> class Product extends Batman.Model @validate 'exact', length: 5 @validate 'max', maxLength: 4 @validate 'range', lengthWithin: [3, 5] p = new Product exact: '12345', max: '1234', range: '1234' p.validate (result) -> ok result p.set 'exact', '123' p.set 'max', '12345' p.set 'range', '12' p.validate (result, errors) -> ok !result equal errors.length, 3 QUnit.start() asyncTest "presence", 2, -> class Product extends Batman.Model @validate 'name', presence: yes p = new Product name: 'PI:NAME:<NAME>END_PI' p.validate (result, errors) -> ok result p.unset 'name' p.validate (result, errors) -> ok !result QUnit.start() asyncTest "custom async validations", -> letItPass = true class Product extends Batman.Model @validate 'name', (errors, record, key, callback) -> setTimeout -> errors.add 'name', "didn't validate" unless letItPass callback() , 0 p = new Product p.validate (result, errors) -> ok result letItPass = false p.validate (result, errors) -> ok !result QUnit.start() QUnit.module "Batman.Model: binding to errors" setup: -> class @Product extends Batman.Model @validate 'name', presence: yes @product = new @Product @someObject = Batman product: @product asyncTest "errors hash length should be observable", 3, -> @product.get('errors').meta.observe 'length', (newLength, oldLength) -> return if newLength == oldLength # Prevents the assertion below when the errors hash is cleared and its length goes from 0 to 0 equal newLength, 1 @product.validate (result, errors) -> equal errors.meta.get('length'), 1 equal errors.length, 1 QUnit.start() asyncTest "errors hash contents should be observable", 3, -> x = @product.get('errors.name') x.observe 'length', (newLength, oldLength) -> equal newLength, 1 @product.validate (result, errors) => equal errors.meta.get('length'), 1 equal errors.length, 1 x QUnit.start() asyncTest "errors hash length should be bindable", 4, -> @someObject.accessor 'productErrorsLength', -> errors = @get('product.errors') errors.meta.get('length') equal @someObject.get('productErrorsLength'), 0, 'the errors should start empty' @someObject.observe 'productErrorsLength', (newVal, oldVal) -> return if newVal == oldVal # Prevents the assertion below when the errors hash is cleared and its length goes from 0 to 0 equal newVal, 1, 'the foreign observer should fire when errors are added' @product.validate (result, errors) => equal errors.length, 1, 'the validation shouldn\'t succeed' equal @someObject.get('productErrorsLength'), 1, 'the foreign key should have updated' QUnit.start() asyncTest "errors hash contents should be bindable", 4, -> @someObject.accessor 'productNameErrorsLength', -> errors = @get('product.errors.name.length') equal @someObject.get('productNameErrorsLength'), 0, 'the errors should start empty' @someObject.observe 'productNameErrorsLength', (newVal, oldVal) -> return if newVal == oldVal # Prevents the assertion below when the errors hash is cleared and its length goes from 0 to 0 equal newVal, 1, 'the foreign observer should fire when errors are added' @product.validate (result, errors) => equal errors.length, 1, 'the validation shouldn\'t succeed' equal @someObject.get('productNameErrorsLength'), 1, 'the foreign key should have updated' QUnit.start()
[ { "context": "ts factory base class\n ###\n constructor: (@_sourceName, @_contactFetcher) ->\n @_conf = Conf.getCo", "end": 456, "score": 0.6230987310409546, "start": 446, "tag": "USERNAME", "value": "sourceName" }, { "context": "ontinue if not contact\n conta...
src/server/contacts/contacts_factory.coffee
LaPingvino/rizzoma
88
_ = require('underscore') async = require('async') Conf = require('../conf').Conf NotImplementedError = require('../../share/exceptions').NotImplementedError {GoogleContactsFetcher, FacebookContactsFetcher} = require('./contacts_fetcher') DateUtils = require('../utils/date_utils').DateUtils UPDATE_THRESHOLD = Conf.get('contacts').updateThreshold class ContactsFactory ### User contacts factory base class ### constructor: (@_sourceName, @_contactFetcher) -> @_conf = Conf.getContactsConfForSource(@_sourceName) @_logger = Conf.getLogger('contacts') getAccessToken: (req, res) -> @_contactFetcher.getAccessToken(req, res) onAuthCodeGot: (req, res, callback) -> @_contactFetcher.onAuthCodeGot(req, res, callback) autoUpdateContacts: (contacts, callback) -> sourceData = contacts.sources[@_sourceName] return callback(null, false) if not sourceData accessToken = sourceData.accessToken updateDate = sourceData.updateDate if not updateDate or not accessToken or DateUtils.getCurrentTimestamp() - updateDate < UPDATE_THRESHOLD return callback(null, false) locale = updateDate.locale @updateContacts(accessToken, contacts, locale, callback) updateContacts: (accessToken, contacts, locale, callback) => ### Update existing or create new contacts list from source. @param accessToken: string @param contacts: ContactListModel @param locale: string @param callback: function(err, updated: bool) ### updateDate = contacts.sources?[@_sourceName]?.updateDate onSourceContactsGot = (err, sourceContacts) => if err #проблемы с http-клиентом, сетью, гуглом или протух токен @_logger.warn("Error while contacts fetching: #{err}") contacts.removeAccessTocken(@_sourceName) return callback(null, true) #нужно сохранить удаленный токен и отдать те контакты, которые есть @_updateFromSourceContacts(accessToken, contacts, sourceContacts, (err, updated) => return callback(err) if err contacts.updateSourceData(@_sourceName, accessToken, locale) #если все действительно обновилось поменяем дату обновления и токен callback(null, updated) ) if updateDate @_contactFetcher.fetchContactsFromDate(accessToken, updateDate, locale, onSourceContactsGot) else @_contactFetcher.fetchAllContacts(accessToken, locale, onSourceContactsGot) _updateFromSourceContacts: (accessToken, contacts, sourceContacts, callback) -> ### Parse data for contacts source, update model. @param accessToken: string @param contacts: ContactListModel - model for updating @param sourceContacts: object - raw data from contacts provider. @param callback: function ### throw new NotImplementedError() SOURCE_NAME_GOOGLE = require('../../share/contacts/constants').SOURCE_NAME_GOOGLE class GoogleContactsFactory extends ContactsFactory ### Contacts fabric for Google. User pics (avatars) URLs can't be used directly in HTML because URLs should contain accessToken, we have to fetch avatars and serve requests to them ourselves. Directory structure: AVATAR_PATH->[contactsId -> [SHA1(contactEmail)...], ...] ### constructor: () -> @_internalAvatarsUrl = Conf.get('contacts').internalAvatarsUrl super(SOURCE_NAME_GOOGLE, GoogleContactsFetcher) _updateFromSourceContacts: (accessToken, contacts, sourceContacts, callback) -> @_contactFetcher.getUserContactsAvatarsPath(contacts.id, (err, avatarsPath) => @_logger.error("Can not get avatars path for #{contacts.id}", { err }) if err if sourceContacts.error or not sourceContacts.feed @_logger.error("Can not get source contacts data feed (Google)", { sourceContacts }) return callback(new Error('Can not get source contacts')) entry = sourceContacts.feed.entry return callback(null, accessToken != contacts.getSourceData(@_sourceName)?.accessToken) if not entry [toDelete, toFetchAvatar] = @_updateFromSourceContactFast(contacts, entry, avatarsPath) @_contactFetcher.removeContactsAvatar(avatarsPath, toDelete) onAvatarLoad = (email, fileName) => [contact, index] = contacts.getContact(email) contact.setAvatar(@_getInternalAvatarUrl(contacts.id, fileName)) if contact @_contactFetcher.fetchAvatars(accessToken, toFetchAvatar, avatarsPath, onAvatarLoad, () -> callback(null, true) ) ) _updateFromSourceContactFast: (contacts, entry, avatarsPath) -> ### Update model properties which don't require I/O calls. @param contacts: ContactListModel @param entry: array @param avatarPath: string @returns: [array - кто был удален, array - аватары] ### toDelete = [] toFetchAvatar = [] for sourceContact in entry email = @_getPrimaryEmail(sourceContact) continue if not email if @_isDeleted(sourceContact) toDelete.push(email) if contacts.removeContact(email) continue contact = contacts.getOrCreateContact(email, @_sourceName) continue if not contact contact.setName(@_getName(sourceContact)) continue if not avatarsPath avatarUrl = @_getAvatarUrl(sourceContact) toFetchAvatar.push({email, avatarUrl}) if avatarUrl return [toDelete, toFetchAvatar] _getPrimaryEmail: (sourceContact) -> ### Retrieve email. @param sourceContact: object @returns: string ### emails = sourceContact['gd$email'] return null if not emails for email in emails primaryEmail = if email.primary then email.address else null return null if /^activity\+.+@rizzoma.com$/.test(primaryEmail) #убираем наше мыло (ответы из почты на блипы) return primaryEmail return null _isDeleted: (sourceContact) -> ### Check if contact is deleted from al groups. @param sourceContact: object @returns: bool ### groupMembershipInfo = sourceContact['gContact$groupMembershipInfo'] return false if not groupMembershipInfo return _.all(groupMembershipInfo, (group) -> return group.deleted == 'true') _getName: (sourceContact) -> ### Retrieve contact name. @param sourceContact: object @returns: string ### fullName = sourceContact['gd$name']?['gd$fullName']?['$t'] return fullName if fullName givenName = sourceContact['gd$givenName']?['$t'] familyName = sourceContact['gd$familyName']?['$t'] fullName = if givenName then "#{givenName} " else '' fullName += if familyName then familyName else '' return fullName if fullName.length return null _getAvatarUrl: (sourceContact) -> ### Retrieve avatar URL @param sourceContact: object @returns: string ### links = sourceContact['link'] return null if not links for link in links return link.href if link.type == 'image/*' return null _getInternalAvatarUrl: (id, fileName) -> return "#{@_internalAvatarsUrl}#{id}/#{fileName}?r=#{Math.random()}" class FacebookContactsFactory extends ContactsFactory ### Contacts fabric for Facebook. ### constructor: () -> super('facebook', FacebookContactsFetcher) _updateFromSourceContacts: (accessToken, contacts, sourceContacts, callback) -> sourceContacts = sourceContacts.data if not sourceContacts or not sourceContacts.length return callback(null, accessToken != contacts.getSourceData(@_sourceName)?.accessToken) for sourceContact in sourceContacts email = @_getEmail(sourceContact) continue if not email contact = contacts.getOrCreateContact(email, @_sourceName) continue if not contact contact.setExternalId(@_getExternalId(sourceContact)) contact.setName(@_getName(sourceContact)) contact.setAvatar(@_getAvatarUrl(sourceContact)) callback(null, true) _getEmail: (sourceContact) -> username = sourceContact.username return if not username return "#{username}@facebook.com" _getExternalId: (sourceContact) -> return sourceContact.id _getName: (sourceContact) -> return sourceContact.name _getAvatarUrl: (sourceContact) -> username = sourceContact.username return if not username return "#{@_conf.apiUrl}/#{username}/picture" UserCouchProcessor = require('../user/couch_processor').UserCouchProcessor normalizeEmail = require('../user/utils').UserUtils.normalizeEmail SOURCE_NAME_MANUALLY = require('../../share/contacts/constants').SOURCE_NAME_MANUALLY LOCAL_UPDATE_THRESHOLD = 600 class LocalContactsFactory extends ContactsFactory ### Contacts fabric for "local" contacts: predefined support contacts and contacts added automatically when user invites someone to topic. ### constructor: () -> super('local', null) autoUpdateContacts: (contacts, callback) -> updateDate = contacts.sources?[@_sourceName]?.updateDate # minimum update frequency once per 10 minutes (client code fetches contacts twice: just after /topic/ page # loaded and 5 minutes later for additionally loaded/updated contacts or avatars) if updateDate and DateUtils.getCurrentTimestamp() - updateDate < LOCAL_UPDATE_THRESHOLD return callback(null, false) @updateContacts(contacts, callback) updateContacts: (contacts, callback) -> emails = (contact.email for contact in contacts.contacts when contact.source == SOURCE_NAME_MANUALLY) UserCouchProcessor.getByEmails(emails, (err, users) => return callback(null, false) if err updated = false for email in emails contact = users[normalizeEmail(email)]?.toContact() [contactToUpdate, index] = contacts.getContact(email) if contactToUpdate and contact updated |= contactToUpdate.setName(contact.name) updated |= contactToUpdate.setAvatar(contact.avatar) contacts.updateSourceData(@_sourceName) callback(null, updated) ) contactsFactories = 'google': new GoogleContactsFactory() 'facebook': new FacebookContactsFactory() 'local': new LocalContactsFactory() module.exports.ContactsFactory = (sourceName) -> return contactsFactories[sourceName]
112921
_ = require('underscore') async = require('async') Conf = require('../conf').Conf NotImplementedError = require('../../share/exceptions').NotImplementedError {GoogleContactsFetcher, FacebookContactsFetcher} = require('./contacts_fetcher') DateUtils = require('../utils/date_utils').DateUtils UPDATE_THRESHOLD = Conf.get('contacts').updateThreshold class ContactsFactory ### User contacts factory base class ### constructor: (@_sourceName, @_contactFetcher) -> @_conf = Conf.getContactsConfForSource(@_sourceName) @_logger = Conf.getLogger('contacts') getAccessToken: (req, res) -> @_contactFetcher.getAccessToken(req, res) onAuthCodeGot: (req, res, callback) -> @_contactFetcher.onAuthCodeGot(req, res, callback) autoUpdateContacts: (contacts, callback) -> sourceData = contacts.sources[@_sourceName] return callback(null, false) if not sourceData accessToken = sourceData.accessToken updateDate = sourceData.updateDate if not updateDate or not accessToken or DateUtils.getCurrentTimestamp() - updateDate < UPDATE_THRESHOLD return callback(null, false) locale = updateDate.locale @updateContacts(accessToken, contacts, locale, callback) updateContacts: (accessToken, contacts, locale, callback) => ### Update existing or create new contacts list from source. @param accessToken: string @param contacts: ContactListModel @param locale: string @param callback: function(err, updated: bool) ### updateDate = contacts.sources?[@_sourceName]?.updateDate onSourceContactsGot = (err, sourceContacts) => if err #проблемы с http-клиентом, сетью, гуглом или протух токен @_logger.warn("Error while contacts fetching: #{err}") contacts.removeAccessTocken(@_sourceName) return callback(null, true) #нужно сохранить удаленный токен и отдать те контакты, которые есть @_updateFromSourceContacts(accessToken, contacts, sourceContacts, (err, updated) => return callback(err) if err contacts.updateSourceData(@_sourceName, accessToken, locale) #если все действительно обновилось поменяем дату обновления и токен callback(null, updated) ) if updateDate @_contactFetcher.fetchContactsFromDate(accessToken, updateDate, locale, onSourceContactsGot) else @_contactFetcher.fetchAllContacts(accessToken, locale, onSourceContactsGot) _updateFromSourceContacts: (accessToken, contacts, sourceContacts, callback) -> ### Parse data for contacts source, update model. @param accessToken: string @param contacts: ContactListModel - model for updating @param sourceContacts: object - raw data from contacts provider. @param callback: function ### throw new NotImplementedError() SOURCE_NAME_GOOGLE = require('../../share/contacts/constants').SOURCE_NAME_GOOGLE class GoogleContactsFactory extends ContactsFactory ### Contacts fabric for Google. User pics (avatars) URLs can't be used directly in HTML because URLs should contain accessToken, we have to fetch avatars and serve requests to them ourselves. Directory structure: AVATAR_PATH->[contactsId -> [SHA1(contactEmail)...], ...] ### constructor: () -> @_internalAvatarsUrl = Conf.get('contacts').internalAvatarsUrl super(SOURCE_NAME_GOOGLE, GoogleContactsFetcher) _updateFromSourceContacts: (accessToken, contacts, sourceContacts, callback) -> @_contactFetcher.getUserContactsAvatarsPath(contacts.id, (err, avatarsPath) => @_logger.error("Can not get avatars path for #{contacts.id}", { err }) if err if sourceContacts.error or not sourceContacts.feed @_logger.error("Can not get source contacts data feed (Google)", { sourceContacts }) return callback(new Error('Can not get source contacts')) entry = sourceContacts.feed.entry return callback(null, accessToken != contacts.getSourceData(@_sourceName)?.accessToken) if not entry [toDelete, toFetchAvatar] = @_updateFromSourceContactFast(contacts, entry, avatarsPath) @_contactFetcher.removeContactsAvatar(avatarsPath, toDelete) onAvatarLoad = (email, fileName) => [contact, index] = contacts.getContact(email) contact.setAvatar(@_getInternalAvatarUrl(contacts.id, fileName)) if contact @_contactFetcher.fetchAvatars(accessToken, toFetchAvatar, avatarsPath, onAvatarLoad, () -> callback(null, true) ) ) _updateFromSourceContactFast: (contacts, entry, avatarsPath) -> ### Update model properties which don't require I/O calls. @param contacts: ContactListModel @param entry: array @param avatarPath: string @returns: [array - кто был удален, array - аватары] ### toDelete = [] toFetchAvatar = [] for sourceContact in entry email = @_getPrimaryEmail(sourceContact) continue if not email if @_isDeleted(sourceContact) toDelete.push(email) if contacts.removeContact(email) continue contact = contacts.getOrCreateContact(email, @_sourceName) continue if not contact contact.setName(@_getName(sourceContact)) continue if not avatarsPath avatarUrl = @_getAvatarUrl(sourceContact) toFetchAvatar.push({email, avatarUrl}) if avatarUrl return [toDelete, toFetchAvatar] _getPrimaryEmail: (sourceContact) -> ### Retrieve email. @param sourceContact: object @returns: string ### emails = sourceContact['gd$email'] return null if not emails for email in emails primaryEmail = if email.primary then email.address else null return null if /^activity\+.+@<EMAIL>.com$/.test(primaryEmail) #убираем наше мыло (ответы из почты на блипы) return primaryEmail return null _isDeleted: (sourceContact) -> ### Check if contact is deleted from al groups. @param sourceContact: object @returns: bool ### groupMembershipInfo = sourceContact['gContact$groupMembershipInfo'] return false if not groupMembershipInfo return _.all(groupMembershipInfo, (group) -> return group.deleted == 'true') _getName: (sourceContact) -> ### Retrieve contact name. @param sourceContact: object @returns: string ### fullName = sourceContact['gd$name']?['gd$fullName']?['$t'] return fullName if fullName givenName = sourceContact['gd$givenName']?['$t'] familyName = sourceContact['gd$familyName']?['$t'] fullName = if givenName then "#{givenName} " else '' fullName += if familyName then familyName else '' return fullName if fullName.length return null _getAvatarUrl: (sourceContact) -> ### Retrieve avatar URL @param sourceContact: object @returns: string ### links = sourceContact['link'] return null if not links for link in links return link.href if link.type == 'image/*' return null _getInternalAvatarUrl: (id, fileName) -> return "#{@_internalAvatarsUrl}#{id}/#{fileName}?r=#{Math.random()}" class FacebookContactsFactory extends ContactsFactory ### Contacts fabric for Facebook. ### constructor: () -> super('facebook', FacebookContactsFetcher) _updateFromSourceContacts: (accessToken, contacts, sourceContacts, callback) -> sourceContacts = sourceContacts.data if not sourceContacts or not sourceContacts.length return callback(null, accessToken != contacts.getSourceData(@_sourceName)?.accessToken) for sourceContact in sourceContacts email = @_getEmail(sourceContact) continue if not email contact = contacts.getOrCreateContact(email, @_sourceName) continue if not contact contact.setExternalId(@_getExternalId(sourceContact)) contact.setName(@_getName(sourceContact)) contact.setAvatar(@_getAvatarUrl(sourceContact)) callback(null, true) _getEmail: (sourceContact) -> username = sourceContact.username return if not username return <EMAIL>" _getExternalId: (sourceContact) -> return sourceContact.id _getName: (sourceContact) -> return sourceContact.name _getAvatarUrl: (sourceContact) -> username = sourceContact.username return if not username return "#{@_conf.apiUrl}/#{username}/picture" UserCouchProcessor = require('../user/couch_processor').UserCouchProcessor normalizeEmail = require('../user/utils').UserUtils.normalizeEmail SOURCE_NAME_MANUALLY = require('../../share/contacts/constants').SOURCE_NAME_MANUALLY LOCAL_UPDATE_THRESHOLD = 600 class LocalContactsFactory extends ContactsFactory ### Contacts fabric for "local" contacts: predefined support contacts and contacts added automatically when user invites someone to topic. ### constructor: () -> super('local', null) autoUpdateContacts: (contacts, callback) -> updateDate = contacts.sources?[@_sourceName]?.updateDate # minimum update frequency once per 10 minutes (client code fetches contacts twice: just after /topic/ page # loaded and 5 minutes later for additionally loaded/updated contacts or avatars) if updateDate and DateUtils.getCurrentTimestamp() - updateDate < LOCAL_UPDATE_THRESHOLD return callback(null, false) @updateContacts(contacts, callback) updateContacts: (contacts, callback) -> emails = (contact.email for contact in contacts.contacts when contact.source == SOURCE_NAME_MANUALLY) UserCouchProcessor.getByEmails(emails, (err, users) => return callback(null, false) if err updated = false for email in emails contact = users[normalizeEmail(email)]?.toContact() [contactToUpdate, index] = contacts.getContact(email) if contactToUpdate and contact updated |= contactToUpdate.setName(contact.name) updated |= contactToUpdate.setAvatar(contact.avatar) contacts.updateSourceData(@_sourceName) callback(null, updated) ) contactsFactories = 'google': new GoogleContactsFactory() 'facebook': new FacebookContactsFactory() 'local': new LocalContactsFactory() module.exports.ContactsFactory = (sourceName) -> return contactsFactories[sourceName]
true
_ = require('underscore') async = require('async') Conf = require('../conf').Conf NotImplementedError = require('../../share/exceptions').NotImplementedError {GoogleContactsFetcher, FacebookContactsFetcher} = require('./contacts_fetcher') DateUtils = require('../utils/date_utils').DateUtils UPDATE_THRESHOLD = Conf.get('contacts').updateThreshold class ContactsFactory ### User contacts factory base class ### constructor: (@_sourceName, @_contactFetcher) -> @_conf = Conf.getContactsConfForSource(@_sourceName) @_logger = Conf.getLogger('contacts') getAccessToken: (req, res) -> @_contactFetcher.getAccessToken(req, res) onAuthCodeGot: (req, res, callback) -> @_contactFetcher.onAuthCodeGot(req, res, callback) autoUpdateContacts: (contacts, callback) -> sourceData = contacts.sources[@_sourceName] return callback(null, false) if not sourceData accessToken = sourceData.accessToken updateDate = sourceData.updateDate if not updateDate or not accessToken or DateUtils.getCurrentTimestamp() - updateDate < UPDATE_THRESHOLD return callback(null, false) locale = updateDate.locale @updateContacts(accessToken, contacts, locale, callback) updateContacts: (accessToken, contacts, locale, callback) => ### Update existing or create new contacts list from source. @param accessToken: string @param contacts: ContactListModel @param locale: string @param callback: function(err, updated: bool) ### updateDate = contacts.sources?[@_sourceName]?.updateDate onSourceContactsGot = (err, sourceContacts) => if err #проблемы с http-клиентом, сетью, гуглом или протух токен @_logger.warn("Error while contacts fetching: #{err}") contacts.removeAccessTocken(@_sourceName) return callback(null, true) #нужно сохранить удаленный токен и отдать те контакты, которые есть @_updateFromSourceContacts(accessToken, contacts, sourceContacts, (err, updated) => return callback(err) if err contacts.updateSourceData(@_sourceName, accessToken, locale) #если все действительно обновилось поменяем дату обновления и токен callback(null, updated) ) if updateDate @_contactFetcher.fetchContactsFromDate(accessToken, updateDate, locale, onSourceContactsGot) else @_contactFetcher.fetchAllContacts(accessToken, locale, onSourceContactsGot) _updateFromSourceContacts: (accessToken, contacts, sourceContacts, callback) -> ### Parse data for contacts source, update model. @param accessToken: string @param contacts: ContactListModel - model for updating @param sourceContacts: object - raw data from contacts provider. @param callback: function ### throw new NotImplementedError() SOURCE_NAME_GOOGLE = require('../../share/contacts/constants').SOURCE_NAME_GOOGLE class GoogleContactsFactory extends ContactsFactory ### Contacts fabric for Google. User pics (avatars) URLs can't be used directly in HTML because URLs should contain accessToken, we have to fetch avatars and serve requests to them ourselves. Directory structure: AVATAR_PATH->[contactsId -> [SHA1(contactEmail)...], ...] ### constructor: () -> @_internalAvatarsUrl = Conf.get('contacts').internalAvatarsUrl super(SOURCE_NAME_GOOGLE, GoogleContactsFetcher) _updateFromSourceContacts: (accessToken, contacts, sourceContacts, callback) -> @_contactFetcher.getUserContactsAvatarsPath(contacts.id, (err, avatarsPath) => @_logger.error("Can not get avatars path for #{contacts.id}", { err }) if err if sourceContacts.error or not sourceContacts.feed @_logger.error("Can not get source contacts data feed (Google)", { sourceContacts }) return callback(new Error('Can not get source contacts')) entry = sourceContacts.feed.entry return callback(null, accessToken != contacts.getSourceData(@_sourceName)?.accessToken) if not entry [toDelete, toFetchAvatar] = @_updateFromSourceContactFast(contacts, entry, avatarsPath) @_contactFetcher.removeContactsAvatar(avatarsPath, toDelete) onAvatarLoad = (email, fileName) => [contact, index] = contacts.getContact(email) contact.setAvatar(@_getInternalAvatarUrl(contacts.id, fileName)) if contact @_contactFetcher.fetchAvatars(accessToken, toFetchAvatar, avatarsPath, onAvatarLoad, () -> callback(null, true) ) ) _updateFromSourceContactFast: (contacts, entry, avatarsPath) -> ### Update model properties which don't require I/O calls. @param contacts: ContactListModel @param entry: array @param avatarPath: string @returns: [array - кто был удален, array - аватары] ### toDelete = [] toFetchAvatar = [] for sourceContact in entry email = @_getPrimaryEmail(sourceContact) continue if not email if @_isDeleted(sourceContact) toDelete.push(email) if contacts.removeContact(email) continue contact = contacts.getOrCreateContact(email, @_sourceName) continue if not contact contact.setName(@_getName(sourceContact)) continue if not avatarsPath avatarUrl = @_getAvatarUrl(sourceContact) toFetchAvatar.push({email, avatarUrl}) if avatarUrl return [toDelete, toFetchAvatar] _getPrimaryEmail: (sourceContact) -> ### Retrieve email. @param sourceContact: object @returns: string ### emails = sourceContact['gd$email'] return null if not emails for email in emails primaryEmail = if email.primary then email.address else null return null if /^activity\+.+@PI:EMAIL:<EMAIL>END_PI.com$/.test(primaryEmail) #убираем наше мыло (ответы из почты на блипы) return primaryEmail return null _isDeleted: (sourceContact) -> ### Check if contact is deleted from al groups. @param sourceContact: object @returns: bool ### groupMembershipInfo = sourceContact['gContact$groupMembershipInfo'] return false if not groupMembershipInfo return _.all(groupMembershipInfo, (group) -> return group.deleted == 'true') _getName: (sourceContact) -> ### Retrieve contact name. @param sourceContact: object @returns: string ### fullName = sourceContact['gd$name']?['gd$fullName']?['$t'] return fullName if fullName givenName = sourceContact['gd$givenName']?['$t'] familyName = sourceContact['gd$familyName']?['$t'] fullName = if givenName then "#{givenName} " else '' fullName += if familyName then familyName else '' return fullName if fullName.length return null _getAvatarUrl: (sourceContact) -> ### Retrieve avatar URL @param sourceContact: object @returns: string ### links = sourceContact['link'] return null if not links for link in links return link.href if link.type == 'image/*' return null _getInternalAvatarUrl: (id, fileName) -> return "#{@_internalAvatarsUrl}#{id}/#{fileName}?r=#{Math.random()}" class FacebookContactsFactory extends ContactsFactory ### Contacts fabric for Facebook. ### constructor: () -> super('facebook', FacebookContactsFetcher) _updateFromSourceContacts: (accessToken, contacts, sourceContacts, callback) -> sourceContacts = sourceContacts.data if not sourceContacts or not sourceContacts.length return callback(null, accessToken != contacts.getSourceData(@_sourceName)?.accessToken) for sourceContact in sourceContacts email = @_getEmail(sourceContact) continue if not email contact = contacts.getOrCreateContact(email, @_sourceName) continue if not contact contact.setExternalId(@_getExternalId(sourceContact)) contact.setName(@_getName(sourceContact)) contact.setAvatar(@_getAvatarUrl(sourceContact)) callback(null, true) _getEmail: (sourceContact) -> username = sourceContact.username return if not username return PI:EMAIL:<EMAIL>END_PI" _getExternalId: (sourceContact) -> return sourceContact.id _getName: (sourceContact) -> return sourceContact.name _getAvatarUrl: (sourceContact) -> username = sourceContact.username return if not username return "#{@_conf.apiUrl}/#{username}/picture" UserCouchProcessor = require('../user/couch_processor').UserCouchProcessor normalizeEmail = require('../user/utils').UserUtils.normalizeEmail SOURCE_NAME_MANUALLY = require('../../share/contacts/constants').SOURCE_NAME_MANUALLY LOCAL_UPDATE_THRESHOLD = 600 class LocalContactsFactory extends ContactsFactory ### Contacts fabric for "local" contacts: predefined support contacts and contacts added automatically when user invites someone to topic. ### constructor: () -> super('local', null) autoUpdateContacts: (contacts, callback) -> updateDate = contacts.sources?[@_sourceName]?.updateDate # minimum update frequency once per 10 minutes (client code fetches contacts twice: just after /topic/ page # loaded and 5 minutes later for additionally loaded/updated contacts or avatars) if updateDate and DateUtils.getCurrentTimestamp() - updateDate < LOCAL_UPDATE_THRESHOLD return callback(null, false) @updateContacts(contacts, callback) updateContacts: (contacts, callback) -> emails = (contact.email for contact in contacts.contacts when contact.source == SOURCE_NAME_MANUALLY) UserCouchProcessor.getByEmails(emails, (err, users) => return callback(null, false) if err updated = false for email in emails contact = users[normalizeEmail(email)]?.toContact() [contactToUpdate, index] = contacts.getContact(email) if contactToUpdate and contact updated |= contactToUpdate.setName(contact.name) updated |= contactToUpdate.setAvatar(contact.avatar) contacts.updateSourceData(@_sourceName) callback(null, updated) ) contactsFactories = 'google': new GoogleContactsFactory() 'facebook': new FacebookContactsFactory() 'local': new LocalContactsFactory() module.exports.ContactsFactory = (sourceName) -> return contactsFactories[sourceName]
[ { "context": "s on: ['$http', 'ApiUrl', 'ClientUrl']\n#\n# @author Torstein Thune\n# @copyright 2016 Microbrew.it\nangular.module('Mi", "end": 119, "score": 0.9998782873153687, "start": 105, "tag": "NAME", "value": "Torstein Thune" } ]
app/api/Request.coffee
Microbrewit/microbrewit-recipe-calculator
0
# mbit/api/Request # # REST ($http) wrapper # # Depends on: ['$http', 'ApiUrl', 'ClientUrl'] # # @author Torstein Thune # @copyright 2016 Microbrew.it angular.module('Microbrewit').factory('mbit/api/Request', [ '$http' ($http) -> # GET: $http.jsonp wrapper # We are talking to the middleware-server so no tokens needed. # @param [Object] options get = (requestUrl, options = {}) -> if requestUrl.indexOf('?') is -1 requestUrl += '?callback=JSON_CALLBACK' else requestUrl += '&callback=JSON_CALLBACK' console.log "GET: #{requestUrl}" # Create promise promise = $http.get(requestUrl, {}) .error((data, status, headers) -> console.error "GET #{requestUrl} gave HTTP #{status}", data return { data: data status: status headers: headers } ) .then((response) -> returnData = response.data if options.returnProperty? and response.data[options.returnProperty]? returnData = response.data[options.returnProperty] return returnData ) return promise # POST: $http.post wrapper # We are talking to the middleware-server so no tokens needed. # @param [String] requestUrl The endpoint to POST to # @param [Object] payload The data structure to POST to server # @return [Promise] promise post = (requestUrl, payload) -> options = {} console.log "POST: #{requestUrl}" promise = $http.post(requestUrl, payload, options) .error((data, status, headers) -> console.error "POST #{requestUrl} gave HTTP #{status}", data return { data: data status: status headers: headers } ) .then((response) -> return response.data ) return promise # POST: $http.put wrapper # We are talking to the middleware-server so no tokens needed. # @param [String] requestUrl The endpoint to PUT to # @param [Object] payload The data structure to PUT to server # @return [Promise] promise put = (requestUrl, payload) -> options = {} console.log "PUT: #{requestUrl}" promise = $http.put(requestUrl, payload, options) .error((data, status, headers) -> console.error "PUT #{requestUrl} gave HTTP #{status}", data return { data: data status: status headers: headers } ) .then((response) -> return response.data ) return promise return { get: get post: post put: put } ])
91290
# mbit/api/Request # # REST ($http) wrapper # # Depends on: ['$http', 'ApiUrl', 'ClientUrl'] # # @author <NAME> # @copyright 2016 Microbrew.it angular.module('Microbrewit').factory('mbit/api/Request', [ '$http' ($http) -> # GET: $http.jsonp wrapper # We are talking to the middleware-server so no tokens needed. # @param [Object] options get = (requestUrl, options = {}) -> if requestUrl.indexOf('?') is -1 requestUrl += '?callback=JSON_CALLBACK' else requestUrl += '&callback=JSON_CALLBACK' console.log "GET: #{requestUrl}" # Create promise promise = $http.get(requestUrl, {}) .error((data, status, headers) -> console.error "GET #{requestUrl} gave HTTP #{status}", data return { data: data status: status headers: headers } ) .then((response) -> returnData = response.data if options.returnProperty? and response.data[options.returnProperty]? returnData = response.data[options.returnProperty] return returnData ) return promise # POST: $http.post wrapper # We are talking to the middleware-server so no tokens needed. # @param [String] requestUrl The endpoint to POST to # @param [Object] payload The data structure to POST to server # @return [Promise] promise post = (requestUrl, payload) -> options = {} console.log "POST: #{requestUrl}" promise = $http.post(requestUrl, payload, options) .error((data, status, headers) -> console.error "POST #{requestUrl} gave HTTP #{status}", data return { data: data status: status headers: headers } ) .then((response) -> return response.data ) return promise # POST: $http.put wrapper # We are talking to the middleware-server so no tokens needed. # @param [String] requestUrl The endpoint to PUT to # @param [Object] payload The data structure to PUT to server # @return [Promise] promise put = (requestUrl, payload) -> options = {} console.log "PUT: #{requestUrl}" promise = $http.put(requestUrl, payload, options) .error((data, status, headers) -> console.error "PUT #{requestUrl} gave HTTP #{status}", data return { data: data status: status headers: headers } ) .then((response) -> return response.data ) return promise return { get: get post: post put: put } ])
true
# mbit/api/Request # # REST ($http) wrapper # # Depends on: ['$http', 'ApiUrl', 'ClientUrl'] # # @author PI:NAME:<NAME>END_PI # @copyright 2016 Microbrew.it angular.module('Microbrewit').factory('mbit/api/Request', [ '$http' ($http) -> # GET: $http.jsonp wrapper # We are talking to the middleware-server so no tokens needed. # @param [Object] options get = (requestUrl, options = {}) -> if requestUrl.indexOf('?') is -1 requestUrl += '?callback=JSON_CALLBACK' else requestUrl += '&callback=JSON_CALLBACK' console.log "GET: #{requestUrl}" # Create promise promise = $http.get(requestUrl, {}) .error((data, status, headers) -> console.error "GET #{requestUrl} gave HTTP #{status}", data return { data: data status: status headers: headers } ) .then((response) -> returnData = response.data if options.returnProperty? and response.data[options.returnProperty]? returnData = response.data[options.returnProperty] return returnData ) return promise # POST: $http.post wrapper # We are talking to the middleware-server so no tokens needed. # @param [String] requestUrl The endpoint to POST to # @param [Object] payload The data structure to POST to server # @return [Promise] promise post = (requestUrl, payload) -> options = {} console.log "POST: #{requestUrl}" promise = $http.post(requestUrl, payload, options) .error((data, status, headers) -> console.error "POST #{requestUrl} gave HTTP #{status}", data return { data: data status: status headers: headers } ) .then((response) -> return response.data ) return promise # POST: $http.put wrapper # We are talking to the middleware-server so no tokens needed. # @param [String] requestUrl The endpoint to PUT to # @param [Object] payload The data structure to PUT to server # @return [Promise] promise put = (requestUrl, payload) -> options = {} console.log "PUT: #{requestUrl}" promise = $http.put(requestUrl, payload, options) .error((data, status, headers) -> console.error "PUT #{requestUrl} gave HTTP #{status}", data return { data: data status: status headers: headers } ) .then((response) -> return response.data ) return promise return { get: get post: post put: put } ])
[ { "context": "ised Event Emitter\n @link http://github.com/dragoscirjan/promised-events for the canonical source reposito", "end": 72, "score": 0.9996799230575562, "start": 60, "tag": "USERNAME", "value": "dragoscirjan" }, { "context": "source repository\n @link https://g...
src/promised-events.coffee
dragoscirjan/promised-events
1
### Promised Event Emitter @link http://github.com/dragoscirjan/promised-events for the canonical source repository @link https://github.com/dragoscirjan/promised-events/issues for issues and support @license https://github.com/dragoscirjan/promised-events/blob/master/LICENSE ### # http://code.tutsplus.com/tutorials/using-nodes-event-module--net-35941 # http://bahmutov.calepin.co/promisify-event-emitter.html # https://quickleft.com/blog/creating-and-publishing-a-node-js-module/ # https://github.com/brentertz/scapegoat ### @var {Object} @class EventEmitter ### EventEmitter = require('events').EventEmitter ### @var {Object} @class Q ### Q = require 'q' ### @var Function ### selfAddressed = require('self-addressed') isFunction = (arg) -> typeof arg == 'function' isNumber = (arg) -> typeof arg == 'number' isObject = (arg) -> typeof arg == 'object' and arg != null isUndefined = (arg) -> arg == undefined ### Promised Event Emitter based on an article written by Gleb Bahmutov @class PromisedEventEmitter @link https://github.com/Gozala/events @link https://github.com/bahmutov/self-addressed @link http://bahmutov.calepin.co/promisify-event-emitter.html @license MIT ### class SelfAdressedEventEmitter extends EventEmitter constructor: () -> throw new Error('This class is in development still') emit: (name, data) -> console.log 'emiting', name, data # override EventEmitter.prototype.emit function mailman = (address, envelope) -> SelfAdressedEventEmitter.__super__.emit.apply address, [name, envelope] # return a promise selfAddressed mailman, @, data # on: (name, func) -> # onSelfAddressedEnvelope = (envelope) -> # # we could get data from envelope if needed # result = () -> # selfAddressed envelope, result # # somehow deliver the envelope back to the caller .emit # PromisedEventEmitter.__super__.on.call @, name, onSelfAddressedEnvelope on: (name, func) -> console.log 'add onSelfAddressedEnvelope' onSelfAddressedEnvelope = (envelope) -> console.log 'exec onSelfAddressedEnvelope' if selfAddressed.is envelope # we could get data from envelope if needed result = () -> selfAddressed envelope, result # somehow deliver the envelope back to the caller .emit # envelope.replies = 1 # selfAddressed envelope SelfAdressedEventEmitter.__super__.on.apply @, [name, onSelfAddressedEnvelope] ### Promised Event Emitter based on the Q library written by Kristopher Michael Kowal @link https://github.com/Gozala/events @link https://github.com/kriskowal/q @license GPL v3 ### class QEventEmitter extends EventEmitter ### Override of EventEmitter emit method, in order to promisify any function/method called by an event. @see EventEmitter::emit() @return {Object} Promise ### emit: (type) -> defered = Q.defer() ### @see EventEmitter::emit() code ### er = undefined handler = undefined len = undefined args = undefined i = undefined listeners = undefined if !@_events @_events = {} # If there is no 'error' event listener then throw. if type == 'error' if !@_events.error or isObject(@_events.error) and !@_events.error.length er = arguments[1] if er instanceof Error throw er # Unhandled 'error' event throw TypeError('Uncaught, unspecified "error" event.') handler = @_events[type] if isUndefined(handler) return defered.reject new Error 'Undefined handler for this event' if isFunction(handler) args = if arguments.length > 0 then Array::slice.call(arguments, 1) else [] args.unshift(handler) Q.fcall.apply(@, args).then (val) -> defered.resolve val # handler.apply this, args else if isObject(handler) args = Array::slice.call(arguments, 1) args.unshift null listeners = handler.slice() len = listeners.length results = [] success = (val) -> results.push(val) if results.length == listeners.length defered.resolve results i = 0 # while i < len for listener in listeners args.shift() # args.unshift(listeners[i]) args.unshift(listener) fail = false Q.fcall.apply(@, args).then success, (err) -> fail = true defered.reject err if fail break # listeners[i].apply this, args i++ defered.promise module.exports = { SAPromisedEventEmitter: SelfAdressedEventEmitter QPromisedEventEmitter: QEventEmitter PromisedEventEmitter: QEventEmitter }
205034
### Promised Event Emitter @link http://github.com/dragoscirjan/promised-events for the canonical source repository @link https://github.com/dragoscirjan/promised-events/issues for issues and support @license https://github.com/dragoscirjan/promised-events/blob/master/LICENSE ### # http://code.tutsplus.com/tutorials/using-nodes-event-module--net-35941 # http://bahmutov.calepin.co/promisify-event-emitter.html # https://quickleft.com/blog/creating-and-publishing-a-node-js-module/ # https://github.com/brentertz/scapegoat ### @var {Object} @class EventEmitter ### EventEmitter = require('events').EventEmitter ### @var {Object} @class Q ### Q = require 'q' ### @var Function ### selfAddressed = require('self-addressed') isFunction = (arg) -> typeof arg == 'function' isNumber = (arg) -> typeof arg == 'number' isObject = (arg) -> typeof arg == 'object' and arg != null isUndefined = (arg) -> arg == undefined ### Promised Event Emitter based on an article written by <NAME> @class PromisedEventEmitter @link https://github.com/Gozala/events @link https://github.com/bahmutov/self-addressed @link http://bahmutov.calepin.co/promisify-event-emitter.html @license MIT ### class SelfAdressedEventEmitter extends EventEmitter constructor: () -> throw new Error('This class is in development still') emit: (name, data) -> console.log 'emiting', name, data # override EventEmitter.prototype.emit function mailman = (address, envelope) -> SelfAdressedEventEmitter.__super__.emit.apply address, [name, envelope] # return a promise selfAddressed mailman, @, data # on: (name, func) -> # onSelfAddressedEnvelope = (envelope) -> # # we could get data from envelope if needed # result = () -> # selfAddressed envelope, result # # somehow deliver the envelope back to the caller .emit # PromisedEventEmitter.__super__.on.call @, name, onSelfAddressedEnvelope on: (name, func) -> console.log 'add onSelfAddressedEnvelope' onSelfAddressedEnvelope = (envelope) -> console.log 'exec onSelfAddressedEnvelope' if selfAddressed.is envelope # we could get data from envelope if needed result = () -> selfAddressed envelope, result # somehow deliver the envelope back to the caller .emit # envelope.replies = 1 # selfAddressed envelope SelfAdressedEventEmitter.__super__.on.apply @, [name, onSelfAddressedEnvelope] ### Promised Event Emitter based on the Q library written by <NAME> @link https://github.com/Gozala/events @link https://github.com/kriskowal/q @license GPL v3 ### class QEventEmitter extends EventEmitter ### Override of EventEmitter emit method, in order to promisify any function/method called by an event. @see EventEmitter::emit() @return {Object} Promise ### emit: (type) -> defered = Q.defer() ### @see EventEmitter::emit() code ### er = undefined handler = undefined len = undefined args = undefined i = undefined listeners = undefined if !@_events @_events = {} # If there is no 'error' event listener then throw. if type == 'error' if !@_events.error or isObject(@_events.error) and !@_events.error.length er = arguments[1] if er instanceof Error throw er # Unhandled 'error' event throw TypeError('Uncaught, unspecified "error" event.') handler = @_events[type] if isUndefined(handler) return defered.reject new Error 'Undefined handler for this event' if isFunction(handler) args = if arguments.length > 0 then Array::slice.call(arguments, 1) else [] args.unshift(handler) Q.fcall.apply(@, args).then (val) -> defered.resolve val # handler.apply this, args else if isObject(handler) args = Array::slice.call(arguments, 1) args.unshift null listeners = handler.slice() len = listeners.length results = [] success = (val) -> results.push(val) if results.length == listeners.length defered.resolve results i = 0 # while i < len for listener in listeners args.shift() # args.unshift(listeners[i]) args.unshift(listener) fail = false Q.fcall.apply(@, args).then success, (err) -> fail = true defered.reject err if fail break # listeners[i].apply this, args i++ defered.promise module.exports = { SAPromisedEventEmitter: SelfAdressedEventEmitter QPromisedEventEmitter: QEventEmitter PromisedEventEmitter: QEventEmitter }
true
### Promised Event Emitter @link http://github.com/dragoscirjan/promised-events for the canonical source repository @link https://github.com/dragoscirjan/promised-events/issues for issues and support @license https://github.com/dragoscirjan/promised-events/blob/master/LICENSE ### # http://code.tutsplus.com/tutorials/using-nodes-event-module--net-35941 # http://bahmutov.calepin.co/promisify-event-emitter.html # https://quickleft.com/blog/creating-and-publishing-a-node-js-module/ # https://github.com/brentertz/scapegoat ### @var {Object} @class EventEmitter ### EventEmitter = require('events').EventEmitter ### @var {Object} @class Q ### Q = require 'q' ### @var Function ### selfAddressed = require('self-addressed') isFunction = (arg) -> typeof arg == 'function' isNumber = (arg) -> typeof arg == 'number' isObject = (arg) -> typeof arg == 'object' and arg != null isUndefined = (arg) -> arg == undefined ### Promised Event Emitter based on an article written by PI:NAME:<NAME>END_PI @class PromisedEventEmitter @link https://github.com/Gozala/events @link https://github.com/bahmutov/self-addressed @link http://bahmutov.calepin.co/promisify-event-emitter.html @license MIT ### class SelfAdressedEventEmitter extends EventEmitter constructor: () -> throw new Error('This class is in development still') emit: (name, data) -> console.log 'emiting', name, data # override EventEmitter.prototype.emit function mailman = (address, envelope) -> SelfAdressedEventEmitter.__super__.emit.apply address, [name, envelope] # return a promise selfAddressed mailman, @, data # on: (name, func) -> # onSelfAddressedEnvelope = (envelope) -> # # we could get data from envelope if needed # result = () -> # selfAddressed envelope, result # # somehow deliver the envelope back to the caller .emit # PromisedEventEmitter.__super__.on.call @, name, onSelfAddressedEnvelope on: (name, func) -> console.log 'add onSelfAddressedEnvelope' onSelfAddressedEnvelope = (envelope) -> console.log 'exec onSelfAddressedEnvelope' if selfAddressed.is envelope # we could get data from envelope if needed result = () -> selfAddressed envelope, result # somehow deliver the envelope back to the caller .emit # envelope.replies = 1 # selfAddressed envelope SelfAdressedEventEmitter.__super__.on.apply @, [name, onSelfAddressedEnvelope] ### Promised Event Emitter based on the Q library written by PI:NAME:<NAME>END_PI @link https://github.com/Gozala/events @link https://github.com/kriskowal/q @license GPL v3 ### class QEventEmitter extends EventEmitter ### Override of EventEmitter emit method, in order to promisify any function/method called by an event. @see EventEmitter::emit() @return {Object} Promise ### emit: (type) -> defered = Q.defer() ### @see EventEmitter::emit() code ### er = undefined handler = undefined len = undefined args = undefined i = undefined listeners = undefined if !@_events @_events = {} # If there is no 'error' event listener then throw. if type == 'error' if !@_events.error or isObject(@_events.error) and !@_events.error.length er = arguments[1] if er instanceof Error throw er # Unhandled 'error' event throw TypeError('Uncaught, unspecified "error" event.') handler = @_events[type] if isUndefined(handler) return defered.reject new Error 'Undefined handler for this event' if isFunction(handler) args = if arguments.length > 0 then Array::slice.call(arguments, 1) else [] args.unshift(handler) Q.fcall.apply(@, args).then (val) -> defered.resolve val # handler.apply this, args else if isObject(handler) args = Array::slice.call(arguments, 1) args.unshift null listeners = handler.slice() len = listeners.length results = [] success = (val) -> results.push(val) if results.length == listeners.length defered.resolve results i = 0 # while i < len for listener in listeners args.shift() # args.unshift(listeners[i]) args.unshift(listener) fail = false Q.fcall.apply(@, args).then success, (err) -> fail = true defered.reject err if fail break # listeners[i].apply this, args i++ defered.promise module.exports = { SAPromisedEventEmitter: SelfAdressedEventEmitter QPromisedEventEmitter: QEventEmitter PromisedEventEmitter: QEventEmitter }
[ { "context": " search string', () ->\n $scope.searchString = 'angry'\n $scope.searchStringChanged()\n $timeout.fl", "end": 1079, "score": 0.5822710990905762, "start": 1074, "tag": "PASSWORD", "value": "angry" } ]
spec/javascripts/controllers/navigation_controller_spec.coffee
jusso-dev/jila-mobile
6
describe 'NavigationController', () -> controller = null $scope = {} $rootScope = null $q = null $timeout = null deferred = null entryService = search_for: () -> deferred = $q.defer() deferred.promise beforeEach module('app') beforeEach inject ($controller, _$q_, _$rootScope_, _$httpBackend_, _$timeout_) -> $rootScope = _$rootScope_ $q = _$q_ $timeout = _$timeout_ _$httpBackend_.whenGET('partials/splash.html').respond(200); spyOn(entryService, 'search_for').and.callThrough() controller = $controller 'navigationController', $scope: $scope entryService: entryService $timeout: $timeout return it 'search should not be visible by default', () -> expect($scope.searchIsVisible).toBe false it 'should toggle visibility of the search', () -> $scope.toggleSearch() expect($scope.searchIsVisible).toBe true $scope.toggleSearch() expect($scope.searchIsVisible).toBe false it 'should retrieve entries matching the search string', () -> $scope.searchString = 'angry' $scope.searchStringChanged() $timeout.flush() entries = ['bili'] deferred.resolve entries $rootScope.$apply() expect($scope.entries).toEqual entries expect(entryService.search_for).toHaveBeenCalled() it 'should not search if the search string is empty', () -> $scope.searchStringChanged() expect(entryService.search_for).not.toHaveBeenCalled()
39454
describe 'NavigationController', () -> controller = null $scope = {} $rootScope = null $q = null $timeout = null deferred = null entryService = search_for: () -> deferred = $q.defer() deferred.promise beforeEach module('app') beforeEach inject ($controller, _$q_, _$rootScope_, _$httpBackend_, _$timeout_) -> $rootScope = _$rootScope_ $q = _$q_ $timeout = _$timeout_ _$httpBackend_.whenGET('partials/splash.html').respond(200); spyOn(entryService, 'search_for').and.callThrough() controller = $controller 'navigationController', $scope: $scope entryService: entryService $timeout: $timeout return it 'search should not be visible by default', () -> expect($scope.searchIsVisible).toBe false it 'should toggle visibility of the search', () -> $scope.toggleSearch() expect($scope.searchIsVisible).toBe true $scope.toggleSearch() expect($scope.searchIsVisible).toBe false it 'should retrieve entries matching the search string', () -> $scope.searchString = '<PASSWORD>' $scope.searchStringChanged() $timeout.flush() entries = ['bili'] deferred.resolve entries $rootScope.$apply() expect($scope.entries).toEqual entries expect(entryService.search_for).toHaveBeenCalled() it 'should not search if the search string is empty', () -> $scope.searchStringChanged() expect(entryService.search_for).not.toHaveBeenCalled()
true
describe 'NavigationController', () -> controller = null $scope = {} $rootScope = null $q = null $timeout = null deferred = null entryService = search_for: () -> deferred = $q.defer() deferred.promise beforeEach module('app') beforeEach inject ($controller, _$q_, _$rootScope_, _$httpBackend_, _$timeout_) -> $rootScope = _$rootScope_ $q = _$q_ $timeout = _$timeout_ _$httpBackend_.whenGET('partials/splash.html').respond(200); spyOn(entryService, 'search_for').and.callThrough() controller = $controller 'navigationController', $scope: $scope entryService: entryService $timeout: $timeout return it 'search should not be visible by default', () -> expect($scope.searchIsVisible).toBe false it 'should toggle visibility of the search', () -> $scope.toggleSearch() expect($scope.searchIsVisible).toBe true $scope.toggleSearch() expect($scope.searchIsVisible).toBe false it 'should retrieve entries matching the search string', () -> $scope.searchString = 'PI:PASSWORD:<PASSWORD>END_PI' $scope.searchStringChanged() $timeout.flush() entries = ['bili'] deferred.resolve entries $rootScope.$apply() expect($scope.entries).toEqual entries expect(entryService.search_for).toHaveBeenCalled() it 'should not search if the search string is empty', () -> $scope.searchStringChanged() expect(entryService.search_for).not.toHaveBeenCalled()
[ { "context": "# @file logging.coffee\n# @Copyright (c) 2016 Taylor Siviter\n# This source code is licensed under the MIT Lice", "end": 59, "score": 0.9997898936271667, "start": 45, "tag": "NAME", "value": "Taylor Siviter" } ]
src/util/log.coffee
siviter-t/lampyridae.coffee
4
# @file logging.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. Lampyridae.Log = {} Lampyridae.Log.default = () -> Lampyridae.Log.warn "Nothing to log!" Lampyridae.Log.error = (message) -> if arguments.length < 1 then @default() else console.error @wrap(message) Lampyridae.Log.info = (message) -> if @isLogging if arguments.length < 1 then @default() else console.info @wrap(message) Lampyridae.Log.isLogging = false Lampyridae.Log.out = (message) -> if @isLogging if arguments.length < 1 then @default() else console.log @wrap(message) Lampyridae.Log.prefix = "#{Lampyridae.name}: " Lampyridae.Log.warn = (message) -> if arguments.length < 1 then @default() else console.warn @wrap(message) Lampyridae.Log.wrap = (message) -> @prefix + message module.exports = Lampyridae.Log
207271
# @file logging.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. Lampyridae.Log = {} Lampyridae.Log.default = () -> Lampyridae.Log.warn "Nothing to log!" Lampyridae.Log.error = (message) -> if arguments.length < 1 then @default() else console.error @wrap(message) Lampyridae.Log.info = (message) -> if @isLogging if arguments.length < 1 then @default() else console.info @wrap(message) Lampyridae.Log.isLogging = false Lampyridae.Log.out = (message) -> if @isLogging if arguments.length < 1 then @default() else console.log @wrap(message) Lampyridae.Log.prefix = "#{Lampyridae.name}: " Lampyridae.Log.warn = (message) -> if arguments.length < 1 then @default() else console.warn @wrap(message) Lampyridae.Log.wrap = (message) -> @prefix + message module.exports = Lampyridae.Log
true
# @file logging.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. Lampyridae.Log = {} Lampyridae.Log.default = () -> Lampyridae.Log.warn "Nothing to log!" Lampyridae.Log.error = (message) -> if arguments.length < 1 then @default() else console.error @wrap(message) Lampyridae.Log.info = (message) -> if @isLogging if arguments.length < 1 then @default() else console.info @wrap(message) Lampyridae.Log.isLogging = false Lampyridae.Log.out = (message) -> if @isLogging if arguments.length < 1 then @default() else console.log @wrap(message) Lampyridae.Log.prefix = "#{Lampyridae.name}: " Lampyridae.Log.warn = (message) -> if arguments.length < 1 then @default() else console.warn @wrap(message) Lampyridae.Log.wrap = (message) -> @prefix + message module.exports = Lampyridae.Log
[ { "context": "howAlert: -> alert('Alert!!!') }\nmodel = { name: 'Jonas' }\n\nresult = Serenade.render('test', model, contr", "end": 202, "score": 0.9997546672821045, "start": 197, "tag": "NAME", "value": "Jonas" } ]
examples/bindings_and_callbacks.coffee
varvet/serenade.js
5
Serenade.view 'test', ''' div[id="hello-world"] h1 @name p a[event:click=showAlert href="#"] "Show the alert" ''' controller = { showAlert: -> alert('Alert!!!') } model = { name: 'Jonas' } result = Serenade.render('test', model, controller) window.onload = -> document.body.appendChild(result)
98512
Serenade.view 'test', ''' div[id="hello-world"] h1 @name p a[event:click=showAlert href="#"] "Show the alert" ''' controller = { showAlert: -> alert('Alert!!!') } model = { name: '<NAME>' } result = Serenade.render('test', model, controller) window.onload = -> document.body.appendChild(result)
true
Serenade.view 'test', ''' div[id="hello-world"] h1 @name p a[event:click=showAlert href="#"] "Show the alert" ''' controller = { showAlert: -> alert('Alert!!!') } model = { name: 'PI:NAME:<NAME>END_PI' } result = Serenade.render('test', model, controller) window.onload = -> document.body.appendChild(result)
[ { "context": "タントAIモモチです。\n\n以下の問い合わせがありましたので、回答をお願いします。\n\n\n質問者: {{userName}} さま ({{userEmailAddress}})\n\n\n■質問メール内容:\n---------", "end": 137, "score": 0.8574778437614441, "start": 129, "tag": "USERNAME", "value": "userName" }, { "context": "\n\n以下の問い合わせがありましたので、回答をお願いします。\n\n\n質問...
config/tmplOfFaqAutoReplyAnswer.cson
syu-tjsys/tjtest
0
## 二次受け窓口からの回答を転送・メール文面 "tmplOfFaqAutoReplyAnswer" : ''' {{dispatchTo}} さま アシスタントAIモモチです。 以下の問い合わせがありましたので、回答をお願いします。 質問者: {{userName}} さま ({{userEmailAddress}}) ■質問メール内容: ---------------------------------------------------- {{body}} ---------------------------------------------------- 以上です。 '''
178424
## 二次受け窓口からの回答を転送・メール文面 "tmplOfFaqAutoReplyAnswer" : ''' {{dispatchTo}} さま アシスタントAIモモチです。 以下の問い合わせがありましたので、回答をお願いします。 質問者: {{userName}} <NAME> ({{userEmailAddress}}) ■質問メール内容: ---------------------------------------------------- {{body}} ---------------------------------------------------- 以上です。 '''
true
## 二次受け窓口からの回答を転送・メール文面 "tmplOfFaqAutoReplyAnswer" : ''' {{dispatchTo}} さま アシスタントAIモモチです。 以下の問い合わせがありましたので、回答をお願いします。 質問者: {{userName}} PI:NAME:<NAME>END_PI ({{userEmailAddress}}) ■質問メール内容: ---------------------------------------------------- {{body}} ---------------------------------------------------- 以上です。 '''
[ { "context": "###*\n * Toast\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\n{Component} ", "end": 31, "score": 0.9994063377380371, "start": 25, "tag": "USERNAME", "value": "vfasky" }, { "context": "###*\n * Toast\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n...
src/coffee/toast.coffee
vfasky/mcore-weui
0
###* * Toast * @author vfasky <vfasky@gmail.com> ### 'use strict' {Component} = require 'mcore' # 单例 _toast = null _loadingArr = [0...12] class Toast extends Component constructor: (@el = document.body, @virtualEl = null)-> super @el, @virtualEl init: -> @render require('../tpl/toast.html'), show: false msg: '' loadingArr: _loadingArr show: (msg, type = 'toast')-> @set 'msg', msg @set 'type', type @set 'show', true hide: -> @set 'show', false Toast.loading = show: (msg = '数据加载中')-> _toast = new Toast() if !_toast _toast.show msg, 'loading' hide: -> _toast.hide() if _toast Toast.success = show: (msg)-> _toast = new Toast() if !_toast _toast.show msg hide: -> _toast.hide() if _toast module.exports = Toast
33887
###* * Toast * @author vfasky <<EMAIL>> ### 'use strict' {Component} = require 'mcore' # 单例 _toast = null _loadingArr = [0...12] class Toast extends Component constructor: (@el = document.body, @virtualEl = null)-> super @el, @virtualEl init: -> @render require('../tpl/toast.html'), show: false msg: '' loadingArr: _loadingArr show: (msg, type = 'toast')-> @set 'msg', msg @set 'type', type @set 'show', true hide: -> @set 'show', false Toast.loading = show: (msg = '数据加载中')-> _toast = new Toast() if !_toast _toast.show msg, 'loading' hide: -> _toast.hide() if _toast Toast.success = show: (msg)-> _toast = new Toast() if !_toast _toast.show msg hide: -> _toast.hide() if _toast module.exports = Toast
true
###* * Toast * @author vfasky <PI:EMAIL:<EMAIL>END_PI> ### 'use strict' {Component} = require 'mcore' # 单例 _toast = null _loadingArr = [0...12] class Toast extends Component constructor: (@el = document.body, @virtualEl = null)-> super @el, @virtualEl init: -> @render require('../tpl/toast.html'), show: false msg: '' loadingArr: _loadingArr show: (msg, type = 'toast')-> @set 'msg', msg @set 'type', type @set 'show', true hide: -> @set 'show', false Toast.loading = show: (msg = '数据加载中')-> _toast = new Toast() if !_toast _toast.show msg, 'loading' hide: -> _toast.hide() if _toast Toast.success = show: (msg)-> _toast = new Toast() if !_toast _toast.show msg hide: -> _toast.hide() if _toast module.exports = Toast
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999088048934937, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/react/modding-profile/events.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 * as React from 'react' import { div, h2, a, img } from 'react-dom-factories' el = React.createElement export class Events extends React.Component render: => div className: 'page-extra', h2 className: 'title title--page-extra', osu.trans('users.show.extra.events.title_longer') div className: 'modding-profile-list', if @props.events.length == 0 div className: 'modding-profile-list__empty', osu.trans('users.show.extra.none') else div className: 'beatmapset-events beatmapset-events--profile', [ for event in @props.events if !event.beatmapset continue cover = if event.beatmapset then event.beatmapset.covers.list else '' discussionId = event.comment?.beatmap_discussion_id ? null discussionLink = laroute.route('beatmapsets.discussion', beatmapset: event.beatmapset.id) if (discussionId) discussionLink = "#{discussionLink}#/#{discussionId}" div className: 'beatmapset-events__event', key: event.id, div className: 'beatmapset-event', a href: discussionLink, img className: 'beatmapset-activities__beatmapset-cover', src: cover, div className: "beatmapset-event__icon beatmapset-event__icon--#{_.kebabCase(event.type)} beatmapset-activities__event-icon-spacer" div {}, div className: "beatmapset-event__content" dangerouslySetInnerHTML: __html: osu.trans "beatmapset_events.event.#{@typeForTranslation(event)}", user: @props.users[event.user_id].username discussion: (if discussionId then "<a href='#{discussionLink}'>##{discussionId}</a>" else '') text: (if event.discussion?.starting_post? then _.truncate(event.discussion.starting_post.message, {length: 100}) else '[no preview]') div className: 'beatmap-discussion-post__info' dangerouslySetInnerHTML: __html: osu.timeago(event.created_at) a className: 'modding-profile-list__show-more' key: 'show-more' href: laroute.route('users.modding.events', {user: @props.user.id}), osu.trans('users.show.extra.events.show_more') ] typeForTranslation: (event) => if event.type == 'disqualify' && !_.isArray(event.comment) 'disqualify_legacy' event.type
33918
# 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 * as React from 'react' import { div, h2, a, img } from 'react-dom-factories' el = React.createElement export class Events extends React.Component render: => div className: 'page-extra', h2 className: 'title title--page-extra', osu.trans('users.show.extra.events.title_longer') div className: 'modding-profile-list', if @props.events.length == 0 div className: 'modding-profile-list__empty', osu.trans('users.show.extra.none') else div className: 'beatmapset-events beatmapset-events--profile', [ for event in @props.events if !event.beatmapset continue cover = if event.beatmapset then event.beatmapset.covers.list else '' discussionId = event.comment?.beatmap_discussion_id ? null discussionLink = laroute.route('beatmapsets.discussion', beatmapset: event.beatmapset.id) if (discussionId) discussionLink = "#{discussionLink}#/#{discussionId}" div className: 'beatmapset-events__event', key: event.id, div className: 'beatmapset-event', a href: discussionLink, img className: 'beatmapset-activities__beatmapset-cover', src: cover, div className: "beatmapset-event__icon beatmapset-event__icon--#{_.kebabCase(event.type)} beatmapset-activities__event-icon-spacer" div {}, div className: "beatmapset-event__content" dangerouslySetInnerHTML: __html: osu.trans "beatmapset_events.event.#{@typeForTranslation(event)}", user: @props.users[event.user_id].username discussion: (if discussionId then "<a href='#{discussionLink}'>##{discussionId}</a>" else '') text: (if event.discussion?.starting_post? then _.truncate(event.discussion.starting_post.message, {length: 100}) else '[no preview]') div className: 'beatmap-discussion-post__info' dangerouslySetInnerHTML: __html: osu.timeago(event.created_at) a className: 'modding-profile-list__show-more' key: 'show-more' href: laroute.route('users.modding.events', {user: @props.user.id}), osu.trans('users.show.extra.events.show_more') ] typeForTranslation: (event) => if event.type == 'disqualify' && !_.isArray(event.comment) 'disqualify_legacy' event.type
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 * as React from 'react' import { div, h2, a, img } from 'react-dom-factories' el = React.createElement export class Events extends React.Component render: => div className: 'page-extra', h2 className: 'title title--page-extra', osu.trans('users.show.extra.events.title_longer') div className: 'modding-profile-list', if @props.events.length == 0 div className: 'modding-profile-list__empty', osu.trans('users.show.extra.none') else div className: 'beatmapset-events beatmapset-events--profile', [ for event in @props.events if !event.beatmapset continue cover = if event.beatmapset then event.beatmapset.covers.list else '' discussionId = event.comment?.beatmap_discussion_id ? null discussionLink = laroute.route('beatmapsets.discussion', beatmapset: event.beatmapset.id) if (discussionId) discussionLink = "#{discussionLink}#/#{discussionId}" div className: 'beatmapset-events__event', key: event.id, div className: 'beatmapset-event', a href: discussionLink, img className: 'beatmapset-activities__beatmapset-cover', src: cover, div className: "beatmapset-event__icon beatmapset-event__icon--#{_.kebabCase(event.type)} beatmapset-activities__event-icon-spacer" div {}, div className: "beatmapset-event__content" dangerouslySetInnerHTML: __html: osu.trans "beatmapset_events.event.#{@typeForTranslation(event)}", user: @props.users[event.user_id].username discussion: (if discussionId then "<a href='#{discussionLink}'>##{discussionId}</a>" else '') text: (if event.discussion?.starting_post? then _.truncate(event.discussion.starting_post.message, {length: 100}) else '[no preview]') div className: 'beatmap-discussion-post__info' dangerouslySetInnerHTML: __html: osu.timeago(event.created_at) a className: 'modding-profile-list__show-more' key: 'show-more' href: laroute.route('users.modding.events', {user: @props.user.id}), osu.trans('users.show.extra.events.show_more') ] typeForTranslation: (event) => if event.type == 'disqualify' && !_.isArray(event.comment) 'disqualify_legacy' event.type
[ { "context": "###\nCopyright 2016 Clemens Nylandsted Klokmose, Aarhus University\n\nLicensed under the Apache Lic", "end": 46, "score": 0.9998939633369446, "start": 19, "tag": "NAME", "value": "Clemens Nylandsted Klokmose" }, { "context": "ll;\nmongoDB = null\nMongoClient.connect 'mo...
webstrates.coffee
kar288/ddd
0
### Copyright 2016 Clemens Nylandsted Klokmose, Aarhus University 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. ### https = require 'https' {Duplex} = require 'stream' express = require 'express' bodyParser = require 'body-parser' argv = require('optimist').argv livedb = require('livedb') livedbMongo = require 'livedb-mongo' ot = require 'livedb/lib/ot' jsonml = require 'jsonml-tools' http_auth = require 'http-auth' shortId = require 'shortid' WebSocketServer = require('ws').Server http = require 'http' passport = require 'passport' sessions = require "client-sessions" fs = require "fs" path = require "path" util = require "./util.coffee" try require 'heapdump' sharejs = require 'share' # Setup MongoDB connection for the session log MongoClient = require('mongodb').MongoClient sessionLog = null; mongoDB = null MongoClient.connect 'mongodb://127.0.0.1:27017/webstrate', (err, db) -> mongoDB = db MongoClient.connect 'mongodb://127.0.0.1:27017/log', (err, db) -> sessionLog = db.collection 'sessionLog' docsDirectory = '../VAST_Data_preprocessed/news-original-and-extra-raw-tables/' options = key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.crt'), requestCert: false, rejectUnauthorized: false # Create express app and websocket server app = express() app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.server = http.createServer app # app.server = https.createServer options, app wss = new WebSocketServer {server: app.server} router = express.Router(); httpsServer = https.createServer options, app # httpsServer.listen 443, "localhost" # Serve all static files (including source coffee files) app.use(express.static('images')); app.use('/client_src', express.static('client_src')); app.use(express.static('html')) app.use(express.static('webclient')) app.use(express.static(sharejs.scriptsDir)) app.use('/api', router); # Setup connection to MongoDB for ShareJS mongo = livedbMongo('mongodb://localhost:27017/webstrate?auto_reconnect', {safe:true}); # Setup livedb to use MongoDB as backend backend = livedb.client(mongo); # Setup ShareJS to use LiveDB as backend share = sharejs.server.createClient {backend} # Load configuration try fs.statSync 'config.json' catch err console.log "No config file present, creating one now." fs.writeFileSync 'config.json', "{}" config = JSON.parse(fs.readFileSync('config.json', 'utf8')) # Setup basic auth if configured in the config file if config.basic_auth? console.log "Basic auth enabled" basic = http_auth.basic { realm: config.basic_auth.realm, }, (username, password, callback) -> callback username == config.basic_auth.username and password == config.basic_auth.password app.use(http_auth.connect(basic)) # Setup Webstrates authentication if configured in the config file (currently only tested with GitHub as provider) auth = false permissionCache = {} if config.auth? secret = config.auth.secret app.use sessions { cookieName: 'session', secret: secret, duration: config.auth.cookieDuration } passport.serializeUser (user, done) -> done null, user passport.deserializeUser (obj, done) -> done null, obj # Iterate auth providers and initialize their strategies. for key of config.auth.providers PassportStrategy = require(config.auth.providers[key].node_module).Strategy passport.use new PassportStrategy config.auth.providers[key].config, (accessToken, refreshToken, profile, done) -> process.nextTick () -> return done null, profile app.use passport.initialize() app.use passport.session() # Setup login and callback URLs for provider of config.auth.providers app.get '/auth/'+provider, passport.authenticate(provider), (req, res) -> app.get '/auth/'+provider+'/callback', passport.authenticate(provider, { failureRedirect: '/auth/'+provider }), (req, res) -> res.redirect '/' console.log provider + " based authentication enabled" app.get '/auth/logout', (req, res) -> req.logout() res.redirect '/' auth = true # Decode a cookie into a JSON object decodeCookie = (cookie) -> if !cookie? return null if cookie['session']? return sessions.util.decode({cookieName: 'session', secret:secret}, cookie['session']).content; return null # Handle permissions for requests to ShareJS (over Websockets) share.use (request, next) -> if auth session = decodeCookie(util.parseCookie request.agent.stream.headers.cookie) if auth and session? and session.passport? and session.passport.user? provider = session.passport.user.provider username = session.passport.user.username else username = "anonymous" provider = "" userId = username + ":" + provider if request.action == "connect" #Log connection logItem = {sessionId: request.agent.sessionId, userId: userId, connectTime: request.agent.connectTime, remoteAddress: request.stream.remoteAddress} sessionLog.insert logItem, (err, db) -> if err throw err next() return if not permissionCache[userId]? # This happens if the client has not actually opened a page next("Forbidden") return permissions = permissionCache[userId] if request.action in ["fetch", "bulk fetch", "getOps", "query"] # Check for read permissions if request.docName? requestedWebstrate = request.docName else if request.requests? and request.requests.webstrates[0]? requestedWebstrate = request.requests.webstrates[0] if permissions[requestedWebstrate]? if permissions[requestedWebstrate].indexOf("r") > -1 next() return next('Forbidden') else if request.action == "submit" # Check for write permissions webstrate = request.docName if permissions[webstrate]? if permissions[webstrate].indexOf("w") > -1 next() return next('Forbidden') else if request.action == "delete" next("Forbidden") else next() generateTasks = (participant) -> array = [] array.push(i) for i in [0..81] when i != 4 and i != 10 i = array.length j = 0 tasks = [] while i -= 1 do (i) -> j = Math.floor(Math.random() * (i+1)); temp = array[i]; array[i] = array[j]; array[j] = temp; ids = [ {'prototype': 'toolbar', 'id': 'toolbar', 'task': 'A'}, {'prototype': 'editor', 'id': 'editor', 'task': 'B'}, {'prototype': 'editor', 'id': 'editor', 'task': 'C'}, {'prototype': 'toolbar', 'id': 'toolbar-sample', 'task': 'A'}, {'prototype': 'editor', 'id': 'editor-sample', 'task': 'B'}, {'prototype': 'editor', 'id': 'editor-sample', 'task': 'C'} ] imageCount = 6 for i in [0..5] do (i) -> task = 'localhost:7007/new?id=' + ids[i]['id'] + '-' + ids[i]['task'] + '&prototype=' + ids[i]['prototype'] + '&participant=' + participant + '&task=' + ids[i]['task'] + '&images=' if ids[i]['id'].endsWith('sample') task += '5,11' else for j in [0..imageCount - 1] do (j) -> task += (array[(i * imageCount + j)] + 1) if j < imageCount - 1 task += ',' tasks.push(task) # console.log(tasks) return tasks app.post '/log', (req, res) -> # console.log req.body # b = JSON.parse( req.body ) messages = req.body['messages[]'] if messages && messages.length && messages.join fileName = './logs' + req.body.name + '.txt' text = messages.join('\n') + '\n' fs.writeFile fileName, text, { flag: 'a' }, (err) -> if err console.log err res.json({'success': true}) else res.json({'success': false}) app.get '/generateTasks', (req, res) -> participant = req.query.participant tasks = generateTasks(participant) res.json({'tasks': tasks}) app.get '/generateTasksAll', (req, res) -> tasks = [] tasks = tasks.concat(generateTasks(i)) for i in [1..18] # console.log(tasks) res.json({'tasks': tasks}) app.get '/favicon.ico', (req, res) -> res.status(404).send("") app.get '/fileNames', (req, res) -> files = fs.readdirSync(docsDirectory) # console.log files res.json({'names': files}) app.get '/file', (req, res) -> if req.query.id? # console.log req.query.id name = docsDirectory + req.query.id fs.readFile name, 'utf8', (err, data) -> if err return res.json({error: err, text: ''}) data = data.replace(/\n/g, '<br>') data = data.replace(/\\/g, '"') res.json({text: data}) router.get '/names', (req, res) -> col = mongoDB.collection('webstrates') #Reading all Documents col.find().toArray (err, result) -> if err console.log err else ids = (obj._id for obj in result) res.json({ids: ids}) return getOcurrences = (string, substring, index, positions) -> if index >= string.length return positions nextIndex = string.substr(index).indexOf(substring) if nextIndex < 0 return positions nextIndex += index + substring.length positions.push(string.substr( Math.max(0, nextIndex - substring.length - 50), 100 )) return getOcurrences(string, substring, nextIndex, positions) router.get '/search', (req, res) -> ids = new Set if !req.query.query? res.json({ids: ids}) query = req.query.query done = 0 docs = fs.readdirSync(docsDirectory) terms = query.split(' ') terms.forEach (term, j) -> docs.forEach (doc, i) -> if !doc.endsWith('.txt') done++ return fs.readFile docsDirectory + doc, 'utf8', (err, data) -> done++ if err return if data.indexOf(term) >= 0 ids.add({ id: doc.replace('.txt', ''), positions: getOcurrences(data, term, 0, []) }) if done >= docs.length * terms.length res.json({ids: Array.from(ids)}) return # /new creates a new webstrate. # An id for the new webstrate can be provide, if not it is autogenerated # A reference to a prototype can be given, and then the new webstrate will be a copy of the given prototype app.get '/new', (req, res) -> if req.query.prototype? if req.query.id? webstrateId = req.query.id else webstrateId = shortId.generate() backend.fetch 'webstrates', req.query.prototype, (err, prototypeSnapshot) -> if req.query.v? if not req.query.v? or Number(prototypeSnapshot.v) < Number(req.query.v) or Number(req.query.v) == 0 version = prototypeSnapshot.v else version = req.query.v backend.getOps 'webstrates', req.query.prototype, 0, Number(version), (err, ops) -> ops.sort (a,b) -> return a.v - b.v data = {v:0} for op in ops ot.apply data, op backend.submit 'webstrates', webstrateId, {v:0, create:{type:'json0', data:data.data}}, (err) -> console.log err # if err? # res.status(409).send("Webstrate already exsist") # else res.redirect '/' + webstrateId else backend.submit 'webstrates', webstrateId, {v:0, create:{type:'json0', data:prototypeSnapshot.data}}, (err) -> extra = '?' if req.query.images extra += 'images=' + req.query.images if req.query.participant extra += '&participant=' + req.query.participant if req.query.task extra += '&task=' + req.query.task if req.query.task == 'B' || req.query.task == 'C' extra += '&mainEditor=1' console.log err # if err? # res.status(409).send("Webstrate already exsist") # else res.redirect '/' + webstrateId + extra else res.redirect '/' + shortId.generate() app.get '/backup', (req, res) -> col = mongoDB.collection('webstrates') col.find({'_id': {$ne: 'frontpage'}}).toArray (err, result) -> if err # console.log err else done = [] doneCount = 0 for obj in result do (obj)-> objId = obj._id backend.fetch 'webstrates', objId, (err, snapshot) -> if !snapshot # console.log objId doneCount++ return objId = snapshot.docName version = snapshot.v if !snapshot.data console.log 'no data' backend.submit 'webstrates', objId + '_9', {v:0, create:{type:'json0', data:snapshot.data}}, (err) -> doneCount++ if !err done.push objId else console.log 'error->', err if doneCount == result.length res.json({ids: done}) # console.log err return app.get '/restore', (req, res) -> col = mongoDB.collection('webstrates') # col.remove( { $and: [ { '_id': { $not: /_9/ } }, { '_id': { $ne: 'frontpage' } } ] },{ w: 0 } ) col.find({ '_id': /_9/ }).toArray (err, result) -> if err # console.log err else done = [] doneCount = 0 for obj in result do (obj)-> objId = obj._id backend.fetch 'webstrates', objId, (err, snapshot) -> if !snapshot doneCount++ return data = snapshot.data if !data console.log 'no data' backend.submit 'webstrates', objId.replace('_9', ''), {v:0, create:{type:'json0', data:data}}, (err) -> doneCount++ if !err done.push objId.replace('_9', '') else console.log 'error->', err if doneCount == result.length col.remove({'_id': /_9/}, { w: 0 }) res.json({ids: done}) return # Extract permission data from a webstrate getPermissionsForWebstrate = (username, provider, webstrate, snapshot) -> if snapshot.data? and snapshot.data[0]? and snapshot.data[0] == 'html' if snapshot.data[1]? and snapshot.data[1]['data-auth']? try authData = JSON.parse snapshot.data[1]['data-auth'] for user in authData if user.username == username && user.provider == provider return user.permissions catch error return "rw" # Get a webstrate. # ?v=10 will result in version 10 of the given webstrate (without the client loaded) # ?v=head gives the newest version of the webstrate (without the client loaded) # ?v returns the version number of head # When a previous version is fetched, the server will convert JsonML from the backend to HTML for the browser # GET on a webstrate will set the permissions in the permission cache for the given user, which is used when requests for ShareJS arrives over a websocket connection app.get '/:id', (req, res) -> if req.params.id.length > 0 session = req.session if auth and session? and session.passport? and session.passport.user? username = session.passport.user.username provider = session.passport.user.provider else username = "anonymous" provider = "" userId = username+":"+provider if req.query.v? backend.fetch 'webstrates', req.params.id, (err, snapshot) -> permissions = getPermissionsForWebstrate username, provider, req.params.id, snapshot if permissions.indexOf("r") < 0 res.send "Permission denied" return if Number(req.query.v) > 0 if snapshot.v < req.query.v res.status(404).send "'" + req.params.id + "' does not exist in version " + req.query.v + ". Highest version is " + snapshot.v + "." else backend.getOps 'webstrates', req.params.id, 0, Number(req.query.v), (err, ops) -> ops.sort (a,b) -> return a.v - b.v data = {v:0} for op in ops ot.apply data, op res.send (jsonml.toXML data.data, ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]) else if Number(req.query.v) < 0 version = snapshot.v + Number(req.query.v) if version < 0 res.send "'" + req.params.id + "' does not exist in version " + req.query.v + ". Highest version is " + snapshot.v + ".", 404 else backend.getOps 'webstrates', req.params.id, 0, version, (err, ops) -> ops.sort (a,b) -> return a.v - b.v data = {v:0} for op in ops ot.apply data, op res.send (jsonml.toXML data.data, ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]) else if req.query.v == 'head' # res.setHeader("Location", '/' + req.params.id) # res.sendFile __dirname+'/html/_client.html' res.send (jsonml.toXML snapshot.data, ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]) else if req.query.v == '' res.send "" + snapshot.v else res.send "Version must be a number or head" else if req.query.ops? backend.fetch 'webstrates', req.params.id, (err, snapshot) -> permissions = getPermissionsForWebstrate username, provider, req.params.id, snapshot if permissions.indexOf("r") < 0 res.send "Permission denied" return backend.getOps 'webstrates', req.params.id, 0, null, (err, ops) -> sessionsInOps = [] for op in ops if op.src in sessionsInOps continue sessionsInOps.push op.src userId = sessionLog.find({"sessionId": { $in: sessionsInOps }}).toArray (err, results) -> for op in ops for session in results if op.src == session.sessionId op.session = session res.send ops else if req.query.undo? backend.fetch 'webstrates', req.params.id, (err, snapshot) -> version = snapshot.v - 3 backend.getOps 'webstrates', req.params.id, 0, version, (err, ops) -> ops.sort (a,b) -> return a.v - b.v data = {v:0} for op in ops ot.apply data, op # console.log(data) # console.log snapshot mongoDB.collection 'webstrates', (err, collection) -> collection.update {'_id': snapshot.docName}, {$set: {'_v': data.v, '_data': data.data}}, (err, el) -> # console.log el mongoDB.collection 'webstrates_ops', (err, webstrates_ops) -> # console.log webstrates_ops # webstrates_ops.remove({'name': snapshot.docName, 'v': {$gt: version}}) (err, numberOfRemovedDocs) -> # # webstrate_ops.find({'name': snapshot.docName, 'v': {$gt: version}}).toArray (err, items) -> # console.log numberOfRemovedDocs res.send (jsonml.toXML data.data, ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]) else # console.log "ELSE" if not permissionCache[userId]? permissionCache[userId] = {} backend.fetch 'webstrates', req.params.id, (err, snapshot) -> webstrate = req.params.id # console.log webstrate # console.log snapshot permissions = getPermissionsForWebstrate username, provider, webstrate, snapshot permissionCache[userId][webstrate] = permissions if permissions.indexOf("r") < 0 res.send "Permission denied" return res.setHeader("Location", '/' + req.params.id) res.sendFile __dirname+'/html/_client.html' else res.redirect '/frontpage' app.get '/', (req, res) -> res.redirect '/frontpage' # Setup websocket connections and interaction with ShareJS wss.on 'connection', (client) -> stream = new Duplex objectMode:yes stream._write = (chunk, encoding, callback) -> try client.send JSON.stringify chunk catch error console.log error callback() stream._read = -> # Ignore. stream.headers = client.upgradeReq.headers stream.remoteAddress = client.upgradeReq.connection.remoteAddress client.on 'message', (data) -> stream.push JSON.parse data stream.on 'error', (msg) -> try client.close msg catch error console.log error client.on 'close', (reason) -> stream.push null stream.emit 'close' try client.close reason catch error console.log error stream.on 'end', -> try client.close() catch error console.log error # ... and give the stream to ShareJS. share.listen stream app.use '/_share', share.rest() port = argv.p or 7007 app.server.listen port console.log "Listening on http://localhost:#{port}/"
207912
### Copyright 2016 <NAME>, Aarhus University 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. ### https = require 'https' {Duplex} = require 'stream' express = require 'express' bodyParser = require 'body-parser' argv = require('optimist').argv livedb = require('livedb') livedbMongo = require 'livedb-mongo' ot = require 'livedb/lib/ot' jsonml = require 'jsonml-tools' http_auth = require 'http-auth' shortId = require 'shortid' WebSocketServer = require('ws').Server http = require 'http' passport = require 'passport' sessions = require "client-sessions" fs = require "fs" path = require "path" util = require "./util.coffee" try require 'heapdump' sharejs = require 'share' # Setup MongoDB connection for the session log MongoClient = require('mongodb').MongoClient sessionLog = null; mongoDB = null MongoClient.connect 'mongodb://127.0.0.1:27017/webstrate', (err, db) -> mongoDB = db MongoClient.connect 'mongodb://127.0.0.1:27017/log', (err, db) -> sessionLog = db.collection 'sessionLog' docsDirectory = '../VAST_Data_preprocessed/news-original-and-extra-raw-tables/' options = key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.crt'), requestCert: false, rejectUnauthorized: false # Create express app and websocket server app = express() app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.server = http.createServer app # app.server = https.createServer options, app wss = new WebSocketServer {server: app.server} router = express.Router(); httpsServer = https.createServer options, app # httpsServer.listen 443, "localhost" # Serve all static files (including source coffee files) app.use(express.static('images')); app.use('/client_src', express.static('client_src')); app.use(express.static('html')) app.use(express.static('webclient')) app.use(express.static(sharejs.scriptsDir)) app.use('/api', router); # Setup connection to MongoDB for ShareJS mongo = livedbMongo('mongodb://localhost:27017/webstrate?auto_reconnect', {safe:true}); # Setup livedb to use MongoDB as backend backend = livedb.client(mongo); # Setup ShareJS to use LiveDB as backend share = sharejs.server.createClient {backend} # Load configuration try fs.statSync 'config.json' catch err console.log "No config file present, creating one now." fs.writeFileSync 'config.json', "{}" config = JSON.parse(fs.readFileSync('config.json', 'utf8')) # Setup basic auth if configured in the config file if config.basic_auth? console.log "Basic auth enabled" basic = http_auth.basic { realm: config.basic_auth.realm, }, (username, password, callback) -> callback username == config.basic_auth.username and password == config.basic_auth.password app.use(http_auth.connect(basic)) # Setup Webstrates authentication if configured in the config file (currently only tested with GitHub as provider) auth = false permissionCache = {} if config.auth? secret = config.auth.secret app.use sessions { cookieName: 'session', secret: secret, duration: config.auth.cookieDuration } passport.serializeUser (user, done) -> done null, user passport.deserializeUser (obj, done) -> done null, obj # Iterate auth providers and initialize their strategies. for key of config.auth.providers PassportStrategy = require(config.auth.providers[key].node_module).Strategy passport.use new PassportStrategy config.auth.providers[key].config, (accessToken, refreshToken, profile, done) -> process.nextTick () -> return done null, profile app.use passport.initialize() app.use passport.session() # Setup login and callback URLs for provider of config.auth.providers app.get '/auth/'+provider, passport.authenticate(provider), (req, res) -> app.get '/auth/'+provider+'/callback', passport.authenticate(provider, { failureRedirect: '/auth/'+provider }), (req, res) -> res.redirect '/' console.log provider + " based authentication enabled" app.get '/auth/logout', (req, res) -> req.logout() res.redirect '/' auth = true # Decode a cookie into a JSON object decodeCookie = (cookie) -> if !cookie? return null if cookie['session']? return sessions.util.decode({cookieName: 'session', secret:secret}, cookie['session']).content; return null # Handle permissions for requests to ShareJS (over Websockets) share.use (request, next) -> if auth session = decodeCookie(util.parseCookie request.agent.stream.headers.cookie) if auth and session? and session.passport? and session.passport.user? provider = session.passport.user.provider username = session.passport.user.username else username = "anonymous" provider = "" userId = username + ":" + provider if request.action == "connect" #Log connection logItem = {sessionId: request.agent.sessionId, userId: userId, connectTime: request.agent.connectTime, remoteAddress: request.stream.remoteAddress} sessionLog.insert logItem, (err, db) -> if err throw err next() return if not permissionCache[userId]? # This happens if the client has not actually opened a page next("Forbidden") return permissions = permissionCache[userId] if request.action in ["fetch", "bulk fetch", "getOps", "query"] # Check for read permissions if request.docName? requestedWebstrate = request.docName else if request.requests? and request.requests.webstrates[0]? requestedWebstrate = request.requests.webstrates[0] if permissions[requestedWebstrate]? if permissions[requestedWebstrate].indexOf("r") > -1 next() return next('Forbidden') else if request.action == "submit" # Check for write permissions webstrate = request.docName if permissions[webstrate]? if permissions[webstrate].indexOf("w") > -1 next() return next('Forbidden') else if request.action == "delete" next("Forbidden") else next() generateTasks = (participant) -> array = [] array.push(i) for i in [0..81] when i != 4 and i != 10 i = array.length j = 0 tasks = [] while i -= 1 do (i) -> j = Math.floor(Math.random() * (i+1)); temp = array[i]; array[i] = array[j]; array[j] = temp; ids = [ {'prototype': 'toolbar', 'id': 'toolbar', 'task': 'A'}, {'prototype': 'editor', 'id': 'editor', 'task': 'B'}, {'prototype': 'editor', 'id': 'editor', 'task': 'C'}, {'prototype': 'toolbar', 'id': 'toolbar-sample', 'task': 'A'}, {'prototype': 'editor', 'id': 'editor-sample', 'task': 'B'}, {'prototype': 'editor', 'id': 'editor-sample', 'task': 'C'} ] imageCount = 6 for i in [0..5] do (i) -> task = 'localhost:7007/new?id=' + ids[i]['id'] + '-' + ids[i]['task'] + '&prototype=' + ids[i]['prototype'] + '&participant=' + participant + '&task=' + ids[i]['task'] + '&images=' if ids[i]['id'].endsWith('sample') task += '5,11' else for j in [0..imageCount - 1] do (j) -> task += (array[(i * imageCount + j)] + 1) if j < imageCount - 1 task += ',' tasks.push(task) # console.log(tasks) return tasks app.post '/log', (req, res) -> # console.log req.body # b = JSON.parse( req.body ) messages = req.body['messages[]'] if messages && messages.length && messages.join fileName = './logs' + req.body.name + '.txt' text = messages.join('\n') + '\n' fs.writeFile fileName, text, { flag: 'a' }, (err) -> if err console.log err res.json({'success': true}) else res.json({'success': false}) app.get '/generateTasks', (req, res) -> participant = req.query.participant tasks = generateTasks(participant) res.json({'tasks': tasks}) app.get '/generateTasksAll', (req, res) -> tasks = [] tasks = tasks.concat(generateTasks(i)) for i in [1..18] # console.log(tasks) res.json({'tasks': tasks}) app.get '/favicon.ico', (req, res) -> res.status(404).send("") app.get '/fileNames', (req, res) -> files = fs.readdirSync(docsDirectory) # console.log files res.json({'names': files}) app.get '/file', (req, res) -> if req.query.id? # console.log req.query.id name = docsDirectory + req.query.id fs.readFile name, 'utf8', (err, data) -> if err return res.json({error: err, text: ''}) data = data.replace(/\n/g, '<br>') data = data.replace(/\\/g, '"') res.json({text: data}) router.get '/names', (req, res) -> col = mongoDB.collection('webstrates') #Reading all Documents col.find().toArray (err, result) -> if err console.log err else ids = (obj._id for obj in result) res.json({ids: ids}) return getOcurrences = (string, substring, index, positions) -> if index >= string.length return positions nextIndex = string.substr(index).indexOf(substring) if nextIndex < 0 return positions nextIndex += index + substring.length positions.push(string.substr( Math.max(0, nextIndex - substring.length - 50), 100 )) return getOcurrences(string, substring, nextIndex, positions) router.get '/search', (req, res) -> ids = new Set if !req.query.query? res.json({ids: ids}) query = req.query.query done = 0 docs = fs.readdirSync(docsDirectory) terms = query.split(' ') terms.forEach (term, j) -> docs.forEach (doc, i) -> if !doc.endsWith('.txt') done++ return fs.readFile docsDirectory + doc, 'utf8', (err, data) -> done++ if err return if data.indexOf(term) >= 0 ids.add({ id: doc.replace('.txt', ''), positions: getOcurrences(data, term, 0, []) }) if done >= docs.length * terms.length res.json({ids: Array.from(ids)}) return # /new creates a new webstrate. # An id for the new webstrate can be provide, if not it is autogenerated # A reference to a prototype can be given, and then the new webstrate will be a copy of the given prototype app.get '/new', (req, res) -> if req.query.prototype? if req.query.id? webstrateId = req.query.id else webstrateId = shortId.generate() backend.fetch 'webstrates', req.query.prototype, (err, prototypeSnapshot) -> if req.query.v? if not req.query.v? or Number(prototypeSnapshot.v) < Number(req.query.v) or Number(req.query.v) == 0 version = prototypeSnapshot.v else version = req.query.v backend.getOps 'webstrates', req.query.prototype, 0, Number(version), (err, ops) -> ops.sort (a,b) -> return a.v - b.v data = {v:0} for op in ops ot.apply data, op backend.submit 'webstrates', webstrateId, {v:0, create:{type:'json0', data:data.data}}, (err) -> console.log err # if err? # res.status(409).send("Webstrate already exsist") # else res.redirect '/' + webstrateId else backend.submit 'webstrates', webstrateId, {v:0, create:{type:'json0', data:prototypeSnapshot.data}}, (err) -> extra = '?' if req.query.images extra += 'images=' + req.query.images if req.query.participant extra += '&participant=' + req.query.participant if req.query.task extra += '&task=' + req.query.task if req.query.task == 'B' || req.query.task == 'C' extra += '&mainEditor=1' console.log err # if err? # res.status(409).send("Webstrate already exsist") # else res.redirect '/' + webstrateId + extra else res.redirect '/' + shortId.generate() app.get '/backup', (req, res) -> col = mongoDB.collection('webstrates') col.find({'_id': {$ne: 'frontpage'}}).toArray (err, result) -> if err # console.log err else done = [] doneCount = 0 for obj in result do (obj)-> objId = obj._id backend.fetch 'webstrates', objId, (err, snapshot) -> if !snapshot # console.log objId doneCount++ return objId = snapshot.docName version = snapshot.v if !snapshot.data console.log 'no data' backend.submit 'webstrates', objId + '_9', {v:0, create:{type:'json0', data:snapshot.data}}, (err) -> doneCount++ if !err done.push objId else console.log 'error->', err if doneCount == result.length res.json({ids: done}) # console.log err return app.get '/restore', (req, res) -> col = mongoDB.collection('webstrates') # col.remove( { $and: [ { '_id': { $not: /_9/ } }, { '_id': { $ne: 'frontpage' } } ] },{ w: 0 } ) col.find({ '_id': /_9/ }).toArray (err, result) -> if err # console.log err else done = [] doneCount = 0 for obj in result do (obj)-> objId = obj._id backend.fetch 'webstrates', objId, (err, snapshot) -> if !snapshot doneCount++ return data = snapshot.data if !data console.log 'no data' backend.submit 'webstrates', objId.replace('_9', ''), {v:0, create:{type:'json0', data:data}}, (err) -> doneCount++ if !err done.push objId.replace('_9', '') else console.log 'error->', err if doneCount == result.length col.remove({'_id': /_9/}, { w: 0 }) res.json({ids: done}) return # Extract permission data from a webstrate getPermissionsForWebstrate = (username, provider, webstrate, snapshot) -> if snapshot.data? and snapshot.data[0]? and snapshot.data[0] == 'html' if snapshot.data[1]? and snapshot.data[1]['data-auth']? try authData = JSON.parse snapshot.data[1]['data-auth'] for user in authData if user.username == username && user.provider == provider return user.permissions catch error return "rw" # Get a webstrate. # ?v=10 will result in version 10 of the given webstrate (without the client loaded) # ?v=head gives the newest version of the webstrate (without the client loaded) # ?v returns the version number of head # When a previous version is fetched, the server will convert JsonML from the backend to HTML for the browser # GET on a webstrate will set the permissions in the permission cache for the given user, which is used when requests for ShareJS arrives over a websocket connection app.get '/:id', (req, res) -> if req.params.id.length > 0 session = req.session if auth and session? and session.passport? and session.passport.user? username = session.passport.user.username provider = session.passport.user.provider else username = "anonymous" provider = "" userId = username+":"+provider if req.query.v? backend.fetch 'webstrates', req.params.id, (err, snapshot) -> permissions = getPermissionsForWebstrate username, provider, req.params.id, snapshot if permissions.indexOf("r") < 0 res.send "Permission denied" return if Number(req.query.v) > 0 if snapshot.v < req.query.v res.status(404).send "'" + req.params.id + "' does not exist in version " + req.query.v + ". Highest version is " + snapshot.v + "." else backend.getOps 'webstrates', req.params.id, 0, Number(req.query.v), (err, ops) -> ops.sort (a,b) -> return a.v - b.v data = {v:0} for op in ops ot.apply data, op res.send (jsonml.toXML data.data, ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]) else if Number(req.query.v) < 0 version = snapshot.v + Number(req.query.v) if version < 0 res.send "'" + req.params.id + "' does not exist in version " + req.query.v + ". Highest version is " + snapshot.v + ".", 404 else backend.getOps 'webstrates', req.params.id, 0, version, (err, ops) -> ops.sort (a,b) -> return a.v - b.v data = {v:0} for op in ops ot.apply data, op res.send (jsonml.toXML data.data, ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]) else if req.query.v == 'head' # res.setHeader("Location", '/' + req.params.id) # res.sendFile __dirname+'/html/_client.html' res.send (jsonml.toXML snapshot.data, ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]) else if req.query.v == '' res.send "" + snapshot.v else res.send "Version must be a number or head" else if req.query.ops? backend.fetch 'webstrates', req.params.id, (err, snapshot) -> permissions = getPermissionsForWebstrate username, provider, req.params.id, snapshot if permissions.indexOf("r") < 0 res.send "Permission denied" return backend.getOps 'webstrates', req.params.id, 0, null, (err, ops) -> sessionsInOps = [] for op in ops if op.src in sessionsInOps continue sessionsInOps.push op.src userId = sessionLog.find({"sessionId": { $in: sessionsInOps }}).toArray (err, results) -> for op in ops for session in results if op.src == session.sessionId op.session = session res.send ops else if req.query.undo? backend.fetch 'webstrates', req.params.id, (err, snapshot) -> version = snapshot.v - 3 backend.getOps 'webstrates', req.params.id, 0, version, (err, ops) -> ops.sort (a,b) -> return a.v - b.v data = {v:0} for op in ops ot.apply data, op # console.log(data) # console.log snapshot mongoDB.collection 'webstrates', (err, collection) -> collection.update {'_id': snapshot.docName}, {$set: {'_v': data.v, '_data': data.data}}, (err, el) -> # console.log el mongoDB.collection 'webstrates_ops', (err, webstrates_ops) -> # console.log webstrates_ops # webstrates_ops.remove({'name': snapshot.docName, 'v': {$gt: version}}) (err, numberOfRemovedDocs) -> # # webstrate_ops.find({'name': snapshot.docName, 'v': {$gt: version}}).toArray (err, items) -> # console.log numberOfRemovedDocs res.send (jsonml.toXML data.data, ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]) else # console.log "ELSE" if not permissionCache[userId]? permissionCache[userId] = {} backend.fetch 'webstrates', req.params.id, (err, snapshot) -> webstrate = req.params.id # console.log webstrate # console.log snapshot permissions = getPermissionsForWebstrate username, provider, webstrate, snapshot permissionCache[userId][webstrate] = permissions if permissions.indexOf("r") < 0 res.send "Permission denied" return res.setHeader("Location", '/' + req.params.id) res.sendFile __dirname+'/html/_client.html' else res.redirect '/frontpage' app.get '/', (req, res) -> res.redirect '/frontpage' # Setup websocket connections and interaction with ShareJS wss.on 'connection', (client) -> stream = new Duplex objectMode:yes stream._write = (chunk, encoding, callback) -> try client.send JSON.stringify chunk catch error console.log error callback() stream._read = -> # Ignore. stream.headers = client.upgradeReq.headers stream.remoteAddress = client.upgradeReq.connection.remoteAddress client.on 'message', (data) -> stream.push JSON.parse data stream.on 'error', (msg) -> try client.close msg catch error console.log error client.on 'close', (reason) -> stream.push null stream.emit 'close' try client.close reason catch error console.log error stream.on 'end', -> try client.close() catch error console.log error # ... and give the stream to ShareJS. share.listen stream app.use '/_share', share.rest() port = argv.p or 7007 app.server.listen port console.log "Listening on http://localhost:#{port}/"
true
### Copyright 2016 PI:NAME:<NAME>END_PI, Aarhus University 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. ### https = require 'https' {Duplex} = require 'stream' express = require 'express' bodyParser = require 'body-parser' argv = require('optimist').argv livedb = require('livedb') livedbMongo = require 'livedb-mongo' ot = require 'livedb/lib/ot' jsonml = require 'jsonml-tools' http_auth = require 'http-auth' shortId = require 'shortid' WebSocketServer = require('ws').Server http = require 'http' passport = require 'passport' sessions = require "client-sessions" fs = require "fs" path = require "path" util = require "./util.coffee" try require 'heapdump' sharejs = require 'share' # Setup MongoDB connection for the session log MongoClient = require('mongodb').MongoClient sessionLog = null; mongoDB = null MongoClient.connect 'mongodb://127.0.0.1:27017/webstrate', (err, db) -> mongoDB = db MongoClient.connect 'mongodb://127.0.0.1:27017/log', (err, db) -> sessionLog = db.collection 'sessionLog' docsDirectory = '../VAST_Data_preprocessed/news-original-and-extra-raw-tables/' options = key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.crt'), requestCert: false, rejectUnauthorized: false # Create express app and websocket server app = express() app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.server = http.createServer app # app.server = https.createServer options, app wss = new WebSocketServer {server: app.server} router = express.Router(); httpsServer = https.createServer options, app # httpsServer.listen 443, "localhost" # Serve all static files (including source coffee files) app.use(express.static('images')); app.use('/client_src', express.static('client_src')); app.use(express.static('html')) app.use(express.static('webclient')) app.use(express.static(sharejs.scriptsDir)) app.use('/api', router); # Setup connection to MongoDB for ShareJS mongo = livedbMongo('mongodb://localhost:27017/webstrate?auto_reconnect', {safe:true}); # Setup livedb to use MongoDB as backend backend = livedb.client(mongo); # Setup ShareJS to use LiveDB as backend share = sharejs.server.createClient {backend} # Load configuration try fs.statSync 'config.json' catch err console.log "No config file present, creating one now." fs.writeFileSync 'config.json', "{}" config = JSON.parse(fs.readFileSync('config.json', 'utf8')) # Setup basic auth if configured in the config file if config.basic_auth? console.log "Basic auth enabled" basic = http_auth.basic { realm: config.basic_auth.realm, }, (username, password, callback) -> callback username == config.basic_auth.username and password == config.basic_auth.password app.use(http_auth.connect(basic)) # Setup Webstrates authentication if configured in the config file (currently only tested with GitHub as provider) auth = false permissionCache = {} if config.auth? secret = config.auth.secret app.use sessions { cookieName: 'session', secret: secret, duration: config.auth.cookieDuration } passport.serializeUser (user, done) -> done null, user passport.deserializeUser (obj, done) -> done null, obj # Iterate auth providers and initialize their strategies. for key of config.auth.providers PassportStrategy = require(config.auth.providers[key].node_module).Strategy passport.use new PassportStrategy config.auth.providers[key].config, (accessToken, refreshToken, profile, done) -> process.nextTick () -> return done null, profile app.use passport.initialize() app.use passport.session() # Setup login and callback URLs for provider of config.auth.providers app.get '/auth/'+provider, passport.authenticate(provider), (req, res) -> app.get '/auth/'+provider+'/callback', passport.authenticate(provider, { failureRedirect: '/auth/'+provider }), (req, res) -> res.redirect '/' console.log provider + " based authentication enabled" app.get '/auth/logout', (req, res) -> req.logout() res.redirect '/' auth = true # Decode a cookie into a JSON object decodeCookie = (cookie) -> if !cookie? return null if cookie['session']? return sessions.util.decode({cookieName: 'session', secret:secret}, cookie['session']).content; return null # Handle permissions for requests to ShareJS (over Websockets) share.use (request, next) -> if auth session = decodeCookie(util.parseCookie request.agent.stream.headers.cookie) if auth and session? and session.passport? and session.passport.user? provider = session.passport.user.provider username = session.passport.user.username else username = "anonymous" provider = "" userId = username + ":" + provider if request.action == "connect" #Log connection logItem = {sessionId: request.agent.sessionId, userId: userId, connectTime: request.agent.connectTime, remoteAddress: request.stream.remoteAddress} sessionLog.insert logItem, (err, db) -> if err throw err next() return if not permissionCache[userId]? # This happens if the client has not actually opened a page next("Forbidden") return permissions = permissionCache[userId] if request.action in ["fetch", "bulk fetch", "getOps", "query"] # Check for read permissions if request.docName? requestedWebstrate = request.docName else if request.requests? and request.requests.webstrates[0]? requestedWebstrate = request.requests.webstrates[0] if permissions[requestedWebstrate]? if permissions[requestedWebstrate].indexOf("r") > -1 next() return next('Forbidden') else if request.action == "submit" # Check for write permissions webstrate = request.docName if permissions[webstrate]? if permissions[webstrate].indexOf("w") > -1 next() return next('Forbidden') else if request.action == "delete" next("Forbidden") else next() generateTasks = (participant) -> array = [] array.push(i) for i in [0..81] when i != 4 and i != 10 i = array.length j = 0 tasks = [] while i -= 1 do (i) -> j = Math.floor(Math.random() * (i+1)); temp = array[i]; array[i] = array[j]; array[j] = temp; ids = [ {'prototype': 'toolbar', 'id': 'toolbar', 'task': 'A'}, {'prototype': 'editor', 'id': 'editor', 'task': 'B'}, {'prototype': 'editor', 'id': 'editor', 'task': 'C'}, {'prototype': 'toolbar', 'id': 'toolbar-sample', 'task': 'A'}, {'prototype': 'editor', 'id': 'editor-sample', 'task': 'B'}, {'prototype': 'editor', 'id': 'editor-sample', 'task': 'C'} ] imageCount = 6 for i in [0..5] do (i) -> task = 'localhost:7007/new?id=' + ids[i]['id'] + '-' + ids[i]['task'] + '&prototype=' + ids[i]['prototype'] + '&participant=' + participant + '&task=' + ids[i]['task'] + '&images=' if ids[i]['id'].endsWith('sample') task += '5,11' else for j in [0..imageCount - 1] do (j) -> task += (array[(i * imageCount + j)] + 1) if j < imageCount - 1 task += ',' tasks.push(task) # console.log(tasks) return tasks app.post '/log', (req, res) -> # console.log req.body # b = JSON.parse( req.body ) messages = req.body['messages[]'] if messages && messages.length && messages.join fileName = './logs' + req.body.name + '.txt' text = messages.join('\n') + '\n' fs.writeFile fileName, text, { flag: 'a' }, (err) -> if err console.log err res.json({'success': true}) else res.json({'success': false}) app.get '/generateTasks', (req, res) -> participant = req.query.participant tasks = generateTasks(participant) res.json({'tasks': tasks}) app.get '/generateTasksAll', (req, res) -> tasks = [] tasks = tasks.concat(generateTasks(i)) for i in [1..18] # console.log(tasks) res.json({'tasks': tasks}) app.get '/favicon.ico', (req, res) -> res.status(404).send("") app.get '/fileNames', (req, res) -> files = fs.readdirSync(docsDirectory) # console.log files res.json({'names': files}) app.get '/file', (req, res) -> if req.query.id? # console.log req.query.id name = docsDirectory + req.query.id fs.readFile name, 'utf8', (err, data) -> if err return res.json({error: err, text: ''}) data = data.replace(/\n/g, '<br>') data = data.replace(/\\/g, '"') res.json({text: data}) router.get '/names', (req, res) -> col = mongoDB.collection('webstrates') #Reading all Documents col.find().toArray (err, result) -> if err console.log err else ids = (obj._id for obj in result) res.json({ids: ids}) return getOcurrences = (string, substring, index, positions) -> if index >= string.length return positions nextIndex = string.substr(index).indexOf(substring) if nextIndex < 0 return positions nextIndex += index + substring.length positions.push(string.substr( Math.max(0, nextIndex - substring.length - 50), 100 )) return getOcurrences(string, substring, nextIndex, positions) router.get '/search', (req, res) -> ids = new Set if !req.query.query? res.json({ids: ids}) query = req.query.query done = 0 docs = fs.readdirSync(docsDirectory) terms = query.split(' ') terms.forEach (term, j) -> docs.forEach (doc, i) -> if !doc.endsWith('.txt') done++ return fs.readFile docsDirectory + doc, 'utf8', (err, data) -> done++ if err return if data.indexOf(term) >= 0 ids.add({ id: doc.replace('.txt', ''), positions: getOcurrences(data, term, 0, []) }) if done >= docs.length * terms.length res.json({ids: Array.from(ids)}) return # /new creates a new webstrate. # An id for the new webstrate can be provide, if not it is autogenerated # A reference to a prototype can be given, and then the new webstrate will be a copy of the given prototype app.get '/new', (req, res) -> if req.query.prototype? if req.query.id? webstrateId = req.query.id else webstrateId = shortId.generate() backend.fetch 'webstrates', req.query.prototype, (err, prototypeSnapshot) -> if req.query.v? if not req.query.v? or Number(prototypeSnapshot.v) < Number(req.query.v) or Number(req.query.v) == 0 version = prototypeSnapshot.v else version = req.query.v backend.getOps 'webstrates', req.query.prototype, 0, Number(version), (err, ops) -> ops.sort (a,b) -> return a.v - b.v data = {v:0} for op in ops ot.apply data, op backend.submit 'webstrates', webstrateId, {v:0, create:{type:'json0', data:data.data}}, (err) -> console.log err # if err? # res.status(409).send("Webstrate already exsist") # else res.redirect '/' + webstrateId else backend.submit 'webstrates', webstrateId, {v:0, create:{type:'json0', data:prototypeSnapshot.data}}, (err) -> extra = '?' if req.query.images extra += 'images=' + req.query.images if req.query.participant extra += '&participant=' + req.query.participant if req.query.task extra += '&task=' + req.query.task if req.query.task == 'B' || req.query.task == 'C' extra += '&mainEditor=1' console.log err # if err? # res.status(409).send("Webstrate already exsist") # else res.redirect '/' + webstrateId + extra else res.redirect '/' + shortId.generate() app.get '/backup', (req, res) -> col = mongoDB.collection('webstrates') col.find({'_id': {$ne: 'frontpage'}}).toArray (err, result) -> if err # console.log err else done = [] doneCount = 0 for obj in result do (obj)-> objId = obj._id backend.fetch 'webstrates', objId, (err, snapshot) -> if !snapshot # console.log objId doneCount++ return objId = snapshot.docName version = snapshot.v if !snapshot.data console.log 'no data' backend.submit 'webstrates', objId + '_9', {v:0, create:{type:'json0', data:snapshot.data}}, (err) -> doneCount++ if !err done.push objId else console.log 'error->', err if doneCount == result.length res.json({ids: done}) # console.log err return app.get '/restore', (req, res) -> col = mongoDB.collection('webstrates') # col.remove( { $and: [ { '_id': { $not: /_9/ } }, { '_id': { $ne: 'frontpage' } } ] },{ w: 0 } ) col.find({ '_id': /_9/ }).toArray (err, result) -> if err # console.log err else done = [] doneCount = 0 for obj in result do (obj)-> objId = obj._id backend.fetch 'webstrates', objId, (err, snapshot) -> if !snapshot doneCount++ return data = snapshot.data if !data console.log 'no data' backend.submit 'webstrates', objId.replace('_9', ''), {v:0, create:{type:'json0', data:data}}, (err) -> doneCount++ if !err done.push objId.replace('_9', '') else console.log 'error->', err if doneCount == result.length col.remove({'_id': /_9/}, { w: 0 }) res.json({ids: done}) return # Extract permission data from a webstrate getPermissionsForWebstrate = (username, provider, webstrate, snapshot) -> if snapshot.data? and snapshot.data[0]? and snapshot.data[0] == 'html' if snapshot.data[1]? and snapshot.data[1]['data-auth']? try authData = JSON.parse snapshot.data[1]['data-auth'] for user in authData if user.username == username && user.provider == provider return user.permissions catch error return "rw" # Get a webstrate. # ?v=10 will result in version 10 of the given webstrate (without the client loaded) # ?v=head gives the newest version of the webstrate (without the client loaded) # ?v returns the version number of head # When a previous version is fetched, the server will convert JsonML from the backend to HTML for the browser # GET on a webstrate will set the permissions in the permission cache for the given user, which is used when requests for ShareJS arrives over a websocket connection app.get '/:id', (req, res) -> if req.params.id.length > 0 session = req.session if auth and session? and session.passport? and session.passport.user? username = session.passport.user.username provider = session.passport.user.provider else username = "anonymous" provider = "" userId = username+":"+provider if req.query.v? backend.fetch 'webstrates', req.params.id, (err, snapshot) -> permissions = getPermissionsForWebstrate username, provider, req.params.id, snapshot if permissions.indexOf("r") < 0 res.send "Permission denied" return if Number(req.query.v) > 0 if snapshot.v < req.query.v res.status(404).send "'" + req.params.id + "' does not exist in version " + req.query.v + ". Highest version is " + snapshot.v + "." else backend.getOps 'webstrates', req.params.id, 0, Number(req.query.v), (err, ops) -> ops.sort (a,b) -> return a.v - b.v data = {v:0} for op in ops ot.apply data, op res.send (jsonml.toXML data.data, ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]) else if Number(req.query.v) < 0 version = snapshot.v + Number(req.query.v) if version < 0 res.send "'" + req.params.id + "' does not exist in version " + req.query.v + ". Highest version is " + snapshot.v + ".", 404 else backend.getOps 'webstrates', req.params.id, 0, version, (err, ops) -> ops.sort (a,b) -> return a.v - b.v data = {v:0} for op in ops ot.apply data, op res.send (jsonml.toXML data.data, ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]) else if req.query.v == 'head' # res.setHeader("Location", '/' + req.params.id) # res.sendFile __dirname+'/html/_client.html' res.send (jsonml.toXML snapshot.data, ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]) else if req.query.v == '' res.send "" + snapshot.v else res.send "Version must be a number or head" else if req.query.ops? backend.fetch 'webstrates', req.params.id, (err, snapshot) -> permissions = getPermissionsForWebstrate username, provider, req.params.id, snapshot if permissions.indexOf("r") < 0 res.send "Permission denied" return backend.getOps 'webstrates', req.params.id, 0, null, (err, ops) -> sessionsInOps = [] for op in ops if op.src in sessionsInOps continue sessionsInOps.push op.src userId = sessionLog.find({"sessionId": { $in: sessionsInOps }}).toArray (err, results) -> for op in ops for session in results if op.src == session.sessionId op.session = session res.send ops else if req.query.undo? backend.fetch 'webstrates', req.params.id, (err, snapshot) -> version = snapshot.v - 3 backend.getOps 'webstrates', req.params.id, 0, version, (err, ops) -> ops.sort (a,b) -> return a.v - b.v data = {v:0} for op in ops ot.apply data, op # console.log(data) # console.log snapshot mongoDB.collection 'webstrates', (err, collection) -> collection.update {'_id': snapshot.docName}, {$set: {'_v': data.v, '_data': data.data}}, (err, el) -> # console.log el mongoDB.collection 'webstrates_ops', (err, webstrates_ops) -> # console.log webstrates_ops # webstrates_ops.remove({'name': snapshot.docName, 'v': {$gt: version}}) (err, numberOfRemovedDocs) -> # # webstrate_ops.find({'name': snapshot.docName, 'v': {$gt: version}}).toArray (err, items) -> # console.log numberOfRemovedDocs res.send (jsonml.toXML data.data, ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]) else # console.log "ELSE" if not permissionCache[userId]? permissionCache[userId] = {} backend.fetch 'webstrates', req.params.id, (err, snapshot) -> webstrate = req.params.id # console.log webstrate # console.log snapshot permissions = getPermissionsForWebstrate username, provider, webstrate, snapshot permissionCache[userId][webstrate] = permissions if permissions.indexOf("r") < 0 res.send "Permission denied" return res.setHeader("Location", '/' + req.params.id) res.sendFile __dirname+'/html/_client.html' else res.redirect '/frontpage' app.get '/', (req, res) -> res.redirect '/frontpage' # Setup websocket connections and interaction with ShareJS wss.on 'connection', (client) -> stream = new Duplex objectMode:yes stream._write = (chunk, encoding, callback) -> try client.send JSON.stringify chunk catch error console.log error callback() stream._read = -> # Ignore. stream.headers = client.upgradeReq.headers stream.remoteAddress = client.upgradeReq.connection.remoteAddress client.on 'message', (data) -> stream.push JSON.parse data stream.on 'error', (msg) -> try client.close msg catch error console.log error client.on 'close', (reason) -> stream.push null stream.emit 'close' try client.close reason catch error console.log error stream.on 'end', -> try client.close() catch error console.log error # ... and give the stream to ShareJS. share.listen stream app.use '/_share', share.rest() port = argv.p or 7007 app.server.listen port console.log "Listening on http://localhost:#{port}/"
[ { "context": "\"items\": [\n {\n \"name\": \"Horse\",\n \"quantity\": 1,\n ", "end": 1803, "score": 0.9174322485923767, "start": 1798, "tag": "NAME", "value": "Horse" }, { "context": "io=basic.apib, katt_transaction=2\n{\n \"...
test/katt-player.fixtures.coffee
klarna/katt-player
2
### Copyright 2013 Klarna AB 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. ### { _ mockery } = require './_utils' exports.run = {} exports.run.before = () -> # Mock file system fs = require 'fs' fsMock = _.cloneDeep fs fsMock.readFileSync = (filename) -> return fsTest1 if filename is '/mock/basic.apib' fs.readFileSync.apply fs, arguments fsMock.existsSync = (filename) -> return true if filename is '/mock/basic.apib' fs.existsSync.apply fs, arguments fsMock.statSync = (filename) -> if filename is '/mock/basic.apib' return { isDirectory: () -> false isFile: () -> true } fs.statSync.apply fs, arguments mockery.registerMock 'fs', fsMock mockery.enable useCleanCache: true warnOnUnregistered: false { katt: require 'katt-js' kattPlayer: require '../' } exports.run.after = () -> mockery.disable() mockery.deregisterAll() fsTest1 = """--- Test 1 --- --- Some description --- # Step 1 The merchant creates a new example object on our server, and we respond with the location of the created example. POST /step1 > Accept: application/json > Content-Type: application/json > Cookie: katt_scenario=basic.apib { "cart": { "items": [ { "name": "Horse", "quantity": 1, "unit_price": 4495000 }, { "name": "Battery", "quantity": 4, "unit_price": 1000 }, { "name": "Staple", "quantity": 1, "unit_price": 12000 } ] } } < 201 < Location: {{>example_uri}} # Step 2 The client (customer) fetches the created resource data. GET {{<example_uri}} > Accept: application/json > Cookie: katt_scenario=basic.apib, katt_transaction=1 < 200 < Content-Type: application/json { "required_fields": [ "email" ], "cart": "{{_}}" } # Step 3 The customer submits an e-mail address in the form. POST {{<example_uri}}/step3 > Accept: application/json > Content-Type: application/json > Cookie: katt_scenario=basic.apib, katt_transaction=2 { "email": "test-customer@foo.klarna.com" } < 200 < Content-Type: application/json { "required_fields": [ "password" ], "cart": "{{_}}" } # Step 4 The customer submits the form again, this time also with his password. We inform him that payment is required. POST {{<example_uri}}/step4 > Accept: application/json > Content-Type: application/json > Cookie: katt_scenario=basic.apib, katt_transaction=3 { "email": "test-customer@foo.klarna.com", "password": "correct horse battery staple" } < 402 < Content-Type: application/json { "error": "payment required" } """
146167
### Copyright 2013 Klarna AB 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. ### { _ mockery } = require './_utils' exports.run = {} exports.run.before = () -> # Mock file system fs = require 'fs' fsMock = _.cloneDeep fs fsMock.readFileSync = (filename) -> return fsTest1 if filename is '/mock/basic.apib' fs.readFileSync.apply fs, arguments fsMock.existsSync = (filename) -> return true if filename is '/mock/basic.apib' fs.existsSync.apply fs, arguments fsMock.statSync = (filename) -> if filename is '/mock/basic.apib' return { isDirectory: () -> false isFile: () -> true } fs.statSync.apply fs, arguments mockery.registerMock 'fs', fsMock mockery.enable useCleanCache: true warnOnUnregistered: false { katt: require 'katt-js' kattPlayer: require '../' } exports.run.after = () -> mockery.disable() mockery.deregisterAll() fsTest1 = """--- Test 1 --- --- Some description --- # Step 1 The merchant creates a new example object on our server, and we respond with the location of the created example. POST /step1 > Accept: application/json > Content-Type: application/json > Cookie: katt_scenario=basic.apib { "cart": { "items": [ { "name": "<NAME>", "quantity": 1, "unit_price": 4495000 }, { "name": "Battery", "quantity": 4, "unit_price": 1000 }, { "name": "Staple", "quantity": 1, "unit_price": 12000 } ] } } < 201 < Location: {{>example_uri}} # Step 2 The client (customer) fetches the created resource data. GET {{<example_uri}} > Accept: application/json > Cookie: katt_scenario=basic.apib, katt_transaction=1 < 200 < Content-Type: application/json { "required_fields": [ "email" ], "cart": "{{_}}" } # Step 3 The customer submits an e-mail address in the form. POST {{<example_uri}}/step3 > Accept: application/json > Content-Type: application/json > Cookie: katt_scenario=basic.apib, katt_transaction=2 { "email": "<EMAIL>" } < 200 < Content-Type: application/json { "required_fields": [ "password" ], "cart": "{{_}}" } # Step 4 The customer submits the form again, this time also with his password. We inform him that payment is required. POST {{<example_uri}}/step4 > Accept: application/json > Content-Type: application/json > Cookie: katt_scenario=basic.apib, katt_transaction=3 { "email": "<EMAIL>", "password": "<PASSWORD>" } < 402 < Content-Type: application/json { "error": "payment required" } """
true
### Copyright 2013 Klarna AB 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. ### { _ mockery } = require './_utils' exports.run = {} exports.run.before = () -> # Mock file system fs = require 'fs' fsMock = _.cloneDeep fs fsMock.readFileSync = (filename) -> return fsTest1 if filename is '/mock/basic.apib' fs.readFileSync.apply fs, arguments fsMock.existsSync = (filename) -> return true if filename is '/mock/basic.apib' fs.existsSync.apply fs, arguments fsMock.statSync = (filename) -> if filename is '/mock/basic.apib' return { isDirectory: () -> false isFile: () -> true } fs.statSync.apply fs, arguments mockery.registerMock 'fs', fsMock mockery.enable useCleanCache: true warnOnUnregistered: false { katt: require 'katt-js' kattPlayer: require '../' } exports.run.after = () -> mockery.disable() mockery.deregisterAll() fsTest1 = """--- Test 1 --- --- Some description --- # Step 1 The merchant creates a new example object on our server, and we respond with the location of the created example. POST /step1 > Accept: application/json > Content-Type: application/json > Cookie: katt_scenario=basic.apib { "cart": { "items": [ { "name": "PI:NAME:<NAME>END_PI", "quantity": 1, "unit_price": 4495000 }, { "name": "Battery", "quantity": 4, "unit_price": 1000 }, { "name": "Staple", "quantity": 1, "unit_price": 12000 } ] } } < 201 < Location: {{>example_uri}} # Step 2 The client (customer) fetches the created resource data. GET {{<example_uri}} > Accept: application/json > Cookie: katt_scenario=basic.apib, katt_transaction=1 < 200 < Content-Type: application/json { "required_fields": [ "email" ], "cart": "{{_}}" } # Step 3 The customer submits an e-mail address in the form. POST {{<example_uri}}/step3 > Accept: application/json > Content-Type: application/json > Cookie: katt_scenario=basic.apib, katt_transaction=2 { "email": "PI:EMAIL:<EMAIL>END_PI" } < 200 < Content-Type: application/json { "required_fields": [ "password" ], "cart": "{{_}}" } # Step 4 The customer submits the form again, this time also with his password. We inform him that payment is required. POST {{<example_uri}}/step4 > Accept: application/json > Content-Type: application/json > Cookie: katt_scenario=basic.apib, katt_transaction=3 { "email": "PI:EMAIL:<EMAIL>END_PI", "password": "PI:PASSWORD:<PASSWORD>END_PI" } < 402 < Content-Type: application/json { "error": "payment required" } """
[ { "context": ": \"\"\n default: false\n key: \"BSH.Common.Command.ResumeProgram\"\n }\n ]\n\n class", "end": 20659, "score": 0.5072017312049866, "start": 20653, "tag": "KEY", "value": "Common" }, { "context": "it: \"\"\n default: \"false\"\n ...
appliances.coffee
bertreb/pimatic-home-connect
2
module.exports = (env) -> class CoffeeMaker constructor: () -> @programs = [ {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.Espresso"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.EspressoMacchiato"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.Coffee"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.Cappuccino"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.LatteMacchiato"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.CaffeLatte"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Americano"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.EspressoDoppio"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.FlatWhite"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Galao"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.MilkFroth"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.WarmMilk"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.Ristretto"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Cortado"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.KleinerBrauner"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.GrosserBrauner"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Verlaengerter"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.VerlaengerterBraun"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.WienerMelange"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.FlatWhite"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Cortado"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.CafeCortado"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.CafeConLeche"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.CafeAuLait"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Doppio"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Kaapi"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.KoffieVerkeerd"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Galao"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Garoto"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Americano"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.RedEye"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.BlackEye"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.DeadEye"}, {name: "ConsumerProducts.CoffeeMaker.Program.CleaningModes.ApplianceOnRinsing"}, {name: "ConsumerProducts.CoffeeMaker.Program.CleaningModes.ApplianceOffRinsing"} ] @powerOffState = "BSH.Common.EnumType.PowerState.Standby" @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "CoffeeTemperature" type: "string" description: "" unit: "C" default: "" key: "ConsumerProducts.CoffeeMaker.Option.CoffeeTemperature" }, { name: "FillQuantity" type: "number" description: "" unit: "ml" default: 0 key: "ConsumerProducts.CoffeeMaker.Option.FillQuantity" }, { name: "BeanAmount" type: "string" description: "" unit: "" default: "" key: "ConsumerProducts.CoffeeMaker.Option.BeanAmount" } ] @supportedEvents = [ { name: "BeanContainerEmpty" type: "string" description: "" unit: "" default: "false" key: "ConsumerProducts.CoffeeMaker.Event.BeanContainerEmpty" }, { name: "WaterTankEmpty" type: "string" description: "" unit: "" default: "false" key: "ConsumerProducts.CoffeeMaker.Event.WaterTankEmpty" }, { name: "DripTrayFull" type: "string" description: "" unit: "" default: "false" key: "ConsumerProducts.CoffeeMaker.Event.DripTrayFull" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "RemoteStart" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] class Oven constructor: () -> @programs = [ {name: "Cooking.Oven.Program.HeatingMode.PreHeating"}, {name: "Cooking.Oven.Program.HeatingMode.HotAir"}, {name: "Cooking.Oven.Program.HeatingMode.TopBottomHeating"}, {name: "Cooking.Oven.Program.HeatingMode.PizzaSetting"}, {name: "Cooking.Oven.Program.HeatingMode.HotAirEco"}, {name: "Cooking.Oven.Program.HeatingMode.HotAirGrilling"}, {name: "Cooking.Oven.Program.HeatingMode.TopBottomHeatingEco"}, {name: "Cooking.Oven.Program.HeatingMode.BottomHeating"}, {name: "Cooking.Oven.Program.HeatingMode.SlowCook"}, {name: "Cooking.Oven.Program.HeatingMode.IntensiveHeat"}, {name: "Cooking.Oven.Program.HeatingMode.KeepWarm"}, {name: "Cooking.Oven.Program.HeatingMode.PreheatOvenware"}, {name: "Cooking.Oven.Program.HeatingMode.FrozenHeatupSpecial"}, {name: "Cooking.Oven.Program.HeatingMode.Desiccation"}, {name: "Cooking.Oven.Program.HeatingMode.Defrost"}, {name: "Cooking.Oven.Program.HeatingMode.Proof"} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "SetpointTemperature" type: "number" description: "" unit: "°C" default: 30 key: "Cooking.Oven.Option.SetpointTemperature" }, { name: "Duration" type: "number" description: "Duration in seconds" unit: "sec" default: 30 key: "BSH.Common.Option.Duration" }, { name: "FastPreHeat" type: "boolean" description: "" unit: "°C" default: false key: "Cooking.Oven.Option.FastPreHeat" }, { name: "RemainingProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" }, { name: "AlarmClockElapsed" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.AlarmClockElapsed" }, { name: "PreheatFinished" type: "string" description: "" unit: "" default: "false" key: "Cooking.Oven.Event.PreheatFinished" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "CurrentCavityTemperature" type: "number" description: "CurrentCavityTemperature" unit: "°C" default: 0 key: "Cooking.Oven.Status.CurrentCavityTemperature" }, { name: "RemainingProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" }, { name: "ElapsedProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.ElapsedProgramTime" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] class Washer constructor: () -> @programs = [ {name: "LaundryCare.Washer.Program.Cotton"}, {name: "LaundryCare.Washer.Program.EasyCare"}, {name: "LaundryCare.Washer.Program.Mix"}, {name: "LaundryCare.Washer.Program.DelicatesSilk"}, {name: "LaundryCare.Washer.Program.Wool"}, {name: "LaundryCare.Washer.Program.Sensitive"}, {name: "LaundryCare.Washer.Program.Auto30"}, {name: "LaundryCare.Washer.Program.Auto40"}, {name: "LaundryCare.Washer.Program.Auto60"}, {name: "LaundryCare.Washer.Program.Chiffon"}, {name: "LaundryCare.Washer.Program.Curtains"}, {name: "LaundryCare.Washer.Program.DarkWash"}, {name: "LaundryCare.Washer.Program.Dessous"}, {name: "LaundryCare.Washer.Program.Monsoon"}, {name: "LaundryCare.Washer.Program.Outdoor"}, {name: "LaundryCare.Washer.Program.PlushToy"}, {name: "LaundryCare.Washer.Program.ShirtsBlouses"}, {name: "LaundryCare.Washer.Program.Outdoor"}, {name: "LaundryCare.Washer.Program.SportFitness"}, {name: "LaundryCare.Washer.Program.Towels"}, {name: "LaundryCare.Washer.Program.WaterProof"} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "RemainingProgramTime" type: "number" description: "RemainingProgramTime in seconds" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" }, { name: "Temperature" type: "string" description: "" unit: "°C" default: "" key: "LaundryCare.Washer.Option.Temperature" }, { name: "SpinSpeed" type: "string" description: "SpinSpeed in rpm" unit: "rpm" default: "" key: "LaundryCare.Washer.Option.SpinSpeed" }, { name: "ProgramProgress" type: "string" description: "ProgramProgress in %" unit: "%" default: "" key: "BSH.Common.Option.ProgramProgress" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] class Dishwasher constructor: () -> @programs = [ {name: "Dishcare.Dishwasher.Program.Auto1"}, {name: "Dishcare.Dishwasher.Program.Auto2"}, {name: "Dishcare.Dishwasher.Program.Auto3"}, {name: "Dishcare.Dishwasher.Program.Eco50"}, {name: "Dishcare.Dishwasher.Program.Quick45"}, {name: "Dishcare.Dishwasher.Program.Intensiv70"}, {name: "Dishcare.Dishwasher.Program.Normal65"}, {name: "Dishcare.Dishwasher.Program.Glas40"}, {name: "Dishcare.Dishwasher.Program.GlassCare"}, {name: "Dishcare.Dishwasher.Program.NightWash"}, {name: "Dishcare.Dishwasher.Program.Quick65"}, {name: "Dishcare.Dishwasher.Program.Normal45"}, {name: "Dishcare.Dishwasher.Program.Intensiv45"}, {name: "Dishcare.Dishwasher.Program.AutoHalfLoad"}, {name: "Dishcare.Dishwasher.Program.IntensivPower"}, {name: "Dishcare.Dishwasher.Program.MagicDaily"}, {name: "Dishcare.Dishwasher.Program.Super60"}, {name: "Dishcare.Dishwasher.Program.Kurz60"}, {name: "Dishcare.Dishwasher.Program.ExpressSparkle65"}, {name: "Dishcare.Dishwasher.Program.MachineCare"}, {name: "Dishcare.Dishwasher.Program.SteamFresh"}, {name: "Dishcare.Dishwasher.Program.MaximumCleaning"} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "RemainingProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" }, { name: "StartInRelative" type: "number" description: "StartInRelative" unit: "" default: 0 key: "BSH.Common.Option.StartInRelative" }, { name: "Lighting" type: "boolean" description: "Lighting" unit: "" default: false key: "Cooking.Common.Setting.Lighting" }, { name: "LightingBrightness" type: "number" description: "LightingBrightness" unit: "" default: 10 key: "Cooking.Common.Setting.LightingBrightness" }, { name: "AmbientLightEnabled" type: "boolean" description: "AmbientLightEnabled" unit: "" default: false key: "BSH.Common.Setting.AmbientLightEnabled" }, { name: "AmbientLightBrightness" type: "number" description: "AmbientLightBrightness" unit: "" default: 10 key: "BSH.Common.Setting.AmbientLightBrightness" }, { name: "AmbientLightColor" type: "boolean" description: "AmbientLightColor" unit: "" default: "" key: "BSH.Common.Setting.AmbientLightColor" }, { name: "AmbientLightCustomColor" type: "string" description: "AmbientLightCustomColor" unit: "" default: "" key: "BSH.Common.Setting.AmbientLightCustomColor" } ] @supportedEvents = [ { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" }, { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlStartAllowed" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] class FridgeFreezer constructor: () -> @programs = [] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "SetpointTemperatureRefrigerator" type: "number" description: "SetpointTemperatureRefrigerator in °C" unit: "°C" default: 4 key: "Refrigeration.FridgeFreezer.Setting.SetpointTemperatureRefrigerator" }, { name: "SetpointTemperatureFreezer" type: "number" description: "" unit: "°C" default: -20 key: "Refrigeration.FridgeFreezer.Setting.SetpointTemperatureFreezer" }, { name: "SuperModeRefrigerator" type: "boolean" description: "SuperModeRefrigerator" unit: "" default: false key: "Refrigeration.FridgeFreezer.Setting.SuperModeRefrigerator" }, { name: "SuperModeFreezer" type: "boolean" description: "SuperModeFreezer" unit: "" default: false key: "Refrigeration.FridgeFreezer.Setting.SuperModeFreezer" } ] @supportedEvents = [ { name: "DoorAlarmFreezer" type: "string" description: "" unit: "" default: "false" key: "Refrigeration.FridgeFreezer.Event.DoorAlarmFreezer" }, { name: "DoorAlarmRefrigerator" type: "string" description: "" unit: "" default: "false" key: "Refrigeration.FridgeFreezer.Event.DoorAlarmRefrigerator" }, { name: "TemperatureAlarmFreezer" type: "string" description: "" unit: "" default: "false" key: "Refrigeration.FridgeFreezer.Event.TemperatureAlarmFreezer" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlActive" } ] class Dryer constructor: () -> @programs = [ {name: "LaundryCare.Dryer.Program.Cotton"}, {name: "LaundryCare.Dryer.Program.Synthetic"}, {name: "LaundryCare.Dryer.Program.Mix"}, {name: "LaundryCare.Dryer.Program.Blankets"}, {name: "LaundryCare.Dryer.Program.BusinessShirts"}, {name: "LaundryCare.Dryer.Program.DownFeathers"}, {name: "LaundryCare.Dryer.Program.Hygiene"}, {name: "LaundryCare.Dryer.Program.Program.Jeans"}, {name: "LaundryCare.Dryer.Program.Outdoor"}, {name: "LaundryCare.Dryer.Program.SyntheticRefresh"}, {name: "LaundryCare.Dryer.Program.Towels"}, {name: "LaundryCare.Dryer.Program.Delicates"}, {name: "LaundryCare.Dryer.Program.Super40"}, {name: "LaundryCare.Dryer.Program.Shirts15"}, {name: "LaundryCare.Dryer.Program.Pillow"}, {name: "LaundryCare.Dryer.Program.AntiShrink"} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "DryingTarget" type: "string" description: "DryingTarget" unit: "" default: "" key: "LaundryCare.Dryer.Option.DryingTarget" }, { name: "ProgramProgress" type: "number" description: "ProgramProgress in %" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "RemainingProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] class Hood constructor: () -> @programs = [ {name: "Cooking.Common.Program.Hood.Automatic"}, {name: "Cooking.Common.Program.Hood.Venting"}, {name: "Cooking.Common.Program.Hood.DelayedShutOff "} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "Duration" type: "number" description: "Duration in seconds" unit: "sec" default: 30 key: "BSH.Common.Option.Duration" }, { name: "VentingLevel" type: "string" description: "VentingLevel" unit: "" default: "" key: "Cooking.Common.Option.Hood.VentingLevel" }, { name: "IntensiveLevel" type: "string" description: "IntensiveLevel" unit: "" default: "" key: "Cooking.Common.Option.Hood.IntensiveLevel" }, { name: "Lighting" type: "boolean" description: "Lighting" unit: "" default: false key: "Cooking.Common.Setting.Lighting" }, { name: "Lighting" type: "boolean" description: "Lighting" unit: "" default: false key: "Cooking.Common.Setting.Lighting" }, { name: "LightingBrightness" type: "number" description: "LightingBrightness" unit: "" default: 10 key: "Cooking.Common.Setting.LightingBrightness" }, { name: "AmbientLightEnabled" type: "boolean" description: "AmbientLightEnabled" unit: "" default: false key: "BSH.Common.Setting.AmbientLightEnabled" }, { name: "AmbientLightBrightness" type: "number" description: "AmbientLightBrightness" unit: "" default: 10 key: "BSH.Common.Setting.AmbientLightBrightness" }, { name: "AmbientLightColor" type: "boolean" description: "AmbientLightColor" unit: "" default: "" key: "BSH.Common.Setting.AmbientLightColor" }, { name: "AmbientLightCustomColor" type: "string" description: "AmbientLightCustomColor" unit: "" default: "" key: "BSH.Common.Setting.AmbientLightCustomColor" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "ElapsedProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.ElapsedProgramTime" }, { name: "RemoteControl" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] class CleaningRobot constructor: () -> @programs = [ {name: "ConsumerProducts.CleaningRobot.Program.Cleaning.CleanAll"}, {name: "ConsumerProducts.CleaningRobot.Program.Cleaning.CleanMap"}, {name: "ConsumerProducts.CleaningRobot.Program.Basic.GoHome "} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "ReferenceMapId" type: "string" description: "ReferenceMapId for Available maps" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Option.ReferenceMapId" }, { name: "CleaningMode" type: "string" description: "CleaningMode" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Option.CleaningMode" }, { name: "CurrentMap" type: "string" description: "CurrentMap" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.CurrentMap" }, { name: "NameOfMap1" type: "string" description: "NameOfMap1" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap1" }, { name: "NameOfMap2" type: "string" description: "NameOfMap2" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap2" }, { name: "NameOfMap3" type: "string" description: "NameOfMap3" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap3" }, { name: "NameOfMap4" type: "string" description: "NameOfMap4" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap4" }, { name: "NameOfMap5" type: "string" description: "NameOfMap5" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap5" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" }, { name: "EmptyDustBoxAndCleanFilter" type: "string" description: "EmptyDustBoxAndCleanFilter" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Event.EmptyDustBoxAndCleanFilter" }, { name: "RobotIsStuck" type: "string" description: "RobotIsStuck" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Event.RobotIsStuck" }, { name: "DockingStationNotFound" type: "string" description: "DockingStationNotFound" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Event.DockingStationNotFound" } ] @supportedStatus = [ { name: "CameraState" type: "string" description: "CameraState" unit: "" default: "" key: "BSH.Common.Status.Video.CameraState" }, { name: "ElapsedProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.ElapsedProgramTime" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "DustBoxInserted" type: "boolean" description: "DustBoxInserted" unit: "" default: false key: "ConsumerProducts.CleaningRobot.Status.DustBoxInserted" }, { name: "LastSelectedMap" type: "string" description: "LastSelectedMap" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Status.LastSelectedMap" }, { name: "Lost" type: "boolean" description: "Cleaning robot Lost" unit: "" default: false key: "ConsumerProducts.CleaningRobot.Status.Lost" }, { name: "Lifted" type: "boolean" description: "Cleaning robot Lifted" unit: "" default: false key: "ConsumerProducts.CleaningRobot.Status.Lifted" }, { name: "BatteryLevel" type: "number" description: "Cleaning robot BatteryLevel" unit: "%" default: 100 key: "BSH.Common.Status.BatteryLevel" }, { name: "BatteryChargingState" type: "string" description: "Cleaning robot BatteryChargingState" unit: "" default: "" key: "BSH.Common.Status.BatteryChargingState" }, { name: "ChargingConnection" type: "string" description: "Cleaning robot ChargingConnection" unit: "" default: "" key: "BSH.Common.Status.ChargingConnection" }, { name: "CameraState" type: "string" description: "Cleaning robot CameraState" unit: "" default: "" key: "BSH.Common.Status.Video.CameraState" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] return exports = { CoffeeMaker Oven Washer Dishwasher Dryer FridgeFreezer Hood CleaningRobot }
123428
module.exports = (env) -> class CoffeeMaker constructor: () -> @programs = [ {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.Espresso"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.EspressoMacchiato"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.Coffee"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.Cappuccino"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.LatteMacchiato"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.CaffeLatte"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Americano"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.EspressoDoppio"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.FlatWhite"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Galao"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.MilkFroth"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.WarmMilk"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.Ristretto"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Cortado"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.KleinerBrauner"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.GrosserBrauner"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Verlaengerter"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.VerlaengerterBraun"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.WienerMelange"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.FlatWhite"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Cortado"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.CafeCortado"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.CafeConLeche"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.CafeAuLait"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Doppio"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Kaapi"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.KoffieVerkeerd"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Galao"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Garoto"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Americano"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.RedEye"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.BlackEye"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.DeadEye"}, {name: "ConsumerProducts.CoffeeMaker.Program.CleaningModes.ApplianceOnRinsing"}, {name: "ConsumerProducts.CoffeeMaker.Program.CleaningModes.ApplianceOffRinsing"} ] @powerOffState = "BSH.Common.EnumType.PowerState.Standby" @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "CoffeeTemperature" type: "string" description: "" unit: "C" default: "" key: "ConsumerProducts.CoffeeMaker.Option.CoffeeTemperature" }, { name: "FillQuantity" type: "number" description: "" unit: "ml" default: 0 key: "ConsumerProducts.CoffeeMaker.Option.FillQuantity" }, { name: "BeanAmount" type: "string" description: "" unit: "" default: "" key: "ConsumerProducts.CoffeeMaker.Option.BeanAmount" } ] @supportedEvents = [ { name: "BeanContainerEmpty" type: "string" description: "" unit: "" default: "false" key: "ConsumerProducts.CoffeeMaker.Event.BeanContainerEmpty" }, { name: "WaterTankEmpty" type: "string" description: "" unit: "" default: "false" key: "ConsumerProducts.CoffeeMaker.Event.WaterTankEmpty" }, { name: "DripTrayFull" type: "string" description: "" unit: "" default: "false" key: "ConsumerProducts.CoffeeMaker.Event.DripTrayFull" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "RemoteStart" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] class Oven constructor: () -> @programs = [ {name: "Cooking.Oven.Program.HeatingMode.PreHeating"}, {name: "Cooking.Oven.Program.HeatingMode.HotAir"}, {name: "Cooking.Oven.Program.HeatingMode.TopBottomHeating"}, {name: "Cooking.Oven.Program.HeatingMode.PizzaSetting"}, {name: "Cooking.Oven.Program.HeatingMode.HotAirEco"}, {name: "Cooking.Oven.Program.HeatingMode.HotAirGrilling"}, {name: "Cooking.Oven.Program.HeatingMode.TopBottomHeatingEco"}, {name: "Cooking.Oven.Program.HeatingMode.BottomHeating"}, {name: "Cooking.Oven.Program.HeatingMode.SlowCook"}, {name: "Cooking.Oven.Program.HeatingMode.IntensiveHeat"}, {name: "Cooking.Oven.Program.HeatingMode.KeepWarm"}, {name: "Cooking.Oven.Program.HeatingMode.PreheatOvenware"}, {name: "Cooking.Oven.Program.HeatingMode.FrozenHeatupSpecial"}, {name: "Cooking.Oven.Program.HeatingMode.Desiccation"}, {name: "Cooking.Oven.Program.HeatingMode.Defrost"}, {name: "Cooking.Oven.Program.HeatingMode.Proof"} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "SetpointTemperature" type: "number" description: "" unit: "°C" default: 30 key: "Cooking.Oven.Option.SetpointTemperature" }, { name: "Duration" type: "number" description: "Duration in seconds" unit: "sec" default: 30 key: "BSH.Common.Option.Duration" }, { name: "FastPreHeat" type: "boolean" description: "" unit: "°C" default: false key: "Cooking.Oven.Option.FastPreHeat" }, { name: "RemainingProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" }, { name: "AlarmClockElapsed" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.AlarmClockElapsed" }, { name: "PreheatFinished" type: "string" description: "" unit: "" default: "false" key: "Cooking.Oven.Event.PreheatFinished" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "CurrentCavityTemperature" type: "number" description: "CurrentCavityTemperature" unit: "°C" default: 0 key: "Cooking.Oven.Status.CurrentCavityTemperature" }, { name: "RemainingProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" }, { name: "ElapsedProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.ElapsedProgramTime" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] class Washer constructor: () -> @programs = [ {name: "LaundryCare.Washer.Program.Cotton"}, {name: "LaundryCare.Washer.Program.EasyCare"}, {name: "LaundryCare.Washer.Program.Mix"}, {name: "LaundryCare.Washer.Program.DelicatesSilk"}, {name: "LaundryCare.Washer.Program.Wool"}, {name: "LaundryCare.Washer.Program.Sensitive"}, {name: "LaundryCare.Washer.Program.Auto30"}, {name: "LaundryCare.Washer.Program.Auto40"}, {name: "LaundryCare.Washer.Program.Auto60"}, {name: "LaundryCare.Washer.Program.Chiffon"}, {name: "LaundryCare.Washer.Program.Curtains"}, {name: "LaundryCare.Washer.Program.DarkWash"}, {name: "LaundryCare.Washer.Program.Dessous"}, {name: "LaundryCare.Washer.Program.Monsoon"}, {name: "LaundryCare.Washer.Program.Outdoor"}, {name: "LaundryCare.Washer.Program.PlushToy"}, {name: "LaundryCare.Washer.Program.ShirtsBlouses"}, {name: "LaundryCare.Washer.Program.Outdoor"}, {name: "LaundryCare.Washer.Program.SportFitness"}, {name: "LaundryCare.Washer.Program.Towels"}, {name: "LaundryCare.Washer.Program.WaterProof"} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "RemainingProgramTime" type: "number" description: "RemainingProgramTime in seconds" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" }, { name: "Temperature" type: "string" description: "" unit: "°C" default: "" key: "LaundryCare.Washer.Option.Temperature" }, { name: "SpinSpeed" type: "string" description: "SpinSpeed in rpm" unit: "rpm" default: "" key: "LaundryCare.Washer.Option.SpinSpeed" }, { name: "ProgramProgress" type: "string" description: "ProgramProgress in %" unit: "%" default: "" key: "BSH.Common.Option.ProgramProgress" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] class Dishwasher constructor: () -> @programs = [ {name: "Dishcare.Dishwasher.Program.Auto1"}, {name: "Dishcare.Dishwasher.Program.Auto2"}, {name: "Dishcare.Dishwasher.Program.Auto3"}, {name: "Dishcare.Dishwasher.Program.Eco50"}, {name: "Dishcare.Dishwasher.Program.Quick45"}, {name: "Dishcare.Dishwasher.Program.Intensiv70"}, {name: "Dishcare.Dishwasher.Program.Normal65"}, {name: "Dishcare.Dishwasher.Program.Glas40"}, {name: "Dishcare.Dishwasher.Program.GlassCare"}, {name: "Dishcare.Dishwasher.Program.NightWash"}, {name: "Dishcare.Dishwasher.Program.Quick65"}, {name: "Dishcare.Dishwasher.Program.Normal45"}, {name: "Dishcare.Dishwasher.Program.Intensiv45"}, {name: "Dishcare.Dishwasher.Program.AutoHalfLoad"}, {name: "Dishcare.Dishwasher.Program.IntensivPower"}, {name: "Dishcare.Dishwasher.Program.MagicDaily"}, {name: "Dishcare.Dishwasher.Program.Super60"}, {name: "Dishcare.Dishwasher.Program.Kurz60"}, {name: "Dishcare.Dishwasher.Program.ExpressSparkle65"}, {name: "Dishcare.Dishwasher.Program.MachineCare"}, {name: "Dishcare.Dishwasher.Program.SteamFresh"}, {name: "Dishcare.Dishwasher.Program.MaximumCleaning"} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "RemainingProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" }, { name: "StartInRelative" type: "number" description: "StartInRelative" unit: "" default: 0 key: "BSH.Common.Option.StartInRelative" }, { name: "Lighting" type: "boolean" description: "Lighting" unit: "" default: false key: "Cooking.Common.Setting.Lighting" }, { name: "LightingBrightness" type: "number" description: "LightingBrightness" unit: "" default: 10 key: "Cooking.Common.Setting.LightingBrightness" }, { name: "AmbientLightEnabled" type: "boolean" description: "AmbientLightEnabled" unit: "" default: false key: "BSH.Common.Setting.AmbientLightEnabled" }, { name: "AmbientLightBrightness" type: "number" description: "AmbientLightBrightness" unit: "" default: 10 key: "BSH.Common.Setting.AmbientLightBrightness" }, { name: "AmbientLightColor" type: "boolean" description: "AmbientLightColor" unit: "" default: "" key: "BSH.Common.Setting.AmbientLightColor" }, { name: "AmbientLightCustomColor" type: "string" description: "AmbientLightCustomColor" unit: "" default: "" key: "BSH.Common.Setting.AmbientLightCustomColor" } ] @supportedEvents = [ { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" }, { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlStartAllowed" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.<KEY>.Command.ResumeProgram" } ] class FridgeFreezer constructor: () -> @programs = [] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "SetpointTemperatureRefrigerator" type: "number" description: "SetpointTemperatureRefrigerator in °C" unit: "°C" default: 4 key: "Refrigeration.FridgeFreezer.Setting.SetpointTemperatureRefrigerator" }, { name: "SetpointTemperatureFreezer" type: "number" description: "" unit: "°C" default: -20 key: "Refrigeration.FridgeFreezer.Setting.SetpointTemperatureFreezer" }, { name: "SuperModeRefrigerator" type: "boolean" description: "SuperModeRefrigerator" unit: "" default: false key: "Refrigeration.FridgeFreezer.Setting.SuperModeRefrigerator" }, { name: "SuperModeFreezer" type: "boolean" description: "SuperModeFreezer" unit: "" default: false key: "Refrigeration.FridgeFreezer.Setting.SuperModeFreezer" } ] @supportedEvents = [ { name: "DoorAlarmFreezer" type: "string" description: "" unit: "" default: "false" key: "<KEY>" }, { name: "DoorAlarmRefrigerator" type: "string" description: "" unit: "" default: "false" key: "Refrigeration.<KEY>ridge<KEY>zer.<KEY>DoorAlarmRefrigerator" }, { name: "TemperatureAlarmFreezer" type: "string" description: "" unit: "" default: "false" key: "Refrigeration.<KEY>ridge<KEY>Event<KEY>.TemperatureAlarmFreezer" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlActive" } ] class Dryer constructor: () -> @programs = [ {name: "LaundryCare.Dryer.Program.Cotton"}, {name: "LaundryCare.Dryer.Program.Synthetic"}, {name: "LaundryCare.Dryer.Program.Mix"}, {name: "LaundryCare.Dryer.Program.Blankets"}, {name: "LaundryCare.Dryer.Program.BusinessShirts"}, {name: "LaundryCare.Dryer.Program.DownFeathers"}, {name: "LaundryCare.Dryer.Program.Hygiene"}, {name: "LaundryCare.Dryer.Program.Program.Jeans"}, {name: "LaundryCare.Dryer.Program.Outdoor"}, {name: "LaundryCare.Dryer.Program.SyntheticRefresh"}, {name: "LaundryCare.Dryer.Program.Towels"}, {name: "LaundryCare.Dryer.Program.Delicates"}, {name: "LaundryCare.Dryer.Program.Super40"}, {name: "LaundryCare.Dryer.Program.Shirts15"}, {name: "LaundryCare.Dryer.Program.Pillow"}, {name: "LaundryCare.Dryer.Program.AntiShrink"} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "DryingTarget" type: "string" description: "DryingTarget" unit: "" default: "" key: "LaundryCare.Dryer.Option.DryingTarget" }, { name: "ProgramProgress" type: "number" description: "ProgramProgress in %" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "RemainingProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] class Hood constructor: () -> @programs = [ {name: "Cooking.Common.Program.Hood.Automatic"}, {name: "Cooking.Common.Program.Hood.Venting"}, {name: "Cooking.Common.Program.Hood.DelayedShutOff "} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "Duration" type: "number" description: "Duration in seconds" unit: "sec" default: 30 key: "BSH.Common.Option.Duration" }, { name: "VentingLevel" type: "string" description: "VentingLevel" unit: "" default: "" key: "Cooking.Common.Option.Hood.VentingLevel" }, { name: "IntensiveLevel" type: "string" description: "IntensiveLevel" unit: "" default: "" key: "Cooking.Common.Option.Hood.IntensiveLevel" }, { name: "Lighting" type: "boolean" description: "Lighting" unit: "" default: false key: "Cooking.Common.Setting.Lighting" }, { name: "Lighting" type: "boolean" description: "Lighting" unit: "" default: false key: "Cooking.Common.Setting.Lighting" }, { name: "LightingBrightness" type: "number" description: "LightingBrightness" unit: "" default: 10 key: "Cooking.Common.Setting.LightingBrightness" }, { name: "AmbientLightEnabled" type: "boolean" description: "AmbientLightEnabled" unit: "" default: false key: "BSH.Common.Setting.AmbientLightEnabled" }, { name: "AmbientLightBrightness" type: "number" description: "AmbientLightBrightness" unit: "" default: 10 key: "BSH.Common.Setting.AmbientLightBrightness" }, { name: "AmbientLightColor" type: "boolean" description: "AmbientLightColor" unit: "" default: "" key: "BSH.Common.Setting.AmbientLightColor" }, { name: "AmbientLightCustomColor" type: "string" description: "AmbientLightCustomColor" unit: "" default: "" key: "BSH.Common.Setting.AmbientLightCustomColor" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "ElapsedProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.ElapsedProgramTime" }, { name: "RemoteControl" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] class CleaningRobot constructor: () -> @programs = [ {name: "ConsumerProducts.CleaningRobot.Program.Cleaning.CleanAll"}, {name: "ConsumerProducts.CleaningRobot.Program.Cleaning.CleanMap"}, {name: "ConsumerProducts.CleaningRobot.Program.Basic.GoHome "} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "ReferenceMapId" type: "string" description: "ReferenceMapId for Available maps" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Option.ReferenceMapId" }, { name: "CleaningMode" type: "string" description: "CleaningMode" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Option.CleaningMode" }, { name: "CurrentMap" type: "string" description: "CurrentMap" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.CurrentMap" }, { name: "NameOfMap1" type: "string" description: "NameOfMap1" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap1" }, { name: "NameOfMap2" type: "string" description: "NameOfMap2" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap2" }, { name: "NameOfMap3" type: "string" description: "NameOfMap3" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap3" }, { name: "NameOfMap4" type: "string" description: "NameOfMap4" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap4" }, { name: "NameOfMap5" type: "string" description: "NameOfMap5" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap5" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" }, { name: "EmptyDustBoxAndCleanFilter" type: "string" description: "EmptyDustBoxAndCleanFilter" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Event.EmptyDustBoxAndCleanFilter" }, { name: "RobotIsStuck" type: "string" description: "RobotIsStuck" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Event.RobotIsStuck" }, { name: "DockingStationNotFound" type: "string" description: "DockingStationNotFound" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Event.DockingStationNotFound" } ] @supportedStatus = [ { name: "CameraState" type: "string" description: "CameraState" unit: "" default: "" key: "BSH.Common.Status.Video.CameraState" }, { name: "ElapsedProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.ElapsedProgramTime" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "DustBoxInserted" type: "boolean" description: "DustBoxInserted" unit: "" default: false key: "ConsumerProducts.CleaningRobot.Status.DustBoxInserted" }, { name: "LastSelectedMap" type: "string" description: "LastSelectedMap" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Status.LastSelectedMap" }, { name: "Lost" type: "boolean" description: "Cleaning robot Lost" unit: "" default: false key: "ConsumerProducts.CleaningRobot.Status.Lost" }, { name: "Lifted" type: "boolean" description: "Cleaning robot Lifted" unit: "" default: false key: "ConsumerProducts.CleaningRobot.Status.Lifted" }, { name: "BatteryLevel" type: "number" description: "Cleaning robot BatteryLevel" unit: "%" default: 100 key: "BSH.Common.Status.BatteryLevel" }, { name: "BatteryChargingState" type: "string" description: "Cleaning robot BatteryChargingState" unit: "" default: "" key: "BSH.Common.Status.BatteryChargingState" }, { name: "ChargingConnection" type: "string" description: "Cleaning robot ChargingConnection" unit: "" default: "" key: "BSH.Common.Status.ChargingConnection" }, { name: "CameraState" type: "string" description: "Cleaning robot CameraState" unit: "" default: "" key: "BSH.Common.Status.Video.CameraState" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] return exports = { CoffeeMaker Oven Washer Dishwasher Dryer FridgeFreezer Hood CleaningRobot }
true
module.exports = (env) -> class CoffeeMaker constructor: () -> @programs = [ {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.Espresso"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.EspressoMacchiato"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.Coffee"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.Cappuccino"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.LatteMacchiato"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.CaffeLatte"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Americano"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.EspressoDoppio"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.FlatWhite"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Galao"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.MilkFroth"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.WarmMilk"}, {name: "ConsumerProducts.CoffeeMaker.Program.Beverage.Ristretto"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Cortado"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.KleinerBrauner"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.GrosserBrauner"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Verlaengerter"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.VerlaengerterBraun"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.WienerMelange"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.FlatWhite"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Cortado"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.CafeCortado"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.CafeConLeche"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.CafeAuLait"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Doppio"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Kaapi"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.KoffieVerkeerd"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Galao"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Garoto"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Americano"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.RedEye"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.BlackEye"}, {name: "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.DeadEye"}, {name: "ConsumerProducts.CoffeeMaker.Program.CleaningModes.ApplianceOnRinsing"}, {name: "ConsumerProducts.CoffeeMaker.Program.CleaningModes.ApplianceOffRinsing"} ] @powerOffState = "BSH.Common.EnumType.PowerState.Standby" @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "CoffeeTemperature" type: "string" description: "" unit: "C" default: "" key: "ConsumerProducts.CoffeeMaker.Option.CoffeeTemperature" }, { name: "FillQuantity" type: "number" description: "" unit: "ml" default: 0 key: "ConsumerProducts.CoffeeMaker.Option.FillQuantity" }, { name: "BeanAmount" type: "string" description: "" unit: "" default: "" key: "ConsumerProducts.CoffeeMaker.Option.BeanAmount" } ] @supportedEvents = [ { name: "BeanContainerEmpty" type: "string" description: "" unit: "" default: "false" key: "ConsumerProducts.CoffeeMaker.Event.BeanContainerEmpty" }, { name: "WaterTankEmpty" type: "string" description: "" unit: "" default: "false" key: "ConsumerProducts.CoffeeMaker.Event.WaterTankEmpty" }, { name: "DripTrayFull" type: "string" description: "" unit: "" default: "false" key: "ConsumerProducts.CoffeeMaker.Event.DripTrayFull" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "RemoteStart" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] class Oven constructor: () -> @programs = [ {name: "Cooking.Oven.Program.HeatingMode.PreHeating"}, {name: "Cooking.Oven.Program.HeatingMode.HotAir"}, {name: "Cooking.Oven.Program.HeatingMode.TopBottomHeating"}, {name: "Cooking.Oven.Program.HeatingMode.PizzaSetting"}, {name: "Cooking.Oven.Program.HeatingMode.HotAirEco"}, {name: "Cooking.Oven.Program.HeatingMode.HotAirGrilling"}, {name: "Cooking.Oven.Program.HeatingMode.TopBottomHeatingEco"}, {name: "Cooking.Oven.Program.HeatingMode.BottomHeating"}, {name: "Cooking.Oven.Program.HeatingMode.SlowCook"}, {name: "Cooking.Oven.Program.HeatingMode.IntensiveHeat"}, {name: "Cooking.Oven.Program.HeatingMode.KeepWarm"}, {name: "Cooking.Oven.Program.HeatingMode.PreheatOvenware"}, {name: "Cooking.Oven.Program.HeatingMode.FrozenHeatupSpecial"}, {name: "Cooking.Oven.Program.HeatingMode.Desiccation"}, {name: "Cooking.Oven.Program.HeatingMode.Defrost"}, {name: "Cooking.Oven.Program.HeatingMode.Proof"} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "SetpointTemperature" type: "number" description: "" unit: "°C" default: 30 key: "Cooking.Oven.Option.SetpointTemperature" }, { name: "Duration" type: "number" description: "Duration in seconds" unit: "sec" default: 30 key: "BSH.Common.Option.Duration" }, { name: "FastPreHeat" type: "boolean" description: "" unit: "°C" default: false key: "Cooking.Oven.Option.FastPreHeat" }, { name: "RemainingProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" }, { name: "AlarmClockElapsed" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.AlarmClockElapsed" }, { name: "PreheatFinished" type: "string" description: "" unit: "" default: "false" key: "Cooking.Oven.Event.PreheatFinished" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "CurrentCavityTemperature" type: "number" description: "CurrentCavityTemperature" unit: "°C" default: 0 key: "Cooking.Oven.Status.CurrentCavityTemperature" }, { name: "RemainingProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" }, { name: "ElapsedProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.ElapsedProgramTime" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] class Washer constructor: () -> @programs = [ {name: "LaundryCare.Washer.Program.Cotton"}, {name: "LaundryCare.Washer.Program.EasyCare"}, {name: "LaundryCare.Washer.Program.Mix"}, {name: "LaundryCare.Washer.Program.DelicatesSilk"}, {name: "LaundryCare.Washer.Program.Wool"}, {name: "LaundryCare.Washer.Program.Sensitive"}, {name: "LaundryCare.Washer.Program.Auto30"}, {name: "LaundryCare.Washer.Program.Auto40"}, {name: "LaundryCare.Washer.Program.Auto60"}, {name: "LaundryCare.Washer.Program.Chiffon"}, {name: "LaundryCare.Washer.Program.Curtains"}, {name: "LaundryCare.Washer.Program.DarkWash"}, {name: "LaundryCare.Washer.Program.Dessous"}, {name: "LaundryCare.Washer.Program.Monsoon"}, {name: "LaundryCare.Washer.Program.Outdoor"}, {name: "LaundryCare.Washer.Program.PlushToy"}, {name: "LaundryCare.Washer.Program.ShirtsBlouses"}, {name: "LaundryCare.Washer.Program.Outdoor"}, {name: "LaundryCare.Washer.Program.SportFitness"}, {name: "LaundryCare.Washer.Program.Towels"}, {name: "LaundryCare.Washer.Program.WaterProof"} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "RemainingProgramTime" type: "number" description: "RemainingProgramTime in seconds" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" }, { name: "Temperature" type: "string" description: "" unit: "°C" default: "" key: "LaundryCare.Washer.Option.Temperature" }, { name: "SpinSpeed" type: "string" description: "SpinSpeed in rpm" unit: "rpm" default: "" key: "LaundryCare.Washer.Option.SpinSpeed" }, { name: "ProgramProgress" type: "string" description: "ProgramProgress in %" unit: "%" default: "" key: "BSH.Common.Option.ProgramProgress" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] class Dishwasher constructor: () -> @programs = [ {name: "Dishcare.Dishwasher.Program.Auto1"}, {name: "Dishcare.Dishwasher.Program.Auto2"}, {name: "Dishcare.Dishwasher.Program.Auto3"}, {name: "Dishcare.Dishwasher.Program.Eco50"}, {name: "Dishcare.Dishwasher.Program.Quick45"}, {name: "Dishcare.Dishwasher.Program.Intensiv70"}, {name: "Dishcare.Dishwasher.Program.Normal65"}, {name: "Dishcare.Dishwasher.Program.Glas40"}, {name: "Dishcare.Dishwasher.Program.GlassCare"}, {name: "Dishcare.Dishwasher.Program.NightWash"}, {name: "Dishcare.Dishwasher.Program.Quick65"}, {name: "Dishcare.Dishwasher.Program.Normal45"}, {name: "Dishcare.Dishwasher.Program.Intensiv45"}, {name: "Dishcare.Dishwasher.Program.AutoHalfLoad"}, {name: "Dishcare.Dishwasher.Program.IntensivPower"}, {name: "Dishcare.Dishwasher.Program.MagicDaily"}, {name: "Dishcare.Dishwasher.Program.Super60"}, {name: "Dishcare.Dishwasher.Program.Kurz60"}, {name: "Dishcare.Dishwasher.Program.ExpressSparkle65"}, {name: "Dishcare.Dishwasher.Program.MachineCare"}, {name: "Dishcare.Dishwasher.Program.SteamFresh"}, {name: "Dishcare.Dishwasher.Program.MaximumCleaning"} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "RemainingProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" }, { name: "StartInRelative" type: "number" description: "StartInRelative" unit: "" default: 0 key: "BSH.Common.Option.StartInRelative" }, { name: "Lighting" type: "boolean" description: "Lighting" unit: "" default: false key: "Cooking.Common.Setting.Lighting" }, { name: "LightingBrightness" type: "number" description: "LightingBrightness" unit: "" default: 10 key: "Cooking.Common.Setting.LightingBrightness" }, { name: "AmbientLightEnabled" type: "boolean" description: "AmbientLightEnabled" unit: "" default: false key: "BSH.Common.Setting.AmbientLightEnabled" }, { name: "AmbientLightBrightness" type: "number" description: "AmbientLightBrightness" unit: "" default: 10 key: "BSH.Common.Setting.AmbientLightBrightness" }, { name: "AmbientLightColor" type: "boolean" description: "AmbientLightColor" unit: "" default: "" key: "BSH.Common.Setting.AmbientLightColor" }, { name: "AmbientLightCustomColor" type: "string" description: "AmbientLightCustomColor" unit: "" default: "" key: "BSH.Common.Setting.AmbientLightCustomColor" } ] @supportedEvents = [ { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" }, { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.RemoteControlStartAllowed" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.PI:KEY:<KEY>END_PI.Command.ResumeProgram" } ] class FridgeFreezer constructor: () -> @programs = [] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "SetpointTemperatureRefrigerator" type: "number" description: "SetpointTemperatureRefrigerator in °C" unit: "°C" default: 4 key: "Refrigeration.FridgeFreezer.Setting.SetpointTemperatureRefrigerator" }, { name: "SetpointTemperatureFreezer" type: "number" description: "" unit: "°C" default: -20 key: "Refrigeration.FridgeFreezer.Setting.SetpointTemperatureFreezer" }, { name: "SuperModeRefrigerator" type: "boolean" description: "SuperModeRefrigerator" unit: "" default: false key: "Refrigeration.FridgeFreezer.Setting.SuperModeRefrigerator" }, { name: "SuperModeFreezer" type: "boolean" description: "SuperModeFreezer" unit: "" default: false key: "Refrigeration.FridgeFreezer.Setting.SuperModeFreezer" } ] @supportedEvents = [ { name: "DoorAlarmFreezer" type: "string" description: "" unit: "" default: "false" key: "PI:KEY:<KEY>END_PI" }, { name: "DoorAlarmRefrigerator" type: "string" description: "" unit: "" default: "false" key: "Refrigeration.PI:KEY:<KEY>END_PIridgePI:KEY:<KEY>END_PIzer.PI:KEY:<KEY>END_PIDoorAlarmRefrigerator" }, { name: "TemperatureAlarmFreezer" type: "string" description: "" unit: "" default: "false" key: "Refrigeration.PI:KEY:<KEY>END_PIridgePI:KEY:<KEY>END_PIEventPI:KEY:<KEY>END_PI.TemperatureAlarmFreezer" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlActive" } ] class Dryer constructor: () -> @programs = [ {name: "LaundryCare.Dryer.Program.Cotton"}, {name: "LaundryCare.Dryer.Program.Synthetic"}, {name: "LaundryCare.Dryer.Program.Mix"}, {name: "LaundryCare.Dryer.Program.Blankets"}, {name: "LaundryCare.Dryer.Program.BusinessShirts"}, {name: "LaundryCare.Dryer.Program.DownFeathers"}, {name: "LaundryCare.Dryer.Program.Hygiene"}, {name: "LaundryCare.Dryer.Program.Program.Jeans"}, {name: "LaundryCare.Dryer.Program.Outdoor"}, {name: "LaundryCare.Dryer.Program.SyntheticRefresh"}, {name: "LaundryCare.Dryer.Program.Towels"}, {name: "LaundryCare.Dryer.Program.Delicates"}, {name: "LaundryCare.Dryer.Program.Super40"}, {name: "LaundryCare.Dryer.Program.Shirts15"}, {name: "LaundryCare.Dryer.Program.Pillow"}, {name: "LaundryCare.Dryer.Program.AntiShrink"} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "DryingTarget" type: "string" description: "DryingTarget" unit: "" default: "" key: "LaundryCare.Dryer.Option.DryingTarget" }, { name: "ProgramProgress" type: "number" description: "ProgramProgress in %" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "RemainingProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.RemainingProgramTime" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "DoorState" type: "string" description: "" unit: "" default: "Closed" key: "BSH.Common.Status.DoorState" }, { name: "RemoteControl" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] class Hood constructor: () -> @programs = [ {name: "Cooking.Common.Program.Hood.Automatic"}, {name: "Cooking.Common.Program.Hood.Venting"}, {name: "Cooking.Common.Program.Hood.DelayedShutOff "} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "Duration" type: "number" description: "Duration in seconds" unit: "sec" default: 30 key: "BSH.Common.Option.Duration" }, { name: "VentingLevel" type: "string" description: "VentingLevel" unit: "" default: "" key: "Cooking.Common.Option.Hood.VentingLevel" }, { name: "IntensiveLevel" type: "string" description: "IntensiveLevel" unit: "" default: "" key: "Cooking.Common.Option.Hood.IntensiveLevel" }, { name: "Lighting" type: "boolean" description: "Lighting" unit: "" default: false key: "Cooking.Common.Setting.Lighting" }, { name: "Lighting" type: "boolean" description: "Lighting" unit: "" default: false key: "Cooking.Common.Setting.Lighting" }, { name: "LightingBrightness" type: "number" description: "LightingBrightness" unit: "" default: 10 key: "Cooking.Common.Setting.LightingBrightness" }, { name: "AmbientLightEnabled" type: "boolean" description: "AmbientLightEnabled" unit: "" default: false key: "BSH.Common.Setting.AmbientLightEnabled" }, { name: "AmbientLightBrightness" type: "number" description: "AmbientLightBrightness" unit: "" default: 10 key: "BSH.Common.Setting.AmbientLightBrightness" }, { name: "AmbientLightColor" type: "boolean" description: "AmbientLightColor" unit: "" default: "" key: "BSH.Common.Setting.AmbientLightColor" }, { name: "AmbientLightCustomColor" type: "string" description: "AmbientLightCustomColor" unit: "" default: "" key: "BSH.Common.Setting.AmbientLightCustomColor" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" } ] @supportedStatus = [ { name: "ProgramProgress" type: "number" description: "Program progress in seconds" unit: "%" default: 0 key: "BSH.Common.Option.ProgramProgress" }, { name: "ElapsedProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.ElapsedProgramTime" }, { name: "RemoteControl" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlActive" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "RemoteControlStartAllowed" type: "boolean" description: "" unit: "" default: true key: "BSH.Common.Status.RemoteControlStartAllowed" }, { name: "LocalControlActive" type: "boolean" description: "" unit: "" default: false key: "BSH.Common.Status.LocalControlActive" } ] class CleaningRobot constructor: () -> @programs = [ {name: "ConsumerProducts.CleaningRobot.Program.Cleaning.CleanAll"}, {name: "ConsumerProducts.CleaningRobot.Program.Cleaning.CleanMap"}, {name: "ConsumerProducts.CleaningRobot.Program.Basic.GoHome "} ] @selectedProgram = "BSH.Common.Root.SelectedProgram" @activeProgram = "BSH.Common.Root.ActiveProgram" @supportedOptions = [ { name: "ReferenceMapId" type: "string" description: "ReferenceMapId for Available maps" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Option.ReferenceMapId" }, { name: "CleaningMode" type: "string" description: "CleaningMode" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Option.CleaningMode" }, { name: "CurrentMap" type: "string" description: "CurrentMap" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.CurrentMap" }, { name: "NameOfMap1" type: "string" description: "NameOfMap1" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap1" }, { name: "NameOfMap2" type: "string" description: "NameOfMap2" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap2" }, { name: "NameOfMap3" type: "string" description: "NameOfMap3" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap3" }, { name: "NameOfMap4" type: "string" description: "NameOfMap4" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap4" }, { name: "NameOfMap5" type: "string" description: "NameOfMap5" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Setting.NameOfMap5" } ] @supportedEvents = [ { name: "ProgramFinished" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramFinished" }, { name: "ProgramAborted" type: "string" description: "" unit: "" default: "false" key: "BSH.Common.Event.ProgramAborted" }, { name: "EmptyDustBoxAndCleanFilter" type: "string" description: "EmptyDustBoxAndCleanFilter" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Event.EmptyDustBoxAndCleanFilter" }, { name: "RobotIsStuck" type: "string" description: "RobotIsStuck" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Event.RobotIsStuck" }, { name: "DockingStationNotFound" type: "string" description: "DockingStationNotFound" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Event.DockingStationNotFound" } ] @supportedStatus = [ { name: "CameraState" type: "string" description: "CameraState" unit: "" default: "" key: "BSH.Common.Status.Video.CameraState" }, { name: "ElapsedProgramTime" type: "number" description: "" unit: "sec" default: 0 key: "BSH.Common.Option.ElapsedProgramTime" }, { name: "OperationState" type: "string" description: "" unit: "" default: "" key: "BSH.Common.Status.OperationState" }, { name: "DustBoxInserted" type: "boolean" description: "DustBoxInserted" unit: "" default: false key: "ConsumerProducts.CleaningRobot.Status.DustBoxInserted" }, { name: "LastSelectedMap" type: "string" description: "LastSelectedMap" unit: "" default: "" key: "ConsumerProducts.CleaningRobot.Status.LastSelectedMap" }, { name: "Lost" type: "boolean" description: "Cleaning robot Lost" unit: "" default: false key: "ConsumerProducts.CleaningRobot.Status.Lost" }, { name: "Lifted" type: "boolean" description: "Cleaning robot Lifted" unit: "" default: false key: "ConsumerProducts.CleaningRobot.Status.Lifted" }, { name: "BatteryLevel" type: "number" description: "Cleaning robot BatteryLevel" unit: "%" default: 100 key: "BSH.Common.Status.BatteryLevel" }, { name: "BatteryChargingState" type: "string" description: "Cleaning robot BatteryChargingState" unit: "" default: "" key: "BSH.Common.Status.BatteryChargingState" }, { name: "ChargingConnection" type: "string" description: "Cleaning robot ChargingConnection" unit: "" default: "" key: "BSH.Common.Status.ChargingConnection" }, { name: "CameraState" type: "string" description: "Cleaning robot CameraState" unit: "" default: "" key: "BSH.Common.Status.Video.CameraState" } ] @supportedCommands = [ { name: "PauseProgram" type: "boolean" description: "Pause Program" unit: "" default: false key: "BSH.Common.Command.PauseProgram" }, { name: "ResumeProgram" type: "boolean" description: "Resume Program" unit: "" default: false key: "BSH.Common.Command.ResumeProgram" } ] return exports = { CoffeeMaker Oven Washer Dishwasher Dryer FridgeFreezer Hood CleaningRobot }
[ { "context": "s =\n email: 'the-email'\n password: 'the-password'\n @googleContacts = new GoogleContacts()\n\n ", "end": 672, "score": 0.9993681907653809, "start": 660, "tag": "PASSWORD", "value": "the-password" }, { "context": "l {\n email: 'the-email'\n ...
test/google_contacts_spec.coffee
elentok/gcontacts
1
require './spec_helper' GoogleContacts = null class GoogleClientLogin constructor: (@options) -> GoogleClientLogin.last = this on: -> login: -> GoogleClientLogin.events = login: 'login-event' error: 'error-event' describe "GoogleContacts", -> beforeEach -> @request = @stub() GoogleClientLogin.last = null GoogleContacts = sandbox.require '../lib/google_contacts', requires: googleclientlogin: GoogleClientLogin: GoogleClientLogin request: => @request.apply(global, arguments) describe "#connect", -> beforeEach -> @options = email: 'the-email' password: 'the-password' @googleContacts = new GoogleContacts() it "returns a promise", -> @googleContacts.connect(@options).then.should.be.a.function it "creates a new GoogleClientLogin", -> @googleContacts.connect(@options) login = GoogleClientLogin.last expect(login).to.exist it "stores the options in @options", -> @googleContacts.connect(@options) expect(GoogleClientLogin.last.options).to.eql { email: 'the-email' password: 'the-password' service: 'contacts' } it "calls GoogleClientLogin.login", -> @stub(GoogleClientLogin.prototype, 'login') @googleContacts.connect(@options) expect(GoogleClientLogin.prototype.login).to.have.been.calledOnce describe "when success", -> it "resolves the promise", -> GoogleClientLogin.prototype.on = (event, callback) -> callback?() if event == 'login-event' @googleContacts.connect(@options).should.be.fulfilled describe "when error", -> it "rejects the promise with the error", (done) -> GoogleClientLogin.prototype.on = (event, callback) -> callback?('an-error') if event == 'error-event' @googleContacts.connect(@options).fail (err) => err.should.equal 'an-error' done() describe "#getContacts", -> beforeEach -> @options = email: 'the-email' @contacts = new GoogleContacts() @contacts.options = @options @contacts.auth = getAuthId: -> 'the-auth-id' it "makes a request to /m8/feeds/contacts/{email}/thin?alt=json&max-results=9999", -> @contacts.getContacts() expect(@request).to.have.been.calledOnce expect(@request.getCall(0).args[0]).to.eql { url: 'https://google.com/m8/feeds/contacts/the-email/thin?alt=json&max-results=9999' headers: Authorization: 'GoogleLogin auth=the-auth-id' } describe "on success", -> it "resolves the promise with the page", (done) -> responseBody = JSON.stringify({ feed: openSearch$totalResults: $t: 124 openSearch$startIndex: $t: 1 openSearch$itemsPerPage: $t: 25 entry: [ { id: $t: 'http://www.google.com/m8/feeds/contacts/bob@bob.com/base/this-is-the-id' title: $t: 'bob' gd$email: [ { address: 'bob@bob.com' } ] } ] }) @request.callsArgWith(1, null, null, responseBody) @contacts.getContacts().then (page) => expect(page).to.eql { startIndex: 1 itemsPerPage: 25 totalResults: 124 contacts: [ { id: 'this-is-the-id', name: 'bob', email: 'bob@bob.com' } ] } done() describe "on error", -> it "rejects the promise", (done) -> @request.callsArgWith(1, 'the-error') @contacts.getContacts().fail -> done()
191753
require './spec_helper' GoogleContacts = null class GoogleClientLogin constructor: (@options) -> GoogleClientLogin.last = this on: -> login: -> GoogleClientLogin.events = login: 'login-event' error: 'error-event' describe "GoogleContacts", -> beforeEach -> @request = @stub() GoogleClientLogin.last = null GoogleContacts = sandbox.require '../lib/google_contacts', requires: googleclientlogin: GoogleClientLogin: GoogleClientLogin request: => @request.apply(global, arguments) describe "#connect", -> beforeEach -> @options = email: 'the-email' password: '<PASSWORD>' @googleContacts = new GoogleContacts() it "returns a promise", -> @googleContacts.connect(@options).then.should.be.a.function it "creates a new GoogleClientLogin", -> @googleContacts.connect(@options) login = GoogleClientLogin.last expect(login).to.exist it "stores the options in @options", -> @googleContacts.connect(@options) expect(GoogleClientLogin.last.options).to.eql { email: 'the-email' password: '<PASSWORD>' service: 'contacts' } it "calls GoogleClientLogin.login", -> @stub(GoogleClientLogin.prototype, 'login') @googleContacts.connect(@options) expect(GoogleClientLogin.prototype.login).to.have.been.calledOnce describe "when success", -> it "resolves the promise", -> GoogleClientLogin.prototype.on = (event, callback) -> callback?() if event == 'login-event' @googleContacts.connect(@options).should.be.fulfilled describe "when error", -> it "rejects the promise with the error", (done) -> GoogleClientLogin.prototype.on = (event, callback) -> callback?('an-error') if event == 'error-event' @googleContacts.connect(@options).fail (err) => err.should.equal 'an-error' done() describe "#getContacts", -> beforeEach -> @options = email: 'the-email' @contacts = new GoogleContacts() @contacts.options = @options @contacts.auth = getAuthId: -> 'the-auth-id' it "makes a request to /m8/feeds/contacts/{email}/thin?alt=json&max-results=9999", -> @contacts.getContacts() expect(@request).to.have.been.calledOnce expect(@request.getCall(0).args[0]).to.eql { url: 'https://google.com/m8/feeds/contacts/the-email/thin?alt=json&max-results=9999' headers: Authorization: 'GoogleLogin auth=the-auth-id' } describe "on success", -> it "resolves the promise with the page", (done) -> responseBody = JSON.stringify({ feed: openSearch$totalResults: $t: 124 openSearch$startIndex: $t: 1 openSearch$itemsPerPage: $t: 25 entry: [ { id: $t: 'http://www.google.com/m8/feeds/contacts/<EMAIL>@<EMAIL>.com/base/this-is-the-id' title: $t: 'bob' gd$email: [ { address: '<EMAIL>' } ] } ] }) @request.callsArgWith(1, null, null, responseBody) @contacts.getContacts().then (page) => expect(page).to.eql { startIndex: 1 itemsPerPage: 25 totalResults: 124 contacts: [ { id: 'this-is-the-id', name: '<EMAIL>', email: '<EMAIL>' } ] } done() describe "on error", -> it "rejects the promise", (done) -> @request.callsArgWith(1, 'the-error') @contacts.getContacts().fail -> done()
true
require './spec_helper' GoogleContacts = null class GoogleClientLogin constructor: (@options) -> GoogleClientLogin.last = this on: -> login: -> GoogleClientLogin.events = login: 'login-event' error: 'error-event' describe "GoogleContacts", -> beforeEach -> @request = @stub() GoogleClientLogin.last = null GoogleContacts = sandbox.require '../lib/google_contacts', requires: googleclientlogin: GoogleClientLogin: GoogleClientLogin request: => @request.apply(global, arguments) describe "#connect", -> beforeEach -> @options = email: 'the-email' password: 'PI:PASSWORD:<PASSWORD>END_PI' @googleContacts = new GoogleContacts() it "returns a promise", -> @googleContacts.connect(@options).then.should.be.a.function it "creates a new GoogleClientLogin", -> @googleContacts.connect(@options) login = GoogleClientLogin.last expect(login).to.exist it "stores the options in @options", -> @googleContacts.connect(@options) expect(GoogleClientLogin.last.options).to.eql { email: 'the-email' password: 'PI:PASSWORD:<PASSWORD>END_PI' service: 'contacts' } it "calls GoogleClientLogin.login", -> @stub(GoogleClientLogin.prototype, 'login') @googleContacts.connect(@options) expect(GoogleClientLogin.prototype.login).to.have.been.calledOnce describe "when success", -> it "resolves the promise", -> GoogleClientLogin.prototype.on = (event, callback) -> callback?() if event == 'login-event' @googleContacts.connect(@options).should.be.fulfilled describe "when error", -> it "rejects the promise with the error", (done) -> GoogleClientLogin.prototype.on = (event, callback) -> callback?('an-error') if event == 'error-event' @googleContacts.connect(@options).fail (err) => err.should.equal 'an-error' done() describe "#getContacts", -> beforeEach -> @options = email: 'the-email' @contacts = new GoogleContacts() @contacts.options = @options @contacts.auth = getAuthId: -> 'the-auth-id' it "makes a request to /m8/feeds/contacts/{email}/thin?alt=json&max-results=9999", -> @contacts.getContacts() expect(@request).to.have.been.calledOnce expect(@request.getCall(0).args[0]).to.eql { url: 'https://google.com/m8/feeds/contacts/the-email/thin?alt=json&max-results=9999' headers: Authorization: 'GoogleLogin auth=the-auth-id' } describe "on success", -> it "resolves the promise with the page", (done) -> responseBody = JSON.stringify({ feed: openSearch$totalResults: $t: 124 openSearch$startIndex: $t: 1 openSearch$itemsPerPage: $t: 25 entry: [ { id: $t: 'http://www.google.com/m8/feeds/contacts/PI:EMAIL:<EMAIL>END_PI@PI:EMAIL:<EMAIL>END_PI.com/base/this-is-the-id' title: $t: 'bob' gd$email: [ { address: 'PI:EMAIL:<EMAIL>END_PI' } ] } ] }) @request.callsArgWith(1, null, null, responseBody) @contacts.getContacts().then (page) => expect(page).to.eql { startIndex: 1 itemsPerPage: 25 totalResults: 124 contacts: [ { id: 'this-is-the-id', name: 'PI:NAME:<EMAIL>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI' } ] } done() describe "on error", -> it "rejects the promise", (done) -> @request.callsArgWith(1, 'the-error') @contacts.getContacts().fail -> done()
[ { "context": "nect: true, primary:null, poolSize: 50 },\n\tuser: 'admin',\n\tpass: 'UCLZk2ddmQa8CsH',\n\thost: '127.0.0.1'\n\tp", "end": 138, "score": 0.9986827373504639, "start": 133, "tag": "USERNAME", "value": "admin" }, { "context": "ary:null, poolSize: 50 },\n\tuser: 'admin',\n\...
init/database.coffee
winnlab/Polpharma
0
mongoose = require 'mongoose' async = require 'async' opts = server: { auto_reconnect: true, primary:null, poolSize: 50 }, user: 'admin', pass: 'UCLZk2ddmQa8CsH', host: '127.0.0.1' port: '27017' database: 'Polpharma' primary: null connString = 'mongodb://'+opts.user+":"+opts.pass+"@"+opts.host+":"+opts.port+"/"+opts.database+"?auto_reconnect=true" mongoose.connection.on 'error', (err) -> console.dir err process.exit() # setTimeout(() -> # mongoose.connect connString, opts # console.log 'Could not connect to mongo server' # console.log err # , 1000) mongoose.connection.on 'open', (err) -> console.log 'Connected to mongo server' mongoose.connect connString, opts
54071
mongoose = require 'mongoose' async = require 'async' opts = server: { auto_reconnect: true, primary:null, poolSize: 50 }, user: 'admin', pass: '<PASSWORD>', host: '127.0.0.1' port: '27017' database: 'Polpharma' primary: null connString = 'mongodb://'+opts.user+":"+opts.pass+"@"+opts.host+":"+opts.port+"/"+opts.database+"?auto_reconnect=true" mongoose.connection.on 'error', (err) -> console.dir err process.exit() # setTimeout(() -> # mongoose.connect connString, opts # console.log 'Could not connect to mongo server' # console.log err # , 1000) mongoose.connection.on 'open', (err) -> console.log 'Connected to mongo server' mongoose.connect connString, opts
true
mongoose = require 'mongoose' async = require 'async' opts = server: { auto_reconnect: true, primary:null, poolSize: 50 }, user: 'admin', pass: 'PI:PASSWORD:<PASSWORD>END_PI', host: '127.0.0.1' port: '27017' database: 'Polpharma' primary: null connString = 'mongodb://'+opts.user+":"+opts.pass+"@"+opts.host+":"+opts.port+"/"+opts.database+"?auto_reconnect=true" mongoose.connection.on 'error', (err) -> console.dir err process.exit() # setTimeout(() -> # mongoose.connect connString, opts # console.log 'Could not connect to mongo server' # console.log err # , 1000) mongoose.connection.on 'open', (err) -> console.log 'Connected to mongo server' mongoose.connect connString, opts
[ { "context": " ,\n DOM.input\n name: 'firstName'\n placeholder: 'first name'\n ", "end": 635, "score": 0.9958428740501404, "start": 626, "tag": "NAME", "value": "firstName" }, { "context": "stName\n DOM.input\n n...
src/components/edit.coffee
brianshaler/kerplunk-identity
0
_ = require 'lodash' React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass render: -> identityConfig = @props.globals.public.identity cardComponentPath = identityConfig.contactCardComponent ? identityConfig.defaultContactCard ContactCard = @props.getComponent cardComponentPath DOM.section className: 'content' , DOM.div className: 'clearfix' , ContactCard (_.extend {}, @props), DOM.form action: '/admin/settings/identity' method: 'post' , DOM.input name: 'firstName' placeholder: 'first name' defaultValue: @props.identity.firstName DOM.input name: 'lastName' placeholder: 'last name' defaultValue: @props.identity.lastName DOM.input name: 'fullName' placeholder: 'full name' defaultValue: @props.identity.fullName DOM.input name: 'nickName' placeholder: 'nick name' defaultValue: @props.identity.nickName DOM.input type: 'submit' value: 'save' _.map @props.identity.platform, (platform) => return null unless @props.identity.data?[platform]?.profileUrl url = @props.identity.data[platform].profileUrl DOM.div key: "profile-link-#{platform}" , DOM.a href: url target: '_blank' , "#{platform}: " url.replace /^https?:\/\/(www\.)?/i, ''
30791
_ = require 'lodash' React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass render: -> identityConfig = @props.globals.public.identity cardComponentPath = identityConfig.contactCardComponent ? identityConfig.defaultContactCard ContactCard = @props.getComponent cardComponentPath DOM.section className: 'content' , DOM.div className: 'clearfix' , ContactCard (_.extend {}, @props), DOM.form action: '/admin/settings/identity' method: 'post' , DOM.input name: '<NAME>' placeholder: 'first name' defaultValue: @props.identity.firstName DOM.input name: '<NAME>' placeholder: '<NAME> name' defaultValue: @props.identity.lastName DOM.input name: 'fullName' placeholder: 'full name' defaultValue: @props.identity.fullName DOM.input name: 'nickName' placeholder: 'nick name' defaultValue: @props.identity.nickName DOM.input type: 'submit' value: 'save' _.map @props.identity.platform, (platform) => return null unless @props.identity.data?[platform]?.profileUrl url = @props.identity.data[platform].profileUrl DOM.div key: "profile-link-#{platform}" , DOM.a href: url target: '_blank' , "#{platform}: " url.replace /^https?:\/\/(www\.)?/i, ''
true
_ = require 'lodash' React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass render: -> identityConfig = @props.globals.public.identity cardComponentPath = identityConfig.contactCardComponent ? identityConfig.defaultContactCard ContactCard = @props.getComponent cardComponentPath DOM.section className: 'content' , DOM.div className: 'clearfix' , ContactCard (_.extend {}, @props), DOM.form action: '/admin/settings/identity' method: 'post' , DOM.input name: 'PI:NAME:<NAME>END_PI' placeholder: 'first name' defaultValue: @props.identity.firstName DOM.input name: 'PI:NAME:<NAME>END_PI' placeholder: 'PI:NAME:<NAME>END_PI name' defaultValue: @props.identity.lastName DOM.input name: 'fullName' placeholder: 'full name' defaultValue: @props.identity.fullName DOM.input name: 'nickName' placeholder: 'nick name' defaultValue: @props.identity.nickName DOM.input type: 'submit' value: 'save' _.map @props.identity.platform, (platform) => return null unless @props.identity.data?[platform]?.profileUrl url = @props.identity.data[platform].profileUrl DOM.div key: "profile-link-#{platform}" , DOM.a href: url target: '_blank' , "#{platform}: " url.replace /^https?:\/\/(www\.)?/i, ''
[ { "context": "\nTendina jQuery plugin v0.11.1\n\nCopyright (c) 2015 Ivan Prignano\nReleased under the MIT License\n###\n\n(($, window) ", "end": 67, "score": 0.9998838305473328, "start": 54, "tag": "NAME", "value": "Ivan Prignano" } ]
src/tendina.coffee
iprignano/tendina
77
### Tendina jQuery plugin v0.11.1 Copyright (c) 2015 Ivan Prignano Released under the MIT License ### (($, window) -> class Tendina # Default options defaults: animate: true speed: 500 onHover: false hoverDelay: 200 activeMenu: null constructor: (el, options) -> @options = $.extend({}, @defaults, options) @$el = $(el) # Gets element selector - needed # for multiple menu initialization @elSelector = @_getSelector(@$el) # Adds tendina class to element # for better reference @$el.addClass('tendina') # Sets a class variable for anchor # elements that will be bound to the handler @linkSelector = "#{@elSelector} a" @$listElements = $(@linkSelector).parent('li') # Hides submenus on document.ready @_hideSubmenus() # Set the event type (hover/click) @mouseEvent = if @options.onHover is true then 'mouseenter.tendina' else 'click.tendina' # Binds handler function # to interactive elements @_bindEvents() # Opens an active menu # if specified in the options @_openActiveMenu(@options.activeMenu) if @options.activeMenu isnt null # ================== # Private Methods # ================== _bindEvents: -> $(document).on @mouseEvent, @linkSelector, @_eventHandler _unbindEvents: -> $(document).off @mouseEvent _getSelector: (el) -> firstClass = $(el).attr('class')?.split(' ')[0] elId = $(el).attr('id') if (elId isnt undefined) then "##{elId}" else ".#{firstClass}" _isFirstLevel: (targetEl) -> # Checks if target element # is a first level menu return true if $(targetEl).parent().parent().hasClass('tendina') _eventHandler: (event) => targetEl = event.currentTarget # Opens or closes target menu if @_hasChildren(targetEl) and @_IsChildrenHidden(targetEl) event.preventDefault() if @options.onHover setTimeout => @_openSubmenu(targetEl) if $(targetEl).is(':hover') , @options.hoverDelay else @_openSubmenu(targetEl) else if @_isCurrentlyOpen(targetEl) and @_hasChildren(targetEl) event.preventDefault() @_closeSubmenu(targetEl) unless @options.onHover _openSubmenu: (el) -> $targetMenu = $(el).next('ul') $openMenus = @$el.find('> .selected ul').not($targetMenu).not($targetMenu.parents('ul')) # Add selected class to menu $(el).parent('li').addClass('selected') # Closes all currently open menus # and opens the targeted one @_close $openMenus @$el.find('.selected') .not($targetMenu.parents('li')) .removeClass('selected') @_open $targetMenu # After opening, fire callback @options.openCallback $(el).parent() if @options.openCallback _closeSubmenu: (el) -> $targetMenu = $(el).next('ul') $nestedMenus = $targetMenu.find('li.selected') # Removes the selected class from the # menu that's being closed $(el) .parent() .removeClass('selected') # Closes the target menu @_close $targetMenu # Removes the selected class from # any open nested submenu and closes them $nestedMenus.removeClass('selected') @_close $nestedMenus.find('ul') # After closing, fire callback @options.closeCallback $(el).parent() if @options.closeCallback _open: ($el) -> if @options.animate $el.stop(true, true).slideDown(@options.speed) else $el.show() _close: ($el) -> if @options.animate $el.stop(true, true).slideUp(@options.speed) else $el.hide() _hasChildren: (el) -> # Checks if clicked el is not a 'leaf' $(el).next('ul').length > 0 _IsChildrenHidden: (el) -> # Checks if children list is hidden $(el).next('ul').is(':hidden') _isCurrentlyOpen: (el) -> $(el).parent().hasClass 'selected' _hideSubmenus: -> @$el.find('ul').hide() _showSubmenus: -> @$el.find('ul').show() @$el.find('li').addClass 'selected' _openActiveMenu: (element) -> $activeMenu = if element instanceof jQuery then element else @$el.find(element) $activeParents = $activeMenu.closest('ul').parents('li').find('> a') # Deeper than first level menus if @_hasChildren($activeParents) and @_IsChildrenHidden($activeParents) $activeParents.next('ul').show() # First level menu else $activeMenu.next('ul').show() # Adds selected class to opened menu # and all its parents $activeMenu.parent().addClass('selected') $activeParents.parent().addClass('selected') # ================== # API # ================== destroy: -> # Remove plugin instance @$el.removeData 'tendina' # Unbind events, remove namespace class # and show hidden submenus @_unbindEvents() @_showSubmenus() @$el.removeClass 'tendina' @$el.find('.selected').removeClass('selected') hideAll: -> @_hideSubmenus() showAll: -> @_showSubmenus() # ================== # jQuery Extend # ================== $.fn.extend tendina: (option, args...) -> @each -> $this = $(this) data = $this.data('tendina') # Instances a new Tendina class # if not already done if !data $this.data 'tendina', (data = new Tendina(this, option)) if typeof option == 'string' data[option].apply(data, args) ) window.jQuery, window
150104
### Tendina jQuery plugin v0.11.1 Copyright (c) 2015 <NAME> Released under the MIT License ### (($, window) -> class Tendina # Default options defaults: animate: true speed: 500 onHover: false hoverDelay: 200 activeMenu: null constructor: (el, options) -> @options = $.extend({}, @defaults, options) @$el = $(el) # Gets element selector - needed # for multiple menu initialization @elSelector = @_getSelector(@$el) # Adds tendina class to element # for better reference @$el.addClass('tendina') # Sets a class variable for anchor # elements that will be bound to the handler @linkSelector = "#{@elSelector} a" @$listElements = $(@linkSelector).parent('li') # Hides submenus on document.ready @_hideSubmenus() # Set the event type (hover/click) @mouseEvent = if @options.onHover is true then 'mouseenter.tendina' else 'click.tendina' # Binds handler function # to interactive elements @_bindEvents() # Opens an active menu # if specified in the options @_openActiveMenu(@options.activeMenu) if @options.activeMenu isnt null # ================== # Private Methods # ================== _bindEvents: -> $(document).on @mouseEvent, @linkSelector, @_eventHandler _unbindEvents: -> $(document).off @mouseEvent _getSelector: (el) -> firstClass = $(el).attr('class')?.split(' ')[0] elId = $(el).attr('id') if (elId isnt undefined) then "##{elId}" else ".#{firstClass}" _isFirstLevel: (targetEl) -> # Checks if target element # is a first level menu return true if $(targetEl).parent().parent().hasClass('tendina') _eventHandler: (event) => targetEl = event.currentTarget # Opens or closes target menu if @_hasChildren(targetEl) and @_IsChildrenHidden(targetEl) event.preventDefault() if @options.onHover setTimeout => @_openSubmenu(targetEl) if $(targetEl).is(':hover') , @options.hoverDelay else @_openSubmenu(targetEl) else if @_isCurrentlyOpen(targetEl) and @_hasChildren(targetEl) event.preventDefault() @_closeSubmenu(targetEl) unless @options.onHover _openSubmenu: (el) -> $targetMenu = $(el).next('ul') $openMenus = @$el.find('> .selected ul').not($targetMenu).not($targetMenu.parents('ul')) # Add selected class to menu $(el).parent('li').addClass('selected') # Closes all currently open menus # and opens the targeted one @_close $openMenus @$el.find('.selected') .not($targetMenu.parents('li')) .removeClass('selected') @_open $targetMenu # After opening, fire callback @options.openCallback $(el).parent() if @options.openCallback _closeSubmenu: (el) -> $targetMenu = $(el).next('ul') $nestedMenus = $targetMenu.find('li.selected') # Removes the selected class from the # menu that's being closed $(el) .parent() .removeClass('selected') # Closes the target menu @_close $targetMenu # Removes the selected class from # any open nested submenu and closes them $nestedMenus.removeClass('selected') @_close $nestedMenus.find('ul') # After closing, fire callback @options.closeCallback $(el).parent() if @options.closeCallback _open: ($el) -> if @options.animate $el.stop(true, true).slideDown(@options.speed) else $el.show() _close: ($el) -> if @options.animate $el.stop(true, true).slideUp(@options.speed) else $el.hide() _hasChildren: (el) -> # Checks if clicked el is not a 'leaf' $(el).next('ul').length > 0 _IsChildrenHidden: (el) -> # Checks if children list is hidden $(el).next('ul').is(':hidden') _isCurrentlyOpen: (el) -> $(el).parent().hasClass 'selected' _hideSubmenus: -> @$el.find('ul').hide() _showSubmenus: -> @$el.find('ul').show() @$el.find('li').addClass 'selected' _openActiveMenu: (element) -> $activeMenu = if element instanceof jQuery then element else @$el.find(element) $activeParents = $activeMenu.closest('ul').parents('li').find('> a') # Deeper than first level menus if @_hasChildren($activeParents) and @_IsChildrenHidden($activeParents) $activeParents.next('ul').show() # First level menu else $activeMenu.next('ul').show() # Adds selected class to opened menu # and all its parents $activeMenu.parent().addClass('selected') $activeParents.parent().addClass('selected') # ================== # API # ================== destroy: -> # Remove plugin instance @$el.removeData 'tendina' # Unbind events, remove namespace class # and show hidden submenus @_unbindEvents() @_showSubmenus() @$el.removeClass 'tendina' @$el.find('.selected').removeClass('selected') hideAll: -> @_hideSubmenus() showAll: -> @_showSubmenus() # ================== # jQuery Extend # ================== $.fn.extend tendina: (option, args...) -> @each -> $this = $(this) data = $this.data('tendina') # Instances a new Tendina class # if not already done if !data $this.data 'tendina', (data = new Tendina(this, option)) if typeof option == 'string' data[option].apply(data, args) ) window.jQuery, window
true
### Tendina jQuery plugin v0.11.1 Copyright (c) 2015 PI:NAME:<NAME>END_PI Released under the MIT License ### (($, window) -> class Tendina # Default options defaults: animate: true speed: 500 onHover: false hoverDelay: 200 activeMenu: null constructor: (el, options) -> @options = $.extend({}, @defaults, options) @$el = $(el) # Gets element selector - needed # for multiple menu initialization @elSelector = @_getSelector(@$el) # Adds tendina class to element # for better reference @$el.addClass('tendina') # Sets a class variable for anchor # elements that will be bound to the handler @linkSelector = "#{@elSelector} a" @$listElements = $(@linkSelector).parent('li') # Hides submenus on document.ready @_hideSubmenus() # Set the event type (hover/click) @mouseEvent = if @options.onHover is true then 'mouseenter.tendina' else 'click.tendina' # Binds handler function # to interactive elements @_bindEvents() # Opens an active menu # if specified in the options @_openActiveMenu(@options.activeMenu) if @options.activeMenu isnt null # ================== # Private Methods # ================== _bindEvents: -> $(document).on @mouseEvent, @linkSelector, @_eventHandler _unbindEvents: -> $(document).off @mouseEvent _getSelector: (el) -> firstClass = $(el).attr('class')?.split(' ')[0] elId = $(el).attr('id') if (elId isnt undefined) then "##{elId}" else ".#{firstClass}" _isFirstLevel: (targetEl) -> # Checks if target element # is a first level menu return true if $(targetEl).parent().parent().hasClass('tendina') _eventHandler: (event) => targetEl = event.currentTarget # Opens or closes target menu if @_hasChildren(targetEl) and @_IsChildrenHidden(targetEl) event.preventDefault() if @options.onHover setTimeout => @_openSubmenu(targetEl) if $(targetEl).is(':hover') , @options.hoverDelay else @_openSubmenu(targetEl) else if @_isCurrentlyOpen(targetEl) and @_hasChildren(targetEl) event.preventDefault() @_closeSubmenu(targetEl) unless @options.onHover _openSubmenu: (el) -> $targetMenu = $(el).next('ul') $openMenus = @$el.find('> .selected ul').not($targetMenu).not($targetMenu.parents('ul')) # Add selected class to menu $(el).parent('li').addClass('selected') # Closes all currently open menus # and opens the targeted one @_close $openMenus @$el.find('.selected') .not($targetMenu.parents('li')) .removeClass('selected') @_open $targetMenu # After opening, fire callback @options.openCallback $(el).parent() if @options.openCallback _closeSubmenu: (el) -> $targetMenu = $(el).next('ul') $nestedMenus = $targetMenu.find('li.selected') # Removes the selected class from the # menu that's being closed $(el) .parent() .removeClass('selected') # Closes the target menu @_close $targetMenu # Removes the selected class from # any open nested submenu and closes them $nestedMenus.removeClass('selected') @_close $nestedMenus.find('ul') # After closing, fire callback @options.closeCallback $(el).parent() if @options.closeCallback _open: ($el) -> if @options.animate $el.stop(true, true).slideDown(@options.speed) else $el.show() _close: ($el) -> if @options.animate $el.stop(true, true).slideUp(@options.speed) else $el.hide() _hasChildren: (el) -> # Checks if clicked el is not a 'leaf' $(el).next('ul').length > 0 _IsChildrenHidden: (el) -> # Checks if children list is hidden $(el).next('ul').is(':hidden') _isCurrentlyOpen: (el) -> $(el).parent().hasClass 'selected' _hideSubmenus: -> @$el.find('ul').hide() _showSubmenus: -> @$el.find('ul').show() @$el.find('li').addClass 'selected' _openActiveMenu: (element) -> $activeMenu = if element instanceof jQuery then element else @$el.find(element) $activeParents = $activeMenu.closest('ul').parents('li').find('> a') # Deeper than first level menus if @_hasChildren($activeParents) and @_IsChildrenHidden($activeParents) $activeParents.next('ul').show() # First level menu else $activeMenu.next('ul').show() # Adds selected class to opened menu # and all its parents $activeMenu.parent().addClass('selected') $activeParents.parent().addClass('selected') # ================== # API # ================== destroy: -> # Remove plugin instance @$el.removeData 'tendina' # Unbind events, remove namespace class # and show hidden submenus @_unbindEvents() @_showSubmenus() @$el.removeClass 'tendina' @$el.find('.selected').removeClass('selected') hideAll: -> @_hideSubmenus() showAll: -> @_showSubmenus() # ================== # jQuery Extend # ================== $.fn.extend tendina: (option, args...) -> @each -> $this = $(this) data = $this.data('tendina') # Instances a new Tendina class # if not already done if !data $this.data 'tendina', (data = new Tendina(this, option)) if typeof option == 'string' data[option].apply(data, args) ) window.jQuery, window
[ { "context": "on.fullName()\", ->\n eq uEx.person.fullName(), 'John Doe'\n\n it \"person.age\", ->\n eq uEx.person.age, 40", "end": 272, "score": 0.9998593926429749, "start": 264, "tag": "NAME", "value": "John Doe" } ]
source/spec/urequire-example-spec.coffee
anodynos/urequire-example
2
# All specHelper imports are injected via `urequire-rc-import` # See 'specHelpers' imports in uRequire:spec task # `uEx` var injected by `dependencies: imports` describe " 'urequire-example' has:", -> it "person.fullName()", -> eq uEx.person.fullName(), 'John Doe' it "person.age", -> eq uEx.person.age, 40 it "add function", -> tru _.isFunction uEx.add eq uEx.add(20, 18), 38 eq uEx.calc.add(20, 8), 28 it "calc.multiply", -> tru _.isFunction uEx.calc.multiply eq uEx.calc.multiply(18, 2), 36 it "person.eat food", -> eq uEx.person.eat('food'), 'ate food' it "VERSION `#{uEx.VERSION}`, #{ if __isNode "running on node, is the exact `package.version`." else "NOT running on node, it just exists." }", -> if __isNode eq uEx.VERSION, JSON.parse(require('fs').readFileSync process.cwd() + '/package.json').version else ok uEx.VERSION
191911
# All specHelper imports are injected via `urequire-rc-import` # See 'specHelpers' imports in uRequire:spec task # `uEx` var injected by `dependencies: imports` describe " 'urequire-example' has:", -> it "person.fullName()", -> eq uEx.person.fullName(), '<NAME>' it "person.age", -> eq uEx.person.age, 40 it "add function", -> tru _.isFunction uEx.add eq uEx.add(20, 18), 38 eq uEx.calc.add(20, 8), 28 it "calc.multiply", -> tru _.isFunction uEx.calc.multiply eq uEx.calc.multiply(18, 2), 36 it "person.eat food", -> eq uEx.person.eat('food'), 'ate food' it "VERSION `#{uEx.VERSION}`, #{ if __isNode "running on node, is the exact `package.version`." else "NOT running on node, it just exists." }", -> if __isNode eq uEx.VERSION, JSON.parse(require('fs').readFileSync process.cwd() + '/package.json').version else ok uEx.VERSION
true
# All specHelper imports are injected via `urequire-rc-import` # See 'specHelpers' imports in uRequire:spec task # `uEx` var injected by `dependencies: imports` describe " 'urequire-example' has:", -> it "person.fullName()", -> eq uEx.person.fullName(), 'PI:NAME:<NAME>END_PI' it "person.age", -> eq uEx.person.age, 40 it "add function", -> tru _.isFunction uEx.add eq uEx.add(20, 18), 38 eq uEx.calc.add(20, 8), 28 it "calc.multiply", -> tru _.isFunction uEx.calc.multiply eq uEx.calc.multiply(18, 2), 36 it "person.eat food", -> eq uEx.person.eat('food'), 'ate food' it "VERSION `#{uEx.VERSION}`, #{ if __isNode "running on node, is the exact `package.version`." else "NOT running on node, it just exists." }", -> if __isNode eq uEx.VERSION, JSON.parse(require('fs').readFileSync process.cwd() + '/package.json').version else ok uEx.VERSION
[ { "context": "fault skill\n# value corresponds to a level of 0.\n\nalice = {}\nalice.skill = [25.0, 25.0/3.0]\n\nbob = {}\nbob", "end": 754, "score": 0.9902709722518921, "start": 749, "tag": "NAME", "value": "alice" }, { "context": "\n# value corresponds to a level of 0.\n\nalice = {...
convert/sample.coffee
freethenation/node-trueskill
28
trueskill = require "./trueskill" # The output of this program should match the output of the TrueSkill # calculator at: # # http://atom.research.microsoft.com/trueskill/rankcalculator.aspx # # (Select game mode "custom", create 4 players each on their own team, # check the second "Draw?" box to indicate a tie for second place, # then click "Recalculate Skill Level Distribution". The mu and sigma # values in the "after game" section should match what this program # prints. # The objects we pass to AdjustPlayers can be anything with skill and # rank attributes. # Create four players. Assign each of them the default skill. The # player ranking (their "level") is mu-3*sigma, so the default skill # value corresponds to a level of 0. alice = {} alice.skill = [25.0, 25.0/3.0] bob = {} bob.skill = [25.0, 25.0/3.0] chris = {} chris.skill = [25.0, 25.0/3.0] darren = {} darren.skill = [25.0, 25.0/3.0] # The four players play a game. Alice wins, Bob and Chris tie for # second, Darren comes in last. The actual numerical values of the # ranks don't matter, they could be (1, 2, 2, 4) or (1, 2, 2, 3) or # (23, 45, 45, 67). All that matters is that a smaller rank beats a # larger one, and equal ranks indicate draws. alice.rank = 1 bob.rank = 2 chris.rank = 2 darren.rank = 4 # Do the computation to find each player's new skill estimate. trueskill.AdjustPlayers([alice, bob, chris, darren]) # Print the results. console.log alice.skill console.log bob.skill console.log chris.skill console.log darren.skill
40962
trueskill = require "./trueskill" # The output of this program should match the output of the TrueSkill # calculator at: # # http://atom.research.microsoft.com/trueskill/rankcalculator.aspx # # (Select game mode "custom", create 4 players each on their own team, # check the second "Draw?" box to indicate a tie for second place, # then click "Recalculate Skill Level Distribution". The mu and sigma # values in the "after game" section should match what this program # prints. # The objects we pass to AdjustPlayers can be anything with skill and # rank attributes. # Create four players. Assign each of them the default skill. The # player ranking (their "level") is mu-3*sigma, so the default skill # value corresponds to a level of 0. <NAME> = {} <NAME>.skill = [25.0, 25.0/3.0] <NAME> = {} bob.skill = [25.0, 25.0/3.0] <NAME> = {} chris.skill = [25.0, 25.0/3.0] <NAME> = {} darren.skill = [25.0, 25.0/3.0] # The four players play a game. <NAME> wins, <NAME> and <NAME> tie for # second, <NAME> comes in last. The actual numerical values of the # ranks don't matter, they could be (1, 2, 2, 4) or (1, 2, 2, 3) or # (23, 45, 45, 67). All that matters is that a smaller rank beats a # larger one, and equal ranks indicate draws. alice.rank = 1 bob.rank = 2 <NAME>.rank = 2 <NAME>ren.rank = 4 # Do the computation to find each player's new skill estimate. trueskill.AdjustPlayers([<NAME>, <NAME>, <NAME>, <NAME>]) # Print the results. console.log <NAME>.skill console.log bob.skill console.log <NAME>.skill console.log darren.skill
true
trueskill = require "./trueskill" # The output of this program should match the output of the TrueSkill # calculator at: # # http://atom.research.microsoft.com/trueskill/rankcalculator.aspx # # (Select game mode "custom", create 4 players each on their own team, # check the second "Draw?" box to indicate a tie for second place, # then click "Recalculate Skill Level Distribution". The mu and sigma # values in the "after game" section should match what this program # prints. # The objects we pass to AdjustPlayers can be anything with skill and # rank attributes. # Create four players. Assign each of them the default skill. The # player ranking (their "level") is mu-3*sigma, so the default skill # value corresponds to a level of 0. PI:NAME:<NAME>END_PI = {} PI:NAME:<NAME>END_PI.skill = [25.0, 25.0/3.0] PI:NAME:<NAME>END_PI = {} bob.skill = [25.0, 25.0/3.0] PI:NAME:<NAME>END_PI = {} chris.skill = [25.0, 25.0/3.0] PI:NAME:<NAME>END_PI = {} darren.skill = [25.0, 25.0/3.0] # The four players play a game. PI:NAME:<NAME>END_PI wins, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI tie for # second, PI:NAME:<NAME>END_PI comes in last. The actual numerical values of the # ranks don't matter, they could be (1, 2, 2, 4) or (1, 2, 2, 3) or # (23, 45, 45, 67). All that matters is that a smaller rank beats a # larger one, and equal ranks indicate draws. alice.rank = 1 bob.rank = 2 PI:NAME:<NAME>END_PI.rank = 2 PI:NAME:<NAME>END_PIren.rank = 4 # Do the computation to find each player's new skill estimate. trueskill.AdjustPlayers([PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI]) # Print the results. console.log PI:NAME:<NAME>END_PI.skill console.log bob.skill console.log PI:NAME:<NAME>END_PI.skill console.log darren.skill
[ { "context": "window.GOOGLE_MAPS_API_KEY = 'AIzaSyDje2Wl4c1HjXvqkjH9sk3lknoRweI89u8'\n", "end": 69, "score": 0.9997097849845886, "start": 30, "tag": "KEY", "value": "AIzaSyDje2Wl4c1HjXvqkjH9sk3lknoRweI89u8" } ]
app/client/config/maps.coffee
AURIN/esp
0
window.GOOGLE_MAPS_API_KEY = 'AIzaSyDje2Wl4c1HjXvqkjH9sk3lknoRweI89u8'
45199
window.GOOGLE_MAPS_API_KEY = '<KEY>'
true
window.GOOGLE_MAPS_API_KEY = 'PI:KEY:<KEY>END_PI'
[ { "context": "}\n />\n\nVerifyEmailModal.defaultProps =\n email: 'xxxxx@xxxxxx.com'\n\n\n", "end": 678, "score": 0.9999013543128967, "start": 662, "tag": "EMAIL", "value": "xxxxx@xxxxxx.com" } ]
client/component-lab/VerifyEmailModal/VerifyEmailModal.coffee
lionheart1022/koding
0
React = require 'react' Dialog = require 'lab/Dialog' module.exports = VerifyEmailModal = ({ isOpen, onButtonClick, email }) -> message = " Please check your inbox and click the link in that email to verify your work email address. After verification, your trial will be extended to 30 days and any free credit will be added to your account. " <Dialog isOpen={isOpen} showAlien={yes} type='danger' title='Please Verify Your Email Address' subtitle="We sent an email to #{email}" message={message} buttonTitle='CONTINUE TO KODING' onButtonClick={onButtonClick} /> VerifyEmailModal.defaultProps = email: 'xxxxx@xxxxxx.com'
87272
React = require 'react' Dialog = require 'lab/Dialog' module.exports = VerifyEmailModal = ({ isOpen, onButtonClick, email }) -> message = " Please check your inbox and click the link in that email to verify your work email address. After verification, your trial will be extended to 30 days and any free credit will be added to your account. " <Dialog isOpen={isOpen} showAlien={yes} type='danger' title='Please Verify Your Email Address' subtitle="We sent an email to #{email}" message={message} buttonTitle='CONTINUE TO KODING' onButtonClick={onButtonClick} /> VerifyEmailModal.defaultProps = email: '<EMAIL>'
true
React = require 'react' Dialog = require 'lab/Dialog' module.exports = VerifyEmailModal = ({ isOpen, onButtonClick, email }) -> message = " Please check your inbox and click the link in that email to verify your work email address. After verification, your trial will be extended to 30 days and any free credit will be added to your account. " <Dialog isOpen={isOpen} showAlien={yes} type='danger' title='Please Verify Your Email Address' subtitle="We sent an email to #{email}" message={message} buttonTitle='CONTINUE TO KODING' onButtonClick={onButtonClick} /> VerifyEmailModal.defaultProps = email: 'PI:EMAIL:<EMAIL>END_PI'
[ { "context": "extends events.EventEmitter\n\n @MDNS_ADDRESS = \"224.0.0.251\"\n @MDNS_PORT = 5353\n @MDNS_TTL = 1\n @MDN", "end": 885, "score": 0.9997924566268921, "start": 874, "tag": "IP_ADDRESS", "value": "224.0.0.251" }, { "context": " @socket.bind mdnsSdSe...
lib/mdns/mdnsSdServer.coffee
waitliu/flingd-coffee
0
# # Copyright (C) 2013-2014, The OpenFlint Open Source Project # # 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. # events = require "events" os = require "os" { Log } = rekuire "log/Log" { MDNSHelper } = rekuire "mdns/MDNSHelper" { Platform } = rekuire "platform/Platform" class mdnsSdServer extends events.EventEmitter @MDNS_ADDRESS = "224.0.0.251" @MDNS_PORT = 5353 @MDNS_TTL = 1 @MDNS_LOOPBACK_MODE = true constructor: -> events.EventEmitter.call(this) @on "ready", => Log.d "MDNSServer is ready !" @fullProtocol @serverName @txtRecord @serverPort @flags @address = @getAddress() @localName @dnsSdResponse @dnsSdKeepResponse @status = false getAddress: -> address = {} ifaces = os.networkInterfaces() for k,v of ifaces if (k.toLowerCase().indexOf "lo") < 0 ipadd = {} for i in v if i.family == "IPv4" ipadd.ipv4 = i.address if i.family == "IPv6" ipadd.ipv6 = i.address # castd node ipv6 not found if ipadd.ipv4 #&& ipadd.ipv6 address = ipadd break return address set: (fullProtocol, port, options) -> @fullProtocol = fullProtocol @serverPort = port @serverName = options.name @txtRecord = options.txtRecord @flags = options.flags @resetDnsSdResponse() resetDnsSdResponse: -> @address = @getAddress() @localName = @serverName + @address.ipv4 if @address.ipv4 @dnsSdResponse = MDNSHelper.creatDnsSdResponse 0, @fullProtocol, @serverName, @serverPort, @txtRecord, @address, @localName @dnsSdKeepResponse = MDNSHelper.creatDnsSdKeepResponse 0, @fullProtocol, @serverName, @serverPort, @txtRecord, @address, @localName _start: -> if !@running @address = @getAddress() @resetDnsSdResponse() if @address.ipv4 && @dnsSdResponse Log.d "Starting MDNSServer ..." dgram = require "dgram" @socket = dgram.createSocket "udp4" @socket.on "error", (err) => Log.e err @socket.on "message", (data, rinfo) => @onReceive data, rinfo.address, rinfo.port @socket.on "listening", => Log.d "MDNS socket is listened" @socket.setMulticastTTL mdnsSdServer.MDNS_TTL @socket.setMulticastLoopback mdnsSdServer.MDNS_LOOPBACK_MODE @socket.bind mdnsSdServer.MDNS_PORT, "0.0.0.0", => Log.d "MDNS socket is binded" @socket.addMembership mdnsSdServer.MDNS_ADDRESS, @address.ipv4 @running = true @listen() @emit "ready" @status = true @keepActive() else Log.d "MDNSServer start fail" if not @dnsSdResponse Log.d "MDNSServer dont config , please config" if not @address.ipv4 Log.d "MDNSServer dont ipv4, please check network" start: -> @_start() @startLoop = setInterval (=> @_start() ), 5000 # @keepActiveLoop = setInterval (=> # @keepActive() ), 8000 stop: -> @socket.close() @status = false clearInterval @start_loop clearInterval @keep_active Log.d "MDNSServer stop" keepActive: -> if @dnsSdKeepResponse @dnsSdKeepResponse.transactionID = 0 buff = new Buffer MDNSHelper.encodeMessage @dnsSdKeepResponse if @status @socket.send buff, 0, buff.length, mdnsSdServer.MDNS_PORT, mdnsSdServer.MDNS_ADDRESS, => Log.i "mdnsResponse to #{mdnsSdServer.MDNS_ADDRESS}:#{mdnsSdServer.MDNS_PORT} done".red listen: -> if not @running then return onReceive: (data, address, port) -> try message = MDNSHelper.decodeMessage data catch error Log.d "error: #{error}" Log.d "#{address}: data #{data}" if message && message.isQuery for question in message.questions if question.name.toLowerCase() is @fullProtocol.toLowerCase() if question.type is MDNSHelper.TYPE_PTR @dnsSdResponse.transactionID = message.transactionID buff = new Buffer MDNSHelper.encodeMessage @dnsSdResponse Log.i "mdns receive message: #{message}".red @socket.send buff, 0, buff.length, port, address, => Log.i "mdnsResponse to #{address}:#{port} done".red module.exports.mdnsSdServer = mdnsSdServer
178637
# # Copyright (C) 2013-2014, The OpenFlint Open Source Project # # 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. # events = require "events" os = require "os" { Log } = rekuire "log/Log" { MDNSHelper } = rekuire "mdns/MDNSHelper" { Platform } = rekuire "platform/Platform" class mdnsSdServer extends events.EventEmitter @MDNS_ADDRESS = "172.16.31.10" @MDNS_PORT = 5353 @MDNS_TTL = 1 @MDNS_LOOPBACK_MODE = true constructor: -> events.EventEmitter.call(this) @on "ready", => Log.d "MDNSServer is ready !" @fullProtocol @serverName @txtRecord @serverPort @flags @address = @getAddress() @localName @dnsSdResponse @dnsSdKeepResponse @status = false getAddress: -> address = {} ifaces = os.networkInterfaces() for k,v of ifaces if (k.toLowerCase().indexOf "lo") < 0 ipadd = {} for i in v if i.family == "IPv4" ipadd.ipv4 = i.address if i.family == "IPv6" ipadd.ipv6 = i.address # castd node ipv6 not found if ipadd.ipv4 #&& ipadd.ipv6 address = ipadd break return address set: (fullProtocol, port, options) -> @fullProtocol = fullProtocol @serverPort = port @serverName = options.name @txtRecord = options.txtRecord @flags = options.flags @resetDnsSdResponse() resetDnsSdResponse: -> @address = @getAddress() @localName = @serverName + @address.ipv4 if @address.ipv4 @dnsSdResponse = MDNSHelper.creatDnsSdResponse 0, @fullProtocol, @serverName, @serverPort, @txtRecord, @address, @localName @dnsSdKeepResponse = MDNSHelper.creatDnsSdKeepResponse 0, @fullProtocol, @serverName, @serverPort, @txtRecord, @address, @localName _start: -> if !@running @address = @getAddress() @resetDnsSdResponse() if @address.ipv4 && @dnsSdResponse Log.d "Starting MDNSServer ..." dgram = require "dgram" @socket = dgram.createSocket "udp4" @socket.on "error", (err) => Log.e err @socket.on "message", (data, rinfo) => @onReceive data, rinfo.address, rinfo.port @socket.on "listening", => Log.d "MDNS socket is listened" @socket.setMulticastTTL mdnsSdServer.MDNS_TTL @socket.setMulticastLoopback mdnsSdServer.MDNS_LOOPBACK_MODE @socket.bind mdnsSdServer.MDNS_PORT, "0.0.0.0", => Log.d "MDNS socket is binded" @socket.addMembership mdnsSdServer.MDNS_ADDRESS, @address.ipv4 @running = true @listen() @emit "ready" @status = true @keepActive() else Log.d "MDNSServer start fail" if not @dnsSdResponse Log.d "MDNSServer dont config , please config" if not @address.ipv4 Log.d "MDNSServer dont ipv4, please check network" start: -> @_start() @startLoop = setInterval (=> @_start() ), 5000 # @keepActiveLoop = setInterval (=> # @keepActive() ), 8000 stop: -> @socket.close() @status = false clearInterval @start_loop clearInterval @keep_active Log.d "MDNSServer stop" keepActive: -> if @dnsSdKeepResponse @dnsSdKeepResponse.transactionID = 0 buff = new Buffer MDNSHelper.encodeMessage @dnsSdKeepResponse if @status @socket.send buff, 0, buff.length, mdnsSdServer.MDNS_PORT, mdnsSdServer.MDNS_ADDRESS, => Log.i "mdnsResponse to #{mdnsSdServer.MDNS_ADDRESS}:#{mdnsSdServer.MDNS_PORT} done".red listen: -> if not @running then return onReceive: (data, address, port) -> try message = MDNSHelper.decodeMessage data catch error Log.d "error: #{error}" Log.d "#{address}: data #{data}" if message && message.isQuery for question in message.questions if question.name.toLowerCase() is @fullProtocol.toLowerCase() if question.type is MDNSHelper.TYPE_PTR @dnsSdResponse.transactionID = message.transactionID buff = new Buffer MDNSHelper.encodeMessage @dnsSdResponse Log.i "mdns receive message: #{message}".red @socket.send buff, 0, buff.length, port, address, => Log.i "mdnsResponse to #{address}:#{port} done".red module.exports.mdnsSdServer = mdnsSdServer
true
# # Copyright (C) 2013-2014, The OpenFlint Open Source Project # # 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. # events = require "events" os = require "os" { Log } = rekuire "log/Log" { MDNSHelper } = rekuire "mdns/MDNSHelper" { Platform } = rekuire "platform/Platform" class mdnsSdServer extends events.EventEmitter @MDNS_ADDRESS = "PI:IP_ADDRESS:172.16.31.10END_PI" @MDNS_PORT = 5353 @MDNS_TTL = 1 @MDNS_LOOPBACK_MODE = true constructor: -> events.EventEmitter.call(this) @on "ready", => Log.d "MDNSServer is ready !" @fullProtocol @serverName @txtRecord @serverPort @flags @address = @getAddress() @localName @dnsSdResponse @dnsSdKeepResponse @status = false getAddress: -> address = {} ifaces = os.networkInterfaces() for k,v of ifaces if (k.toLowerCase().indexOf "lo") < 0 ipadd = {} for i in v if i.family == "IPv4" ipadd.ipv4 = i.address if i.family == "IPv6" ipadd.ipv6 = i.address # castd node ipv6 not found if ipadd.ipv4 #&& ipadd.ipv6 address = ipadd break return address set: (fullProtocol, port, options) -> @fullProtocol = fullProtocol @serverPort = port @serverName = options.name @txtRecord = options.txtRecord @flags = options.flags @resetDnsSdResponse() resetDnsSdResponse: -> @address = @getAddress() @localName = @serverName + @address.ipv4 if @address.ipv4 @dnsSdResponse = MDNSHelper.creatDnsSdResponse 0, @fullProtocol, @serverName, @serverPort, @txtRecord, @address, @localName @dnsSdKeepResponse = MDNSHelper.creatDnsSdKeepResponse 0, @fullProtocol, @serverName, @serverPort, @txtRecord, @address, @localName _start: -> if !@running @address = @getAddress() @resetDnsSdResponse() if @address.ipv4 && @dnsSdResponse Log.d "Starting MDNSServer ..." dgram = require "dgram" @socket = dgram.createSocket "udp4" @socket.on "error", (err) => Log.e err @socket.on "message", (data, rinfo) => @onReceive data, rinfo.address, rinfo.port @socket.on "listening", => Log.d "MDNS socket is listened" @socket.setMulticastTTL mdnsSdServer.MDNS_TTL @socket.setMulticastLoopback mdnsSdServer.MDNS_LOOPBACK_MODE @socket.bind mdnsSdServer.MDNS_PORT, "0.0.0.0", => Log.d "MDNS socket is binded" @socket.addMembership mdnsSdServer.MDNS_ADDRESS, @address.ipv4 @running = true @listen() @emit "ready" @status = true @keepActive() else Log.d "MDNSServer start fail" if not @dnsSdResponse Log.d "MDNSServer dont config , please config" if not @address.ipv4 Log.d "MDNSServer dont ipv4, please check network" start: -> @_start() @startLoop = setInterval (=> @_start() ), 5000 # @keepActiveLoop = setInterval (=> # @keepActive() ), 8000 stop: -> @socket.close() @status = false clearInterval @start_loop clearInterval @keep_active Log.d "MDNSServer stop" keepActive: -> if @dnsSdKeepResponse @dnsSdKeepResponse.transactionID = 0 buff = new Buffer MDNSHelper.encodeMessage @dnsSdKeepResponse if @status @socket.send buff, 0, buff.length, mdnsSdServer.MDNS_PORT, mdnsSdServer.MDNS_ADDRESS, => Log.i "mdnsResponse to #{mdnsSdServer.MDNS_ADDRESS}:#{mdnsSdServer.MDNS_PORT} done".red listen: -> if not @running then return onReceive: (data, address, port) -> try message = MDNSHelper.decodeMessage data catch error Log.d "error: #{error}" Log.d "#{address}: data #{data}" if message && message.isQuery for question in message.questions if question.name.toLowerCase() is @fullProtocol.toLowerCase() if question.type is MDNSHelper.TYPE_PTR @dnsSdResponse.transactionID = message.transactionID buff = new Buffer MDNSHelper.encodeMessage @dnsSdResponse Log.i "mdns receive message: #{message}".red @socket.send buff, 0, buff.length, port, address, => Log.i "mdnsResponse to #{address}:#{port} done".red module.exports.mdnsSdServer = mdnsSdServer
[ { "context": "twitterBootstrapCommit = 'aaabe2a46c64e7d9ffd5735dba2db4f3cf9906f5'\n\nfs = require('fs')\n_path = require('path')\n\ncla", "end": 66, "score": 0.9682256579399109, "start": 26, "tag": "PASSWORD", "value": "aaabe2a46c64e7d9ffd5735dba2db4f3cf9906f5" }, { "context": "sideb...
node_modules/tower/packages/tower-generator/server/generators/tower/app/appGenerator.coffee
MagicPower2/Power
1
twitterBootstrapCommit = 'aaabe2a46c64e7d9ffd5735dba2db4f3cf9906f5' fs = require('fs') _path = require('path') class Tower.GeneratorAppGenerator extends Tower.Generator sourceRoot: __dirname buildApp: (name = @appName) -> app = super(name) app.title = @program.title || _.titleize(_.humanize(app.name)) app.description = @program.description app.keywords = @program.keywords app.stylesheetEngine = @program.stylesheetEngine app.scriptType = @program.scriptType app.templateEngine = @program.templateEngine app run: -> {JAVASCRIPTS, STYLESHEETS, IMAGES, SWFS} = Tower.GeneratorAppGenerator scriptType = @program.scriptType isCoffee = scriptType == 'coffee' templateEngine = @program.templateEngine stylesheetEngine = @program.stylesheetEngine || 'styl' @inside @app.name, '.', -> @template 'gitignore', '.gitignore' unless @program.skipGitfile @template 'npmignore', '.npmignore' @template 'slugignore', '.slugignore' unless @program.skipProcfile @template 'cake', 'Cakefile' if isCoffee @inside 'app', -> @inside 'config', -> @inside 'client', -> @template "bootstrap.#{scriptType}" @template "watch.#{scriptType}" @inside 'server', -> @template "assets.#{scriptType}" @template "bootstrap.#{scriptType}" @template "credentials.#{scriptType}" @template "databases.#{scriptType}" @template "session.#{scriptType}" @inside 'environments', -> if isCoffee # @todo tmp @template "development.#{scriptType}" @template "production.#{scriptType}" @template "test.#{scriptType}" @directory 'initializers' @inside 'shared', -> @template "application.#{scriptType}" @inside 'locales', -> @template "en.#{scriptType}" @template "routes.#{scriptType}" @inside 'controllers', -> @inside 'client', -> @template "applicationController.#{scriptType}" @inside 'server', -> @template "applicationController.#{scriptType}" @inside 'models', -> @directory 'client' @directory 'server' @directory 'shared' @inside 'stylesheets', -> @inside 'client', -> @template "application.#{stylesheetEngine}" @inside 'server', -> @template "email.#{stylesheetEngine}" @inside 'templates', -> @inside 'server', -> @inside 'layout', -> @template "application.#{templateEngine}" @template "_meta.#{templateEngine}" @inside 'shared', -> @template "welcome.#{templateEngine}" @inside 'layout', -> @template "_body.#{templateEngine}" @template "_flash.#{templateEngine}" @template "_footer.#{templateEngine}" @template "_header.#{templateEngine}" @template "_navigation.#{templateEngine}" @template "_sidebar.#{templateEngine}" @inside 'views', -> @inside 'client', -> @inside 'layout', -> @template "application.#{scriptType}" @inside 'data', -> @template "seeds.#{scriptType}" @directory 'lib' @directory 'log' @template 'pack', 'package.json' @template 'Procfile' unless @program.skipProcfile @inside 'public', -> @template '404.html' @template '500.html' @template 'fav.png', 'favicon.png' @template 'crossdomain.xml' @template 'humans.txt' @template 'robots.txt' @directory 'fonts' @directory 'images' @directory 'javascripts' @directory 'stylesheets' @directory 'swfs' @directory 'uploads' @template 'README.md' @inside 'scripts', -> @template 'tower' # @chmod 'scripts/tower', parseInt('0755') @template 'server.js' @inside 'test', '.', -> @inside 'cases', '.', -> @inside 'controllers', -> @directory 'client' @directory 'server' @inside 'features', '.', -> @directory 'client' @directory 'server' #@inside 'server', '.', -> #@template "apiTest.#{scriptType}" @inside 'models', -> @directory 'client' @directory 'server' @directory 'shared' @directory 'factories' @inside 'test', -> @template "client.#{scriptType}" @template 'mocha.opts' @template "server.#{scriptType}" @directory 'tmp' # if tower bundled client files already vendorPath = _path.join(Tower.srcRoot, 'vendor') vendorPathExists = fs.existsSync(vendorPath) copyVendor = (source, destination) => Tower.module('wrench').copyDirSyncRecursive(_path.join(vendorPath, source), @destinationPath(destination)) unless vendorPathExists @inside 'vendor', -> @inside 'javascripts', -> @directory 'bootstrap' @get(remote, local) for remote, local of JAVASCRIPTS @inside 'stylesheets', -> @directory 'bootstrap' @get(remote, local) for remote, local of STYLESHEETS @inside 'public/images', -> @get(remote, local) for remote, local of IMAGES #@inside 'public/swfs', -> # @get(remote, local) for remote, local of SWFS else @directory 'vendor/javascripts' @directory 'vendor/stylesheets' copyVendor('javascripts', 'vendor/javascripts') copyVendor('stylesheets', 'vendor/stylesheets') copyVendor('images', 'public/images') # @todo grunt should only recompile file changes @template "grunt.#{scriptType}", "grunt.#{scriptType}" # github wiki @inside 'wiki', -> @template 'home.md' @template '_sidebar.md' JAVASCRIPTS = # https://github.com/eriwen/javascript-stacktrace 'https://raw.github.com/documentcloud/underscore/master/underscore.js': 'underscore.js' 'https://raw.github.com/epeli/underscore.string/master/lib/underscore.string.js': 'underscore.string.js' 'https://raw.github.com/caolan/async/master/lib/async.js': 'async.js' # https://github.com/viatropos/tiny-require.js 'https://raw.github.com/LearnBoost/socket.io-client/master/dist/socket.io.js': 'socket.io.js' # https://github.com/paulmillr/es6-shim 'https://raw.github.com/timrwood/moment/master/moment.js': 'moment.js' 'https://raw.github.com/andris9/jStorage/72c44323d33bb6a4c3610bdb774184e3a43a230f/jstorage.min.js': 'jstorage.js' 'https://raw.github.com/medialize/URI.js/gh-pages/src/URI.js': 'uri.js' 'https://raw.github.com/visionmedia/mocha/master/mocha.js': 'mocha.js' 'https://raw.github.com/manuelbieh/Geolib/390e9d4e26c05bfdba86fe1a28a8548c58a9b841/geolib.js': 'geolib.js' 'https://raw.github.com/chriso/node-validator/master/validator.js': 'validator.js' 'https://raw.github.com/viatropos/node.inflection/master/lib/inflection.js': 'inflection.js' 'https://raw.github.com/josscrowcroft/accounting.js/9ff4a4022e5c08f028d652d2b0ba1d4b65588bde/accounting.js': 'accounting.js' 'https://raw.github.com/edubkendo/sinon.js/2c6518de91c793344c7ead01a34556585f1b4d2c/sinon.js': 'sinon.js' 'https://raw.github.com/chaijs/chai/efc77596338556cca5fb4eade95c3838a743a186/chai.js': 'chai.js' 'https://raw.github.com/gradus/coffeecup/2d76a48c1292629dbe961088f756f00b034f0060/lib/coffeecup.js': 'coffeekup.js' 'https://raw.github.com/emberjs/starter-kit/1e6ee1418c694206a49bd7b021fe5996e7fdb14c/js/libs/ember-1.0.pre.js': 'ember.js' 'https://raw.github.com/emberjs/starter-kit/1e6ee1418c694206a49bd7b021fe5996e7fdb14c/js/libs/handlebars-1.0.0.beta.6.js': 'handlebars.js' 'https://raw.github.com/edubkendo/prettify.js/544c6cdf16594c85d3698dd0cbe07a9f232d02d9/prettify.js': 'prettify.js' 'https://raw.github.com/Marak/Faker.js/master/Faker.js': 'faker.js' 'https://raw.github.com/madrobby/keymaster/c61b3fef9767d4899a1732b089ca70512c9d4261/keymaster.js': 'keymaster.js' 'https://raw.github.com/mrdoob/stats.js/master/src/Stats.js': 'stats.js' 'http://html5shiv.googlecode.com/svn/trunk/html5.js': 'html5.js' JAVASCRIPTS["http://cloud.github.com/downloads/viatropos/tower/tower-#{Tower.version}.js"] = 'tower.js' JAVASCRIPTS["https://raw.github.com/twitter/bootstrap/#{twitterBootstrapCommit}/js/#{javascript}.js"] = "bootstrap/#{javascript}.js" for javascript in [ 'bootstrap-alert' 'bootstrap-button' 'bootstrap-carousel' 'bootstrap-collapse' 'bootstrap-dropdown' 'bootstrap-modal' 'bootstrap-popover' 'bootstrap-scrollspy' 'bootstrap-tab' 'bootstrap-tooltip' 'bootstrap-transition' 'bootstrap-typeahead' ] STYLESHEETS = 'http://twitter.github.com/bootstrap/assets/js/google-code-prettify/prettify.css': 'prettify.css' 'https://raw.github.com/visionmedia/mocha/master/mocha.css': 'mocha.css' STYLESHEETS["https://raw.github.com/twitter/bootstrap/#{twitterBootstrapCommit}/less/#{stylesheet}.less"] = "bootstrap/#{stylesheet}.less" for stylesheet in [ 'accordion' 'alerts' 'bootstrap' 'breadcrumbs' 'button-groups' 'buttons' 'carousel' 'close' 'code' 'component-animations' 'dropdowns' 'forms' 'grid' 'hero-unit' 'labels-badges' 'layouts' 'mixins' 'modals' 'navbar' 'navs' 'pager' 'pagination' 'popovers' 'progress-bars' 'reset' 'responsive-1200px-min' 'responsive-767px-max' 'responsive-768px-979px' 'responsive-navbar' 'responsive-utilities' 'responsive' 'scaffolding' 'sprites' 'tables' 'thumbnails' 'tooltip' 'type' 'utilities' 'variables' 'wells' ] IMAGES = {} IMAGES["https://raw.github.com/twitter/bootstrap/#{twitterBootstrapCommit}/img/glyphicons-halflings.png"] = 'glyphicons-halflings.png' IMAGES["https://raw.github.com/twitter/bootstrap/#{twitterBootstrapCommit}/img/glyphicons-halflings-white.png"] = 'glyphicons-halflings-white.png' SWFS = 'https://raw.github.com/LearnBoost/socket.io-client/master/dist/WebSocketMain.swf': 'WebSocketMain.swf' 'https://raw.github.com/LearnBoost/socket.io-client/master/dist/WebSocketMainInsecure.swf': 'WebSocketMainInsecure.swf' Tower.GeneratorAppGenerator.JAVASCRIPTS = JAVASCRIPTS Tower.GeneratorAppGenerator.STYLESHEETS = STYLESHEETS Tower.GeneratorAppGenerator.IMAGES = IMAGES Tower.GeneratorAppGenerator.SWFS = SWFS module.exports = Tower.GeneratorAppGenerator
152958
twitterBootstrapCommit = '<PASSWORD>' fs = require('fs') _path = require('path') class Tower.GeneratorAppGenerator extends Tower.Generator sourceRoot: __dirname buildApp: (name = @appName) -> app = super(name) app.title = @program.title || _.titleize(_.humanize(app.name)) app.description = @program.description app.keywords = @program.keywords app.stylesheetEngine = @program.stylesheetEngine app.scriptType = @program.scriptType app.templateEngine = @program.templateEngine app run: -> {JAVASCRIPTS, STYLESHEETS, IMAGES, SWFS} = Tower.GeneratorAppGenerator scriptType = @program.scriptType isCoffee = scriptType == 'coffee' templateEngine = @program.templateEngine stylesheetEngine = @program.stylesheetEngine || 'styl' @inside @app.name, '.', -> @template 'gitignore', '.gitignore' unless @program.skipGitfile @template 'npmignore', '.npmignore' @template 'slugignore', '.slugignore' unless @program.skipProcfile @template 'cake', 'Cakefile' if isCoffee @inside 'app', -> @inside 'config', -> @inside 'client', -> @template "bootstrap.#{scriptType}" @template "watch.#{scriptType}" @inside 'server', -> @template "assets.#{scriptType}" @template "bootstrap.#{scriptType}" @template "credentials.#{scriptType}" @template "databases.#{scriptType}" @template "session.#{scriptType}" @inside 'environments', -> if isCoffee # @todo tmp @template "development.#{scriptType}" @template "production.#{scriptType}" @template "test.#{scriptType}" @directory 'initializers' @inside 'shared', -> @template "application.#{scriptType}" @inside 'locales', -> @template "en.#{scriptType}" @template "routes.#{scriptType}" @inside 'controllers', -> @inside 'client', -> @template "applicationController.#{scriptType}" @inside 'server', -> @template "applicationController.#{scriptType}" @inside 'models', -> @directory 'client' @directory 'server' @directory 'shared' @inside 'stylesheets', -> @inside 'client', -> @template "application.#{stylesheetEngine}" @inside 'server', -> @template "email.#{stylesheetEngine}" @inside 'templates', -> @inside 'server', -> @inside 'layout', -> @template "application.#{templateEngine}" @template "_meta.#{templateEngine}" @inside 'shared', -> @template "welcome.#{templateEngine}" @inside 'layout', -> @template "_body.#{templateEngine}" @template "_flash.#{templateEngine}" @template "_footer.#{templateEngine}" @template "_header.#{templateEngine}" @template "_navigation.#{templateEngine}" @template "_sidebar.#{templateEngine}" @inside 'views', -> @inside 'client', -> @inside 'layout', -> @template "application.#{scriptType}" @inside 'data', -> @template "seeds.#{scriptType}" @directory 'lib' @directory 'log' @template 'pack', 'package.json' @template 'Procfile' unless @program.skipProcfile @inside 'public', -> @template '404.html' @template '500.html' @template 'fav.png', 'favicon.png' @template 'crossdomain.xml' @template 'humans.txt' @template 'robots.txt' @directory 'fonts' @directory 'images' @directory 'javascripts' @directory 'stylesheets' @directory 'swfs' @directory 'uploads' @template 'README.md' @inside 'scripts', -> @template 'tower' # @chmod 'scripts/tower', parseInt('0755') @template 'server.js' @inside 'test', '.', -> @inside 'cases', '.', -> @inside 'controllers', -> @directory 'client' @directory 'server' @inside 'features', '.', -> @directory 'client' @directory 'server' #@inside 'server', '.', -> #@template "apiTest.#{scriptType}" @inside 'models', -> @directory 'client' @directory 'server' @directory 'shared' @directory 'factories' @inside 'test', -> @template "client.#{scriptType}" @template 'mocha.opts' @template "server.#{scriptType}" @directory 'tmp' # if tower bundled client files already vendorPath = _path.join(Tower.srcRoot, 'vendor') vendorPathExists = fs.existsSync(vendorPath) copyVendor = (source, destination) => Tower.module('wrench').copyDirSyncRecursive(_path.join(vendorPath, source), @destinationPath(destination)) unless vendorPathExists @inside 'vendor', -> @inside 'javascripts', -> @directory 'bootstrap' @get(remote, local) for remote, local of JAVASCRIPTS @inside 'stylesheets', -> @directory 'bootstrap' @get(remote, local) for remote, local of STYLESHEETS @inside 'public/images', -> @get(remote, local) for remote, local of IMAGES #@inside 'public/swfs', -> # @get(remote, local) for remote, local of SWFS else @directory 'vendor/javascripts' @directory 'vendor/stylesheets' copyVendor('javascripts', 'vendor/javascripts') copyVendor('stylesheets', 'vendor/stylesheets') copyVendor('images', 'public/images') # @todo grunt should only recompile file changes @template "grunt.#{scriptType}", "grunt.#{scriptType}" # github wiki @inside 'wiki', -> @template 'home.md' @template '_sidebar.md' JAVASCRIPTS = # https://github.com/eriwen/javascript-stacktrace 'https://raw.github.com/documentcloud/underscore/master/underscore.js': 'underscore.js' 'https://raw.github.com/epeli/underscore.string/master/lib/underscore.string.js': 'underscore.string.js' 'https://raw.github.com/caolan/async/master/lib/async.js': 'async.js' # https://github.com/viatropos/tiny-require.js 'https://raw.github.com/LearnBoost/socket.io-client/master/dist/socket.io.js': 'socket.io.js' # https://github.com/paulmillr/es6-shim 'https://raw.github.com/timrwood/moment/master/moment.js': 'moment.js' 'https://raw.github.com/andris9/jStorage/72c44323d33bb6a4c3610bdb774184e3a43a230f/jstorage.min.js': 'jstorage.js' 'https://raw.github.com/medialize/URI.js/gh-pages/src/URI.js': 'uri.js' 'https://raw.github.com/visionmedia/mocha/master/mocha.js': 'mocha.js' 'https://raw.github.com/manuelbieh/Geolib/390e9d4e26c05bfdba86fe1a28a8548c58a9b841/geolib.js': 'geolib.js' 'https://raw.github.com/chriso/node-validator/master/validator.js': 'validator.js' 'https://raw.github.com/viatropos/node.inflection/master/lib/inflection.js': 'inflection.js' 'https://raw.github.com/josscrowcroft/accounting.js/9ff4a4022e5c08f028d652d2b0ba1d4b65588bde/accounting.js': 'accounting.js' 'https://raw.github.com/edubkendo/sinon.js/2c6518de91c793344c7ead01a34556585f1b4d2c/sinon.js': 'sinon.js' 'https://raw.github.com/chaijs/chai/efc77596338556cca5fb4eade95c3838a743a186/chai.js': 'chai.js' 'https://raw.github.com/gradus/coffeecup/2d76a48c1292629dbe961088f756f00b034f0060/lib/coffeecup.js': 'coffeekup.js' 'https://raw.github.com/emberjs/starter-kit/1e6ee1418c694206a49bd7b021fe5996e7fdb14c/js/libs/ember-1.0.pre.js': 'ember.js' 'https://raw.github.com/emberjs/starter-kit/1e6ee1418c694206a49bd7b021fe5996e7fdb14c/js/libs/handlebars-1.0.0.beta.6.js': 'handlebars.js' 'https://raw.github.com/edubkendo/prettify.js/544c6cdf16594c85d3698dd0cbe07a9f232d02d9/prettify.js': 'prettify.js' 'https://raw.github.com/Marak/Faker.js/master/Faker.js': 'faker.js' 'https://raw.github.com/madrobby/keymaster/c61b3fef9767d4899a1732b089ca70512c9d4261/keymaster.js': 'keymaster.js' 'https://raw.github.com/mrdoob/stats.js/master/src/Stats.js': 'stats.js' 'http://html5shiv.googlecode.com/svn/trunk/html5.js': 'html5.js' JAVASCRIPTS["http://cloud.github.com/downloads/viatropos/tower/tower-#{Tower.version}.js"] = 'tower.js' JAVASCRIPTS["https://raw.github.com/twitter/bootstrap/#{twitterBootstrapCommit}/js/#{javascript}.js"] = "bootstrap/#{javascript}.js" for javascript in [ 'bootstrap-alert' 'bootstrap-button' 'bootstrap-carousel' 'bootstrap-collapse' 'bootstrap-dropdown' 'bootstrap-modal' 'bootstrap-popover' 'bootstrap-scrollspy' 'bootstrap-tab' 'bootstrap-tooltip' 'bootstrap-transition' 'bootstrap-typeahead' ] STYLESHEETS = 'http://twitter.github.com/bootstrap/assets/js/google-code-prettify/prettify.css': 'prettify.css' 'https://raw.github.com/visionmedia/mocha/master/mocha.css': 'mocha.css' STYLESHEETS["https://raw.github.com/twitter/bootstrap/#{twitterBootstrapCommit}/less/#{stylesheet}.less"] = "bootstrap/#{stylesheet}.less" for stylesheet in [ 'accordion' 'alerts' 'bootstrap' 'breadcrumbs' 'button-groups' 'buttons' 'carousel' 'close' 'code' 'component-animations' 'dropdowns' 'forms' 'grid' 'hero-unit' 'labels-badges' 'layouts' 'mixins' 'modals' 'navbar' 'navs' 'pager' 'pagination' 'popovers' 'progress-bars' 'reset' 'responsive-1200px-min' 'responsive-767px-max' 'responsive-768px-979px' 'responsive-navbar' 'responsive-utilities' 'responsive' 'scaffolding' 'sprites' 'tables' 'thumbnails' 'tooltip' 'type' 'utilities' 'variables' 'wells' ] IMAGES = {} IMAGES["https://raw.github.com/twitter/bootstrap/#{twitterBootstrapCommit}/img/glyphicons-halflings.png"] = 'glyphicons-halflings.png' IMAGES["https://raw.github.com/twitter/bootstrap/#{twitterBootstrapCommit}/img/glyphicons-halflings-white.png"] = 'glyphicons-halflings-white.png' SWFS = 'https://raw.github.com/LearnBoost/socket.io-client/master/dist/WebSocketMain.swf': 'WebSocketMain.swf' 'https://raw.github.com/LearnBoost/socket.io-client/master/dist/WebSocketMainInsecure.swf': 'WebSocketMainInsecure.swf' Tower.GeneratorAppGenerator.JAVASCRIPTS = JAVASCRIPTS Tower.GeneratorAppGenerator.STYLESHEETS = STYLESHEETS Tower.GeneratorAppGenerator.IMAGES = IMAGES Tower.GeneratorAppGenerator.SWFS = SWFS module.exports = Tower.GeneratorAppGenerator
true
twitterBootstrapCommit = 'PI:PASSWORD:<PASSWORD>END_PI' fs = require('fs') _path = require('path') class Tower.GeneratorAppGenerator extends Tower.Generator sourceRoot: __dirname buildApp: (name = @appName) -> app = super(name) app.title = @program.title || _.titleize(_.humanize(app.name)) app.description = @program.description app.keywords = @program.keywords app.stylesheetEngine = @program.stylesheetEngine app.scriptType = @program.scriptType app.templateEngine = @program.templateEngine app run: -> {JAVASCRIPTS, STYLESHEETS, IMAGES, SWFS} = Tower.GeneratorAppGenerator scriptType = @program.scriptType isCoffee = scriptType == 'coffee' templateEngine = @program.templateEngine stylesheetEngine = @program.stylesheetEngine || 'styl' @inside @app.name, '.', -> @template 'gitignore', '.gitignore' unless @program.skipGitfile @template 'npmignore', '.npmignore' @template 'slugignore', '.slugignore' unless @program.skipProcfile @template 'cake', 'Cakefile' if isCoffee @inside 'app', -> @inside 'config', -> @inside 'client', -> @template "bootstrap.#{scriptType}" @template "watch.#{scriptType}" @inside 'server', -> @template "assets.#{scriptType}" @template "bootstrap.#{scriptType}" @template "credentials.#{scriptType}" @template "databases.#{scriptType}" @template "session.#{scriptType}" @inside 'environments', -> if isCoffee # @todo tmp @template "development.#{scriptType}" @template "production.#{scriptType}" @template "test.#{scriptType}" @directory 'initializers' @inside 'shared', -> @template "application.#{scriptType}" @inside 'locales', -> @template "en.#{scriptType}" @template "routes.#{scriptType}" @inside 'controllers', -> @inside 'client', -> @template "applicationController.#{scriptType}" @inside 'server', -> @template "applicationController.#{scriptType}" @inside 'models', -> @directory 'client' @directory 'server' @directory 'shared' @inside 'stylesheets', -> @inside 'client', -> @template "application.#{stylesheetEngine}" @inside 'server', -> @template "email.#{stylesheetEngine}" @inside 'templates', -> @inside 'server', -> @inside 'layout', -> @template "application.#{templateEngine}" @template "_meta.#{templateEngine}" @inside 'shared', -> @template "welcome.#{templateEngine}" @inside 'layout', -> @template "_body.#{templateEngine}" @template "_flash.#{templateEngine}" @template "_footer.#{templateEngine}" @template "_header.#{templateEngine}" @template "_navigation.#{templateEngine}" @template "_sidebar.#{templateEngine}" @inside 'views', -> @inside 'client', -> @inside 'layout', -> @template "application.#{scriptType}" @inside 'data', -> @template "seeds.#{scriptType}" @directory 'lib' @directory 'log' @template 'pack', 'package.json' @template 'Procfile' unless @program.skipProcfile @inside 'public', -> @template '404.html' @template '500.html' @template 'fav.png', 'favicon.png' @template 'crossdomain.xml' @template 'humans.txt' @template 'robots.txt' @directory 'fonts' @directory 'images' @directory 'javascripts' @directory 'stylesheets' @directory 'swfs' @directory 'uploads' @template 'README.md' @inside 'scripts', -> @template 'tower' # @chmod 'scripts/tower', parseInt('0755') @template 'server.js' @inside 'test', '.', -> @inside 'cases', '.', -> @inside 'controllers', -> @directory 'client' @directory 'server' @inside 'features', '.', -> @directory 'client' @directory 'server' #@inside 'server', '.', -> #@template "apiTest.#{scriptType}" @inside 'models', -> @directory 'client' @directory 'server' @directory 'shared' @directory 'factories' @inside 'test', -> @template "client.#{scriptType}" @template 'mocha.opts' @template "server.#{scriptType}" @directory 'tmp' # if tower bundled client files already vendorPath = _path.join(Tower.srcRoot, 'vendor') vendorPathExists = fs.existsSync(vendorPath) copyVendor = (source, destination) => Tower.module('wrench').copyDirSyncRecursive(_path.join(vendorPath, source), @destinationPath(destination)) unless vendorPathExists @inside 'vendor', -> @inside 'javascripts', -> @directory 'bootstrap' @get(remote, local) for remote, local of JAVASCRIPTS @inside 'stylesheets', -> @directory 'bootstrap' @get(remote, local) for remote, local of STYLESHEETS @inside 'public/images', -> @get(remote, local) for remote, local of IMAGES #@inside 'public/swfs', -> # @get(remote, local) for remote, local of SWFS else @directory 'vendor/javascripts' @directory 'vendor/stylesheets' copyVendor('javascripts', 'vendor/javascripts') copyVendor('stylesheets', 'vendor/stylesheets') copyVendor('images', 'public/images') # @todo grunt should only recompile file changes @template "grunt.#{scriptType}", "grunt.#{scriptType}" # github wiki @inside 'wiki', -> @template 'home.md' @template '_sidebar.md' JAVASCRIPTS = # https://github.com/eriwen/javascript-stacktrace 'https://raw.github.com/documentcloud/underscore/master/underscore.js': 'underscore.js' 'https://raw.github.com/epeli/underscore.string/master/lib/underscore.string.js': 'underscore.string.js' 'https://raw.github.com/caolan/async/master/lib/async.js': 'async.js' # https://github.com/viatropos/tiny-require.js 'https://raw.github.com/LearnBoost/socket.io-client/master/dist/socket.io.js': 'socket.io.js' # https://github.com/paulmillr/es6-shim 'https://raw.github.com/timrwood/moment/master/moment.js': 'moment.js' 'https://raw.github.com/andris9/jStorage/72c44323d33bb6a4c3610bdb774184e3a43a230f/jstorage.min.js': 'jstorage.js' 'https://raw.github.com/medialize/URI.js/gh-pages/src/URI.js': 'uri.js' 'https://raw.github.com/visionmedia/mocha/master/mocha.js': 'mocha.js' 'https://raw.github.com/manuelbieh/Geolib/390e9d4e26c05bfdba86fe1a28a8548c58a9b841/geolib.js': 'geolib.js' 'https://raw.github.com/chriso/node-validator/master/validator.js': 'validator.js' 'https://raw.github.com/viatropos/node.inflection/master/lib/inflection.js': 'inflection.js' 'https://raw.github.com/josscrowcroft/accounting.js/9ff4a4022e5c08f028d652d2b0ba1d4b65588bde/accounting.js': 'accounting.js' 'https://raw.github.com/edubkendo/sinon.js/2c6518de91c793344c7ead01a34556585f1b4d2c/sinon.js': 'sinon.js' 'https://raw.github.com/chaijs/chai/efc77596338556cca5fb4eade95c3838a743a186/chai.js': 'chai.js' 'https://raw.github.com/gradus/coffeecup/2d76a48c1292629dbe961088f756f00b034f0060/lib/coffeecup.js': 'coffeekup.js' 'https://raw.github.com/emberjs/starter-kit/1e6ee1418c694206a49bd7b021fe5996e7fdb14c/js/libs/ember-1.0.pre.js': 'ember.js' 'https://raw.github.com/emberjs/starter-kit/1e6ee1418c694206a49bd7b021fe5996e7fdb14c/js/libs/handlebars-1.0.0.beta.6.js': 'handlebars.js' 'https://raw.github.com/edubkendo/prettify.js/544c6cdf16594c85d3698dd0cbe07a9f232d02d9/prettify.js': 'prettify.js' 'https://raw.github.com/Marak/Faker.js/master/Faker.js': 'faker.js' 'https://raw.github.com/madrobby/keymaster/c61b3fef9767d4899a1732b089ca70512c9d4261/keymaster.js': 'keymaster.js' 'https://raw.github.com/mrdoob/stats.js/master/src/Stats.js': 'stats.js' 'http://html5shiv.googlecode.com/svn/trunk/html5.js': 'html5.js' JAVASCRIPTS["http://cloud.github.com/downloads/viatropos/tower/tower-#{Tower.version}.js"] = 'tower.js' JAVASCRIPTS["https://raw.github.com/twitter/bootstrap/#{twitterBootstrapCommit}/js/#{javascript}.js"] = "bootstrap/#{javascript}.js" for javascript in [ 'bootstrap-alert' 'bootstrap-button' 'bootstrap-carousel' 'bootstrap-collapse' 'bootstrap-dropdown' 'bootstrap-modal' 'bootstrap-popover' 'bootstrap-scrollspy' 'bootstrap-tab' 'bootstrap-tooltip' 'bootstrap-transition' 'bootstrap-typeahead' ] STYLESHEETS = 'http://twitter.github.com/bootstrap/assets/js/google-code-prettify/prettify.css': 'prettify.css' 'https://raw.github.com/visionmedia/mocha/master/mocha.css': 'mocha.css' STYLESHEETS["https://raw.github.com/twitter/bootstrap/#{twitterBootstrapCommit}/less/#{stylesheet}.less"] = "bootstrap/#{stylesheet}.less" for stylesheet in [ 'accordion' 'alerts' 'bootstrap' 'breadcrumbs' 'button-groups' 'buttons' 'carousel' 'close' 'code' 'component-animations' 'dropdowns' 'forms' 'grid' 'hero-unit' 'labels-badges' 'layouts' 'mixins' 'modals' 'navbar' 'navs' 'pager' 'pagination' 'popovers' 'progress-bars' 'reset' 'responsive-1200px-min' 'responsive-767px-max' 'responsive-768px-979px' 'responsive-navbar' 'responsive-utilities' 'responsive' 'scaffolding' 'sprites' 'tables' 'thumbnails' 'tooltip' 'type' 'utilities' 'variables' 'wells' ] IMAGES = {} IMAGES["https://raw.github.com/twitter/bootstrap/#{twitterBootstrapCommit}/img/glyphicons-halflings.png"] = 'glyphicons-halflings.png' IMAGES["https://raw.github.com/twitter/bootstrap/#{twitterBootstrapCommit}/img/glyphicons-halflings-white.png"] = 'glyphicons-halflings-white.png' SWFS = 'https://raw.github.com/LearnBoost/socket.io-client/master/dist/WebSocketMain.swf': 'WebSocketMain.swf' 'https://raw.github.com/LearnBoost/socket.io-client/master/dist/WebSocketMainInsecure.swf': 'WebSocketMainInsecure.swf' Tower.GeneratorAppGenerator.JAVASCRIPTS = JAVASCRIPTS Tower.GeneratorAppGenerator.STYLESHEETS = STYLESHEETS Tower.GeneratorAppGenerator.IMAGES = IMAGES Tower.GeneratorAppGenerator.SWFS = SWFS module.exports = Tower.GeneratorAppGenerator
[ { "context": "Ember.Controller.extend\n users: [{id: 22, name: 'Stacey'}]\n\n actions:\n test: ->\n $.get(\"/groups/", "end": 449, "score": 0.9677169919013977, "start": 443, "tag": "NAME", "value": "Stacey" } ]
app/assets/javascripts/graph_starter/ember_apps/user_list_dropdown.coffee
neo4j-examples/graph_starter
4
EmberENV = {FEATURES: {'_ENABLE_LEGACY_VIEW_SUPPORT': true}}; window.UserListDropdownApp = Ember.Application.create rootElement: '#user-list-dropdown' window.UserListDropdownApp.ApplicationView = Ember.View.extend templateName: 'user-list-dropdown', window.UserListDropdownApp.Router = Ember.Router.extend location: 'none' window.UserListDropdownApp.ApplicationController = Ember.Controller.extend users: [{id: 22, name: 'Stacey'}] actions: test: -> $.get("/groups/#{}/users_to_add.json") $(document).ready ->
5497
EmberENV = {FEATURES: {'_ENABLE_LEGACY_VIEW_SUPPORT': true}}; window.UserListDropdownApp = Ember.Application.create rootElement: '#user-list-dropdown' window.UserListDropdownApp.ApplicationView = Ember.View.extend templateName: 'user-list-dropdown', window.UserListDropdownApp.Router = Ember.Router.extend location: 'none' window.UserListDropdownApp.ApplicationController = Ember.Controller.extend users: [{id: 22, name: '<NAME>'}] actions: test: -> $.get("/groups/#{}/users_to_add.json") $(document).ready ->
true
EmberENV = {FEATURES: {'_ENABLE_LEGACY_VIEW_SUPPORT': true}}; window.UserListDropdownApp = Ember.Application.create rootElement: '#user-list-dropdown' window.UserListDropdownApp.ApplicationView = Ember.View.extend templateName: 'user-list-dropdown', window.UserListDropdownApp.Router = Ember.Router.extend location: 'none' window.UserListDropdownApp.ApplicationController = Ember.Controller.extend users: [{id: 22, name: 'PI:NAME:<NAME>END_PI'}] actions: test: -> $.get("/groups/#{}/users_to_add.json") $(document).ready ->
[ { "context": " url = item[\"thumbnailURL\"]\n urlKey = key+\".thumbnailURL\"\n if !url\n url = item[\"url\"]\n ", "end": 13400, "score": 0.8378432989120483, "start": 13382, "tag": "KEY", "value": "key+\".thumbnailURL" }, { "context": " url = ite...
listmanagementmodule/listmanagementmodule.coffee
JhonnyJason/admin-pwa-sources-source
0
listmanagementmodule = {name: "listmanagementmodule"} ############################################################ #region printLogFunctions log = (arg) -> if adminModules.debugmodule.modulesToDebug["listmanagementmodule"]? then console.log "[listmanagementmodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ admin = null bigpanel = null bottomPanel = null contentHandler = null ############################################################ allLists = null listInformationMap = {} ############################################################ listmanagementmodule.initialize = -> log "listmanagementmodule.initialize" admin = adminModules.adminmodule bigpanel = adminModules.bigpanelmodule bottomPanel = adminModules.bottompanelmodule contentHandler = adminModules.contenthandlermodule return ############################################################ findURLsOfListItem = (listItem) -> log "findURLsOfListItem" urls = [] for label,element of listItem if label == "url" then urls.push(element) if typeof element == "object" then urls.push(findURLsOfListItem(element)) return urls.flat() findImageObject = (name) -> log "findImageObject" content = contentHandler.content() for label,image of content.images if image.name == name then return { label, image } return findAssociatedImageKey = (url) -> log "findAssociatedImageKey" imageObject = findAssetObject(url) if !imageObject or !imageObject.label console.log(url + " did not have an image object") return "" return imageObject.label findAssetObject = (url) -> log "findAssetObject" tokens = url.split("/") if tokens.length < 2 then return null if tokens[0] == "img" then return findImageObject(tokens[1]) if tokens.length < 3 then return null if tokens[1] == "img" then return findImageObject(tokens[2]) return findAssetObjects = (urlList) -> log "findAssetObjects" assetObjects = [] for url in urlList assetObjects.push(findAssetObject(url)) return assetObjects ############################################################ adjustAssetIndicesTo = (assetObjects, index) -> log "adjustAssetIndicesTo" newKey = ""+(index+1) assetObjects = JSON.parse(JSON.stringify(assetObjects)) for assetObject in assetObjects assetObject.label = assetObject.label.replace("1", newKey) if assetObject.image assetObject.image.name = assetObject.image.name.replace("1", newKey) if assetObject.image.thumbnail assetObject.image.thumbnail.name = assetObject.image.thumbnail.name.replace("1", newKey) return assetObjects adjustURLIndicesTo = (item, index) -> log "adjustURLIndicesTo" newKey = ""+(index+1) for label,element of item if label == "url" then item[label] = element.replace("1", newKey) if typeof element == "object" then adjustURLIndicesTo(element, index) return adjustURLIndicesFromTo = (item, fromIndex, toIndex) -> log "adjustURLIndicesFromTo" oldKey = ""+(fromIndex+1) newKey = ""+(toIndex+1) for label,element of item if label == "url" then item[label] = element.replace(oldKey, newKey) if typeof element == "object" then adjustURLIndicesFromTo(element, fromIndex, toIndex) return adjustURLIndicesOneDown = (list, index) -> log "adjustURLIndicesOneDown" while index < list.length adjustURLIndicesFromTo(list[index], index+1, index) index++ return ############################################################ createNewListItem = (templateEntry, index) -> log "createNewListItem" item = JSON.parse(JSON.stringify(templateEntry)) urlList = findURLsOfListItem(item) assetObjects = findAssetObjects(urlList) # olog assetObjects adjustURLIndicesTo(item, index) adjustedObjects = adjustAssetIndicesTo(assetObjects, index) # olog assetObjects if adjustedObjects content = contentHandler.content() oldImages = JSON.parse(JSON.stringify(content.images)) for label,element of adjustedObjects if element.image content.images[element.label] = element.image admin.noticeImagesEdits(oldImages) # olog assetEdits # olog item return item removeAssociatedAssets = (firstItem, index, lastIndex) -> log "removeAssociatedAssets" urlList = findURLsOfListItem(firstItem) assetObjects = findAssetObjects(urlList) if assetObjects adjustedObjects = adjustAssetIndicesTo(assetObjects, lastIndex) content = contentHandler.content() oldImages = JSON.parse(JSON.stringify(content.images)) for label,element of adjustedObjects if element.image delete content.images[element.label] imageMoves = createDeleteMoves(assetObjects, index, lastIndex) admin.noticeImageSwaps(imageMoves) admin.noticeImagesEdits(oldImages) return createDeleteMoves = (assetObjects, index, lastIndex) -> log "createDeleteMoves" moves = [] walker = index while walker < lastIndex walker = walker + 1 fromObjects = adjustAssetIndicesTo(assetObjects, walker) olog fromObjects toObjects = adjustAssetIndicesTo(assetObjects, walker-1) olog toObjects for label of fromObjects if fromObjects[label].image fromName = fromObjects[label].image.name toName = toObjects[label].image.name moves.push {fromName, toName} if fromObjects[label].image.thumbnail fromName = fromObjects[label].image.thumbnail.name toName = toObjects[label].image.thumbnail.name moves.push {fromName, toName} olog moves return moves createSwapMoves = (firstItem, fromIndex, toIndex) -> log "createSwapMoves" moves = [] urlList = findURLsOfListItem(firstItem) assetObjects = findAssetObjects(urlList) fromObjects = adjustAssetIndicesTo(assetObjects, fromIndex) olog fromObjects toObjects = adjustAssetIndicesTo(assetObjects, toIndex) olog toObjects for label of fromObjects if fromObjects[label].image fromName = fromObjects[label].image.name toName = "temp-"+fromObjects[label].image.name moves.push {fromName, toName} if fromObjects[label].image.thumbnail fromName = fromObjects[label].image.thumbnail.name toName = "temp-"+fromObjects[label].image.thumbnail.name moves.push {fromName, toName} for label of fromObjects if fromObjects[label].image fromName = toObjects[label].image.name toName = fromObjects[label].image.name moves.push {fromName, toName} if fromObjects[label].image.thumbnail fromName = toObjects[label].image.thumbnail.name toName = fromObjects[label].image.thumbnail.name moves.push {fromName, toName} for label of fromObjects if fromObjects[label].image fromName = "temp-"+fromObjects[label].image.name toName = toObjects[label].image.name moves.push {fromName, toName} if fromObjects[label].image.thumbnail fromName = "temp-"+fromObjects[label].image.thumbnail.name toName = toObjects[label].image.thumbnail.name moves.push {fromName, toName} olog moves return moves ############################################################ addButtonClicked = (event) -> log "addButtonClicked" listId = event.target.getAttribute("list-id") log listId list = allLists[listId] newList = JSON.parse(JSON.stringify(list)) newItem = createNewListItem(list[0], list.length) newList.push newItem # olog newList admin.noticeListEdit(listId, newList, list) return downButtonClicked = (event) -> log "downButtonClicked" listId = event.target.getAttribute("list-id") index = parseInt(event.target.getAttribute("index")) list = allLists[listId] nextIndex = index + 1 log index log nextIndex if nextIndex >= list.length bottomPanel.setErrorMessage("Das letzte Element kann nicht nach unten verschoben werden!") return # log listId # olog list newList = JSON.parse(JSON.stringify(list)) thisElement = newList[index] nextElement = newList[nextIndex] newList[nextIndex] = thisElement newList[index] = nextElement adjustURLIndicesFromTo(newList[nextIndex], index, nextIndex) adjustURLIndicesFromTo(newList[index], nextIndex, index) imageMoves = createSwapMoves(list[0], index, nextIndex) admin.noticeImageSwaps(imageMoves) admin.noticeListEdit(listId, newList, list) return upButtonClicked = (event) -> log "upButtonClicked" listId = event.target.getAttribute("list-id") index = parseInt(event.target.getAttribute("index")) list = allLists[listId] prevIndex = index - 1 log index log prevIndex if prevIndex < 0 bottomPanel.setErrorMessage("Das erste Element kann nicht nach oben verschoben werden!") return # log listId # olog list newList = JSON.parse(JSON.stringify(list)) thisElement = newList[index] prevElement = newList[prevIndex] newList[prevIndex] = thisElement newList[index] = prevElement adjustURLIndicesFromTo(newList[prevIndex], index, prevIndex) adjustURLIndicesFromTo(newList[index], prevIndex, index) imageMoves = createSwapMoves(list[0], index, prevIndex) admin.noticeImageSwaps(imageMoves) admin.noticeListEdit(listId, newList, list) return deleteButtonClicked = (event) -> log "deleteButtonClicked" listId = event.target.getAttribute("list-id") index = parseInt(event.target.getAttribute("index")) list = allLists[listId] log listId log index if list.length == 1 bottomPanel.setErrorMessage("Das letzte Element kann nicht gelöscht werden!") return newList = JSON.parse(JSON.stringify(list)) newList.splice(index, 1) removeAssociatedAssets(list[0], index, newList.length) # olog newList # olog index adjustURLIndicesOneDown(newList, index) # olog newList admin.noticeListEdit(listId, newList, list) return ############################################################ createListEditElement = (listId, list) -> # log "createImageEditElement" div = document.createElement("div") innerHTML = getEditHeadHTML(listId) for listItem,index in list innerHTML += getListItemHTML(listItem, index, listId) innerHTML += getAddButtonHTML(listId) div.innerHTML = innerHTML leftArrow = div.querySelector(".admin-bigpanel-arrow-left") addButton = div.querySelector(".admin-bigpanel-add-button") upButtons = div.querySelectorAll(".admin-bigpanel-up-button") downButtons = div.querySelectorAll(".admin-bigpanel-down-button") deleteButtons = div.querySelectorAll(".admin-bigpanel-delete-button") div.classList.add("admin-bigpanel-edit-element") div.setAttribute "list-id",listId leftArrow.setAttribute "list-id",listId addButton.setAttribute "list-id",listId addButton.addEventListener("click", addButtonClicked) for button in upButtons button.setAttribute "list-id",listId button.addEventListener("click", upButtonClicked) for button in downButtons button.setAttribute "list-id",listId button.addEventListener("click", downButtonClicked) for button in deleteButtons button.setAttribute "list-id",listId button.addEventListener("click", deleteButtonClicked) return div createListListElement = (listId, list) -> # log "createImageListElement" div = document.createElement("div") innerHTML = "<div>"+listId+"</div>" innerHTML += getArrowRightHTML() div.innerHTML = innerHTML div.classList.add("admin-bigpanel-list-element") div.setAttribute "list-id",listId return div ############################################################ #region createElementHelpers getEditHeadHTML = (name) -> html = "<div class='admin-bigpanel-edit-head'>" html += getArrowLeftHTML() html += "<div>"+name+"</div>" html += "</div>" return html getListItemHTML = (item, index, listId) -> listItemKey = listId+"."+index html = "<div class='admin-bigpanel-list-item'>" html += getItemPreviewHTML(item, listItemKey) html += getItemControlHTML(index, listId) html += "</div>" return html ############################################################ getItemPreviewHTML = (item, key) -> html = "" if typeof item == "string" html += "<div class='admin-bigpanel-list-item-preview' " html += "text-content-key='"+key+"' contentEditable='true'>" html += item html += "</div>" else # olog key # olog item html += "<div class='admin-bigpanel-list-item-preview' >" url = item["thumbnailURL"] urlKey = key+".thumbnailURL" if !url url = item["url"] urlKey = key+".url" if url imageKey = findAssociatedImageKey(url) html += "<img src='"+url+"' " html += "image-content-key='"+imageKey+"' >" # html += "<div text-content-key='"+urlKey+"' contentEditable='true'>" # html += url # html += "</div>" else for label,itemContent of item if typeof itemContent == "string" contentKey = key+"."+label html += "<div text-content-key='"+contentKey+"' contentEditable='true'>" html += itemContent html += "</div>" break html += "</div>" return html getItemControlHTML = (index, listId)-> html = "<div class='admin-bigpanel-list-item-control'>" html += getUpButtonHTML(index, listId) html += getDeleteButtonHTML(index, listId) html += getDownButtonHTML(index, listId) html += "</div>" return html ############################################################ getAddButtonHTML = -> html = "<div class='admin-bigpanel-add-button'>" html += "<svg><use href='#admin-svg-add-icon'></svg>" html += "</div>" return html getUpButtonHTML = (index, listId) -> html = "<div class='admin-bigpanel-up-button' " html += "index='"+index+"' " html += "list-id='"+listId+"' " html += ">" html += "<svg><use href='#admin-svg-arrow-up-icon'></svg>" html += "</div>" return html getDownButtonHTML = (index, listId) -> html = "<div class='admin-bigpanel-down-button' " html += "index='"+index+"' " html += "list-id='"+listId+"' " html += ">" html += "<svg><use href='#admin-svg-arrow-down-icon'></svg>" html += "</div>" return html getDeleteButtonHTML = (index, listId) -> html = "<div class='admin-bigpanel-delete-button' " html += "index='"+index+"' " html += "list-id='"+listId+"' " html += ">" html += "<svg><use href='#admin-svg-delete-icon'></svg>" html += "</div>" return html ############################################################ getArrowLeftHTML = -> html = "<div class='admin-bigpanel-arrow-left'>" html += "<svg><use href='#admin-svg-arrow-left-icon'></svg>" html += "</div>" return html ############################################################ getArrowRightHTML = -> html = "<div class='admin-bigpanel-arrow-right'>" html += "<svg><use href='#admin-svg-arrow-right-icon'></svg>" html += "</div>" return html #endregion addList = (listId, list) -> # log "addList" allLists[listId] = list listInformationMap[listId] = {} listInfo = listInformationMap[listId] listInfo.id = listId listInfo.list = list listInfo.editElement = createListEditElement(listId, list) listInfo.listElement = createListListElement(listId, list) return digestToLists = (prefix, content) -> # log "digestToLists" if Array.isArray(content) then addList(prefix, content) if prefix then nextPrefix = prefix+"." else nextPrefix = prefix for label,element of content if typeof element == "object" then digestToLists(nextPrefix+label, element) return ############################################################ #region exposedFunctions listmanagementmodule.setNewList = (list, listId) -> log "listmanagementmodule.setNewList" allLists[listId] = list return listmanagementmodule.prepareListElements = (content) -> log "listmanagementmodule.prepareListElements" allLists = {} digestToLists("",content) return listmanagementmodule.getListElement = (listId) -> # log "listmanagementmodule.getListElement" return unless listInformationMap[listId] return listInformationMap[listId].listElement return listmanagementmodule.getEditElement = (listId) -> # log "listmanagementmodule.getEditElement" return unless listInformationMap[listId] return listInformationMap[listId].editElement return listmanagementmodule.elementExists = (listId) -> # log "listmanagementmodule.elementExists" # log listId if !listInformationMap[listId] then return false # id = listInformationMap[listId].id # if !document.getElementById(id) then return false # log "does exist" return true listmanagementmodule.getLists = -> allLists #endregion module.exports = listmanagementmodule
117733
listmanagementmodule = {name: "listmanagementmodule"} ############################################################ #region printLogFunctions log = (arg) -> if adminModules.debugmodule.modulesToDebug["listmanagementmodule"]? then console.log "[listmanagementmodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ admin = null bigpanel = null bottomPanel = null contentHandler = null ############################################################ allLists = null listInformationMap = {} ############################################################ listmanagementmodule.initialize = -> log "listmanagementmodule.initialize" admin = adminModules.adminmodule bigpanel = adminModules.bigpanelmodule bottomPanel = adminModules.bottompanelmodule contentHandler = adminModules.contenthandlermodule return ############################################################ findURLsOfListItem = (listItem) -> log "findURLsOfListItem" urls = [] for label,element of listItem if label == "url" then urls.push(element) if typeof element == "object" then urls.push(findURLsOfListItem(element)) return urls.flat() findImageObject = (name) -> log "findImageObject" content = contentHandler.content() for label,image of content.images if image.name == name then return { label, image } return findAssociatedImageKey = (url) -> log "findAssociatedImageKey" imageObject = findAssetObject(url) if !imageObject or !imageObject.label console.log(url + " did not have an image object") return "" return imageObject.label findAssetObject = (url) -> log "findAssetObject" tokens = url.split("/") if tokens.length < 2 then return null if tokens[0] == "img" then return findImageObject(tokens[1]) if tokens.length < 3 then return null if tokens[1] == "img" then return findImageObject(tokens[2]) return findAssetObjects = (urlList) -> log "findAssetObjects" assetObjects = [] for url in urlList assetObjects.push(findAssetObject(url)) return assetObjects ############################################################ adjustAssetIndicesTo = (assetObjects, index) -> log "adjustAssetIndicesTo" newKey = ""+(index+1) assetObjects = JSON.parse(JSON.stringify(assetObjects)) for assetObject in assetObjects assetObject.label = assetObject.label.replace("1", newKey) if assetObject.image assetObject.image.name = assetObject.image.name.replace("1", newKey) if assetObject.image.thumbnail assetObject.image.thumbnail.name = assetObject.image.thumbnail.name.replace("1", newKey) return assetObjects adjustURLIndicesTo = (item, index) -> log "adjustURLIndicesTo" newKey = ""+(index+1) for label,element of item if label == "url" then item[label] = element.replace("1", newKey) if typeof element == "object" then adjustURLIndicesTo(element, index) return adjustURLIndicesFromTo = (item, fromIndex, toIndex) -> log "adjustURLIndicesFromTo" oldKey = ""+(fromIndex+1) newKey = ""+(toIndex+1) for label,element of item if label == "url" then item[label] = element.replace(oldKey, newKey) if typeof element == "object" then adjustURLIndicesFromTo(element, fromIndex, toIndex) return adjustURLIndicesOneDown = (list, index) -> log "adjustURLIndicesOneDown" while index < list.length adjustURLIndicesFromTo(list[index], index+1, index) index++ return ############################################################ createNewListItem = (templateEntry, index) -> log "createNewListItem" item = JSON.parse(JSON.stringify(templateEntry)) urlList = findURLsOfListItem(item) assetObjects = findAssetObjects(urlList) # olog assetObjects adjustURLIndicesTo(item, index) adjustedObjects = adjustAssetIndicesTo(assetObjects, index) # olog assetObjects if adjustedObjects content = contentHandler.content() oldImages = JSON.parse(JSON.stringify(content.images)) for label,element of adjustedObjects if element.image content.images[element.label] = element.image admin.noticeImagesEdits(oldImages) # olog assetEdits # olog item return item removeAssociatedAssets = (firstItem, index, lastIndex) -> log "removeAssociatedAssets" urlList = findURLsOfListItem(firstItem) assetObjects = findAssetObjects(urlList) if assetObjects adjustedObjects = adjustAssetIndicesTo(assetObjects, lastIndex) content = contentHandler.content() oldImages = JSON.parse(JSON.stringify(content.images)) for label,element of adjustedObjects if element.image delete content.images[element.label] imageMoves = createDeleteMoves(assetObjects, index, lastIndex) admin.noticeImageSwaps(imageMoves) admin.noticeImagesEdits(oldImages) return createDeleteMoves = (assetObjects, index, lastIndex) -> log "createDeleteMoves" moves = [] walker = index while walker < lastIndex walker = walker + 1 fromObjects = adjustAssetIndicesTo(assetObjects, walker) olog fromObjects toObjects = adjustAssetIndicesTo(assetObjects, walker-1) olog toObjects for label of fromObjects if fromObjects[label].image fromName = fromObjects[label].image.name toName = toObjects[label].image.name moves.push {fromName, toName} if fromObjects[label].image.thumbnail fromName = fromObjects[label].image.thumbnail.name toName = toObjects[label].image.thumbnail.name moves.push {fromName, toName} olog moves return moves createSwapMoves = (firstItem, fromIndex, toIndex) -> log "createSwapMoves" moves = [] urlList = findURLsOfListItem(firstItem) assetObjects = findAssetObjects(urlList) fromObjects = adjustAssetIndicesTo(assetObjects, fromIndex) olog fromObjects toObjects = adjustAssetIndicesTo(assetObjects, toIndex) olog toObjects for label of fromObjects if fromObjects[label].image fromName = fromObjects[label].image.name toName = "temp-"+fromObjects[label].image.name moves.push {fromName, toName} if fromObjects[label].image.thumbnail fromName = fromObjects[label].image.thumbnail.name toName = "temp-"+fromObjects[label].image.thumbnail.name moves.push {fromName, toName} for label of fromObjects if fromObjects[label].image fromName = toObjects[label].image.name toName = fromObjects[label].image.name moves.push {fromName, toName} if fromObjects[label].image.thumbnail fromName = toObjects[label].image.thumbnail.name toName = fromObjects[label].image.thumbnail.name moves.push {fromName, toName} for label of fromObjects if fromObjects[label].image fromName = "temp-"+fromObjects[label].image.name toName = toObjects[label].image.name moves.push {fromName, toName} if fromObjects[label].image.thumbnail fromName = "temp-"+fromObjects[label].image.thumbnail.name toName = toObjects[label].image.thumbnail.name moves.push {fromName, toName} olog moves return moves ############################################################ addButtonClicked = (event) -> log "addButtonClicked" listId = event.target.getAttribute("list-id") log listId list = allLists[listId] newList = JSON.parse(JSON.stringify(list)) newItem = createNewListItem(list[0], list.length) newList.push newItem # olog newList admin.noticeListEdit(listId, newList, list) return downButtonClicked = (event) -> log "downButtonClicked" listId = event.target.getAttribute("list-id") index = parseInt(event.target.getAttribute("index")) list = allLists[listId] nextIndex = index + 1 log index log nextIndex if nextIndex >= list.length bottomPanel.setErrorMessage("Das letzte Element kann nicht nach unten verschoben werden!") return # log listId # olog list newList = JSON.parse(JSON.stringify(list)) thisElement = newList[index] nextElement = newList[nextIndex] newList[nextIndex] = thisElement newList[index] = nextElement adjustURLIndicesFromTo(newList[nextIndex], index, nextIndex) adjustURLIndicesFromTo(newList[index], nextIndex, index) imageMoves = createSwapMoves(list[0], index, nextIndex) admin.noticeImageSwaps(imageMoves) admin.noticeListEdit(listId, newList, list) return upButtonClicked = (event) -> log "upButtonClicked" listId = event.target.getAttribute("list-id") index = parseInt(event.target.getAttribute("index")) list = allLists[listId] prevIndex = index - 1 log index log prevIndex if prevIndex < 0 bottomPanel.setErrorMessage("Das erste Element kann nicht nach oben verschoben werden!") return # log listId # olog list newList = JSON.parse(JSON.stringify(list)) thisElement = newList[index] prevElement = newList[prevIndex] newList[prevIndex] = thisElement newList[index] = prevElement adjustURLIndicesFromTo(newList[prevIndex], index, prevIndex) adjustURLIndicesFromTo(newList[index], prevIndex, index) imageMoves = createSwapMoves(list[0], index, prevIndex) admin.noticeImageSwaps(imageMoves) admin.noticeListEdit(listId, newList, list) return deleteButtonClicked = (event) -> log "deleteButtonClicked" listId = event.target.getAttribute("list-id") index = parseInt(event.target.getAttribute("index")) list = allLists[listId] log listId log index if list.length == 1 bottomPanel.setErrorMessage("Das letzte Element kann nicht gelöscht werden!") return newList = JSON.parse(JSON.stringify(list)) newList.splice(index, 1) removeAssociatedAssets(list[0], index, newList.length) # olog newList # olog index adjustURLIndicesOneDown(newList, index) # olog newList admin.noticeListEdit(listId, newList, list) return ############################################################ createListEditElement = (listId, list) -> # log "createImageEditElement" div = document.createElement("div") innerHTML = getEditHeadHTML(listId) for listItem,index in list innerHTML += getListItemHTML(listItem, index, listId) innerHTML += getAddButtonHTML(listId) div.innerHTML = innerHTML leftArrow = div.querySelector(".admin-bigpanel-arrow-left") addButton = div.querySelector(".admin-bigpanel-add-button") upButtons = div.querySelectorAll(".admin-bigpanel-up-button") downButtons = div.querySelectorAll(".admin-bigpanel-down-button") deleteButtons = div.querySelectorAll(".admin-bigpanel-delete-button") div.classList.add("admin-bigpanel-edit-element") div.setAttribute "list-id",listId leftArrow.setAttribute "list-id",listId addButton.setAttribute "list-id",listId addButton.addEventListener("click", addButtonClicked) for button in upButtons button.setAttribute "list-id",listId button.addEventListener("click", upButtonClicked) for button in downButtons button.setAttribute "list-id",listId button.addEventListener("click", downButtonClicked) for button in deleteButtons button.setAttribute "list-id",listId button.addEventListener("click", deleteButtonClicked) return div createListListElement = (listId, list) -> # log "createImageListElement" div = document.createElement("div") innerHTML = "<div>"+listId+"</div>" innerHTML += getArrowRightHTML() div.innerHTML = innerHTML div.classList.add("admin-bigpanel-list-element") div.setAttribute "list-id",listId return div ############################################################ #region createElementHelpers getEditHeadHTML = (name) -> html = "<div class='admin-bigpanel-edit-head'>" html += getArrowLeftHTML() html += "<div>"+name+"</div>" html += "</div>" return html getListItemHTML = (item, index, listId) -> listItemKey = listId+"."+index html = "<div class='admin-bigpanel-list-item'>" html += getItemPreviewHTML(item, listItemKey) html += getItemControlHTML(index, listId) html += "</div>" return html ############################################################ getItemPreviewHTML = (item, key) -> html = "" if typeof item == "string" html += "<div class='admin-bigpanel-list-item-preview' " html += "text-content-key='"+key+"' contentEditable='true'>" html += item html += "</div>" else # olog key # olog item html += "<div class='admin-bigpanel-list-item-preview' >" url = item["thumbnailURL"] urlKey = <KEY>" if !url url = item["url"] urlKey = key+".<KEY>" if url imageKey = findAssociatedImageKey(url) html += "<img src='"+url+"' " html += "image-content-key='"+imageKey+"' >" # html += "<div text-content-key='"+urlKey+"' contentEditable='true'>" # html += url # html += "</div>" else for label,itemContent of item if typeof itemContent == "string" contentKey = key+"."+label html += "<div text-content-key='"+contentKey+"' contentEditable='true'>" html += itemContent html += "</div>" break html += "</div>" return html getItemControlHTML = (index, listId)-> html = "<div class='admin-bigpanel-list-item-control'>" html += getUpButtonHTML(index, listId) html += getDeleteButtonHTML(index, listId) html += getDownButtonHTML(index, listId) html += "</div>" return html ############################################################ getAddButtonHTML = -> html = "<div class='admin-bigpanel-add-button'>" html += "<svg><use href='#admin-svg-add-icon'></svg>" html += "</div>" return html getUpButtonHTML = (index, listId) -> html = "<div class='admin-bigpanel-up-button' " html += "index='"+index+"' " html += "list-id='"+listId+"' " html += ">" html += "<svg><use href='#admin-svg-arrow-up-icon'></svg>" html += "</div>" return html getDownButtonHTML = (index, listId) -> html = "<div class='admin-bigpanel-down-button' " html += "index='"+index+"' " html += "list-id='"+listId+"' " html += ">" html += "<svg><use href='#admin-svg-arrow-down-icon'></svg>" html += "</div>" return html getDeleteButtonHTML = (index, listId) -> html = "<div class='admin-bigpanel-delete-button' " html += "index='"+index+"' " html += "list-id='"+listId+"' " html += ">" html += "<svg><use href='#admin-svg-delete-icon'></svg>" html += "</div>" return html ############################################################ getArrowLeftHTML = -> html = "<div class='admin-bigpanel-arrow-left'>" html += "<svg><use href='#admin-svg-arrow-left-icon'></svg>" html += "</div>" return html ############################################################ getArrowRightHTML = -> html = "<div class='admin-bigpanel-arrow-right'>" html += "<svg><use href='#admin-svg-arrow-right-icon'></svg>" html += "</div>" return html #endregion addList = (listId, list) -> # log "addList" allLists[listId] = list listInformationMap[listId] = {} listInfo = listInformationMap[listId] listInfo.id = listId listInfo.list = list listInfo.editElement = createListEditElement(listId, list) listInfo.listElement = createListListElement(listId, list) return digestToLists = (prefix, content) -> # log "digestToLists" if Array.isArray(content) then addList(prefix, content) if prefix then nextPrefix = prefix+"." else nextPrefix = prefix for label,element of content if typeof element == "object" then digestToLists(nextPrefix+label, element) return ############################################################ #region exposedFunctions listmanagementmodule.setNewList = (list, listId) -> log "listmanagementmodule.setNewList" allLists[listId] = list return listmanagementmodule.prepareListElements = (content) -> log "listmanagementmodule.prepareListElements" allLists = {} digestToLists("",content) return listmanagementmodule.getListElement = (listId) -> # log "listmanagementmodule.getListElement" return unless listInformationMap[listId] return listInformationMap[listId].listElement return listmanagementmodule.getEditElement = (listId) -> # log "listmanagementmodule.getEditElement" return unless listInformationMap[listId] return listInformationMap[listId].editElement return listmanagementmodule.elementExists = (listId) -> # log "listmanagementmodule.elementExists" # log listId if !listInformationMap[listId] then return false # id = listInformationMap[listId].id # if !document.getElementById(id) then return false # log "does exist" return true listmanagementmodule.getLists = -> allLists #endregion module.exports = listmanagementmodule
true
listmanagementmodule = {name: "listmanagementmodule"} ############################################################ #region printLogFunctions log = (arg) -> if adminModules.debugmodule.modulesToDebug["listmanagementmodule"]? then console.log "[listmanagementmodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ admin = null bigpanel = null bottomPanel = null contentHandler = null ############################################################ allLists = null listInformationMap = {} ############################################################ listmanagementmodule.initialize = -> log "listmanagementmodule.initialize" admin = adminModules.adminmodule bigpanel = adminModules.bigpanelmodule bottomPanel = adminModules.bottompanelmodule contentHandler = adminModules.contenthandlermodule return ############################################################ findURLsOfListItem = (listItem) -> log "findURLsOfListItem" urls = [] for label,element of listItem if label == "url" then urls.push(element) if typeof element == "object" then urls.push(findURLsOfListItem(element)) return urls.flat() findImageObject = (name) -> log "findImageObject" content = contentHandler.content() for label,image of content.images if image.name == name then return { label, image } return findAssociatedImageKey = (url) -> log "findAssociatedImageKey" imageObject = findAssetObject(url) if !imageObject or !imageObject.label console.log(url + " did not have an image object") return "" return imageObject.label findAssetObject = (url) -> log "findAssetObject" tokens = url.split("/") if tokens.length < 2 then return null if tokens[0] == "img" then return findImageObject(tokens[1]) if tokens.length < 3 then return null if tokens[1] == "img" then return findImageObject(tokens[2]) return findAssetObjects = (urlList) -> log "findAssetObjects" assetObjects = [] for url in urlList assetObjects.push(findAssetObject(url)) return assetObjects ############################################################ adjustAssetIndicesTo = (assetObjects, index) -> log "adjustAssetIndicesTo" newKey = ""+(index+1) assetObjects = JSON.parse(JSON.stringify(assetObjects)) for assetObject in assetObjects assetObject.label = assetObject.label.replace("1", newKey) if assetObject.image assetObject.image.name = assetObject.image.name.replace("1", newKey) if assetObject.image.thumbnail assetObject.image.thumbnail.name = assetObject.image.thumbnail.name.replace("1", newKey) return assetObjects adjustURLIndicesTo = (item, index) -> log "adjustURLIndicesTo" newKey = ""+(index+1) for label,element of item if label == "url" then item[label] = element.replace("1", newKey) if typeof element == "object" then adjustURLIndicesTo(element, index) return adjustURLIndicesFromTo = (item, fromIndex, toIndex) -> log "adjustURLIndicesFromTo" oldKey = ""+(fromIndex+1) newKey = ""+(toIndex+1) for label,element of item if label == "url" then item[label] = element.replace(oldKey, newKey) if typeof element == "object" then adjustURLIndicesFromTo(element, fromIndex, toIndex) return adjustURLIndicesOneDown = (list, index) -> log "adjustURLIndicesOneDown" while index < list.length adjustURLIndicesFromTo(list[index], index+1, index) index++ return ############################################################ createNewListItem = (templateEntry, index) -> log "createNewListItem" item = JSON.parse(JSON.stringify(templateEntry)) urlList = findURLsOfListItem(item) assetObjects = findAssetObjects(urlList) # olog assetObjects adjustURLIndicesTo(item, index) adjustedObjects = adjustAssetIndicesTo(assetObjects, index) # olog assetObjects if adjustedObjects content = contentHandler.content() oldImages = JSON.parse(JSON.stringify(content.images)) for label,element of adjustedObjects if element.image content.images[element.label] = element.image admin.noticeImagesEdits(oldImages) # olog assetEdits # olog item return item removeAssociatedAssets = (firstItem, index, lastIndex) -> log "removeAssociatedAssets" urlList = findURLsOfListItem(firstItem) assetObjects = findAssetObjects(urlList) if assetObjects adjustedObjects = adjustAssetIndicesTo(assetObjects, lastIndex) content = contentHandler.content() oldImages = JSON.parse(JSON.stringify(content.images)) for label,element of adjustedObjects if element.image delete content.images[element.label] imageMoves = createDeleteMoves(assetObjects, index, lastIndex) admin.noticeImageSwaps(imageMoves) admin.noticeImagesEdits(oldImages) return createDeleteMoves = (assetObjects, index, lastIndex) -> log "createDeleteMoves" moves = [] walker = index while walker < lastIndex walker = walker + 1 fromObjects = adjustAssetIndicesTo(assetObjects, walker) olog fromObjects toObjects = adjustAssetIndicesTo(assetObjects, walker-1) olog toObjects for label of fromObjects if fromObjects[label].image fromName = fromObjects[label].image.name toName = toObjects[label].image.name moves.push {fromName, toName} if fromObjects[label].image.thumbnail fromName = fromObjects[label].image.thumbnail.name toName = toObjects[label].image.thumbnail.name moves.push {fromName, toName} olog moves return moves createSwapMoves = (firstItem, fromIndex, toIndex) -> log "createSwapMoves" moves = [] urlList = findURLsOfListItem(firstItem) assetObjects = findAssetObjects(urlList) fromObjects = adjustAssetIndicesTo(assetObjects, fromIndex) olog fromObjects toObjects = adjustAssetIndicesTo(assetObjects, toIndex) olog toObjects for label of fromObjects if fromObjects[label].image fromName = fromObjects[label].image.name toName = "temp-"+fromObjects[label].image.name moves.push {fromName, toName} if fromObjects[label].image.thumbnail fromName = fromObjects[label].image.thumbnail.name toName = "temp-"+fromObjects[label].image.thumbnail.name moves.push {fromName, toName} for label of fromObjects if fromObjects[label].image fromName = toObjects[label].image.name toName = fromObjects[label].image.name moves.push {fromName, toName} if fromObjects[label].image.thumbnail fromName = toObjects[label].image.thumbnail.name toName = fromObjects[label].image.thumbnail.name moves.push {fromName, toName} for label of fromObjects if fromObjects[label].image fromName = "temp-"+fromObjects[label].image.name toName = toObjects[label].image.name moves.push {fromName, toName} if fromObjects[label].image.thumbnail fromName = "temp-"+fromObjects[label].image.thumbnail.name toName = toObjects[label].image.thumbnail.name moves.push {fromName, toName} olog moves return moves ############################################################ addButtonClicked = (event) -> log "addButtonClicked" listId = event.target.getAttribute("list-id") log listId list = allLists[listId] newList = JSON.parse(JSON.stringify(list)) newItem = createNewListItem(list[0], list.length) newList.push newItem # olog newList admin.noticeListEdit(listId, newList, list) return downButtonClicked = (event) -> log "downButtonClicked" listId = event.target.getAttribute("list-id") index = parseInt(event.target.getAttribute("index")) list = allLists[listId] nextIndex = index + 1 log index log nextIndex if nextIndex >= list.length bottomPanel.setErrorMessage("Das letzte Element kann nicht nach unten verschoben werden!") return # log listId # olog list newList = JSON.parse(JSON.stringify(list)) thisElement = newList[index] nextElement = newList[nextIndex] newList[nextIndex] = thisElement newList[index] = nextElement adjustURLIndicesFromTo(newList[nextIndex], index, nextIndex) adjustURLIndicesFromTo(newList[index], nextIndex, index) imageMoves = createSwapMoves(list[0], index, nextIndex) admin.noticeImageSwaps(imageMoves) admin.noticeListEdit(listId, newList, list) return upButtonClicked = (event) -> log "upButtonClicked" listId = event.target.getAttribute("list-id") index = parseInt(event.target.getAttribute("index")) list = allLists[listId] prevIndex = index - 1 log index log prevIndex if prevIndex < 0 bottomPanel.setErrorMessage("Das erste Element kann nicht nach oben verschoben werden!") return # log listId # olog list newList = JSON.parse(JSON.stringify(list)) thisElement = newList[index] prevElement = newList[prevIndex] newList[prevIndex] = thisElement newList[index] = prevElement adjustURLIndicesFromTo(newList[prevIndex], index, prevIndex) adjustURLIndicesFromTo(newList[index], prevIndex, index) imageMoves = createSwapMoves(list[0], index, prevIndex) admin.noticeImageSwaps(imageMoves) admin.noticeListEdit(listId, newList, list) return deleteButtonClicked = (event) -> log "deleteButtonClicked" listId = event.target.getAttribute("list-id") index = parseInt(event.target.getAttribute("index")) list = allLists[listId] log listId log index if list.length == 1 bottomPanel.setErrorMessage("Das letzte Element kann nicht gelöscht werden!") return newList = JSON.parse(JSON.stringify(list)) newList.splice(index, 1) removeAssociatedAssets(list[0], index, newList.length) # olog newList # olog index adjustURLIndicesOneDown(newList, index) # olog newList admin.noticeListEdit(listId, newList, list) return ############################################################ createListEditElement = (listId, list) -> # log "createImageEditElement" div = document.createElement("div") innerHTML = getEditHeadHTML(listId) for listItem,index in list innerHTML += getListItemHTML(listItem, index, listId) innerHTML += getAddButtonHTML(listId) div.innerHTML = innerHTML leftArrow = div.querySelector(".admin-bigpanel-arrow-left") addButton = div.querySelector(".admin-bigpanel-add-button") upButtons = div.querySelectorAll(".admin-bigpanel-up-button") downButtons = div.querySelectorAll(".admin-bigpanel-down-button") deleteButtons = div.querySelectorAll(".admin-bigpanel-delete-button") div.classList.add("admin-bigpanel-edit-element") div.setAttribute "list-id",listId leftArrow.setAttribute "list-id",listId addButton.setAttribute "list-id",listId addButton.addEventListener("click", addButtonClicked) for button in upButtons button.setAttribute "list-id",listId button.addEventListener("click", upButtonClicked) for button in downButtons button.setAttribute "list-id",listId button.addEventListener("click", downButtonClicked) for button in deleteButtons button.setAttribute "list-id",listId button.addEventListener("click", deleteButtonClicked) return div createListListElement = (listId, list) -> # log "createImageListElement" div = document.createElement("div") innerHTML = "<div>"+listId+"</div>" innerHTML += getArrowRightHTML() div.innerHTML = innerHTML div.classList.add("admin-bigpanel-list-element") div.setAttribute "list-id",listId return div ############################################################ #region createElementHelpers getEditHeadHTML = (name) -> html = "<div class='admin-bigpanel-edit-head'>" html += getArrowLeftHTML() html += "<div>"+name+"</div>" html += "</div>" return html getListItemHTML = (item, index, listId) -> listItemKey = listId+"."+index html = "<div class='admin-bigpanel-list-item'>" html += getItemPreviewHTML(item, listItemKey) html += getItemControlHTML(index, listId) html += "</div>" return html ############################################################ getItemPreviewHTML = (item, key) -> html = "" if typeof item == "string" html += "<div class='admin-bigpanel-list-item-preview' " html += "text-content-key='"+key+"' contentEditable='true'>" html += item html += "</div>" else # olog key # olog item html += "<div class='admin-bigpanel-list-item-preview' >" url = item["thumbnailURL"] urlKey = PI:KEY:<KEY>END_PI" if !url url = item["url"] urlKey = key+".PI:KEY:<KEY>END_PI" if url imageKey = findAssociatedImageKey(url) html += "<img src='"+url+"' " html += "image-content-key='"+imageKey+"' >" # html += "<div text-content-key='"+urlKey+"' contentEditable='true'>" # html += url # html += "</div>" else for label,itemContent of item if typeof itemContent == "string" contentKey = key+"."+label html += "<div text-content-key='"+contentKey+"' contentEditable='true'>" html += itemContent html += "</div>" break html += "</div>" return html getItemControlHTML = (index, listId)-> html = "<div class='admin-bigpanel-list-item-control'>" html += getUpButtonHTML(index, listId) html += getDeleteButtonHTML(index, listId) html += getDownButtonHTML(index, listId) html += "</div>" return html ############################################################ getAddButtonHTML = -> html = "<div class='admin-bigpanel-add-button'>" html += "<svg><use href='#admin-svg-add-icon'></svg>" html += "</div>" return html getUpButtonHTML = (index, listId) -> html = "<div class='admin-bigpanel-up-button' " html += "index='"+index+"' " html += "list-id='"+listId+"' " html += ">" html += "<svg><use href='#admin-svg-arrow-up-icon'></svg>" html += "</div>" return html getDownButtonHTML = (index, listId) -> html = "<div class='admin-bigpanel-down-button' " html += "index='"+index+"' " html += "list-id='"+listId+"' " html += ">" html += "<svg><use href='#admin-svg-arrow-down-icon'></svg>" html += "</div>" return html getDeleteButtonHTML = (index, listId) -> html = "<div class='admin-bigpanel-delete-button' " html += "index='"+index+"' " html += "list-id='"+listId+"' " html += ">" html += "<svg><use href='#admin-svg-delete-icon'></svg>" html += "</div>" return html ############################################################ getArrowLeftHTML = -> html = "<div class='admin-bigpanel-arrow-left'>" html += "<svg><use href='#admin-svg-arrow-left-icon'></svg>" html += "</div>" return html ############################################################ getArrowRightHTML = -> html = "<div class='admin-bigpanel-arrow-right'>" html += "<svg><use href='#admin-svg-arrow-right-icon'></svg>" html += "</div>" return html #endregion addList = (listId, list) -> # log "addList" allLists[listId] = list listInformationMap[listId] = {} listInfo = listInformationMap[listId] listInfo.id = listId listInfo.list = list listInfo.editElement = createListEditElement(listId, list) listInfo.listElement = createListListElement(listId, list) return digestToLists = (prefix, content) -> # log "digestToLists" if Array.isArray(content) then addList(prefix, content) if prefix then nextPrefix = prefix+"." else nextPrefix = prefix for label,element of content if typeof element == "object" then digestToLists(nextPrefix+label, element) return ############################################################ #region exposedFunctions listmanagementmodule.setNewList = (list, listId) -> log "listmanagementmodule.setNewList" allLists[listId] = list return listmanagementmodule.prepareListElements = (content) -> log "listmanagementmodule.prepareListElements" allLists = {} digestToLists("",content) return listmanagementmodule.getListElement = (listId) -> # log "listmanagementmodule.getListElement" return unless listInformationMap[listId] return listInformationMap[listId].listElement return listmanagementmodule.getEditElement = (listId) -> # log "listmanagementmodule.getEditElement" return unless listInformationMap[listId] return listInformationMap[listId].editElement return listmanagementmodule.elementExists = (listId) -> # log "listmanagementmodule.elementExists" # log listId if !listInformationMap[listId] then return false # id = listInformationMap[listId].id # if !document.getElementById(id) then return false # log "does exist" return true listmanagementmodule.getLists = -> allLists #endregion module.exports = listmanagementmodule
[ { "context": " {\n data: 'view_user'\n name: 'view_user'\n searchable: false\n order", "end": 2259, "score": 0.563271164894104, "start": 2255, "tag": "NAME", "value": "view" } ]
app/assets/javascripts/admin/id_documents.js.coffee
saydulk/therubyracer
0
jQuery -> $('#verified_datatable').dataTable processing: true serverSide: true ajax: $('#verified_datatable').data('source') pagingType: 'full_numbers' searching: true language: { searchPlaceholder: "By Name or Email" } columns: [ { data:"name" name: "name" searchable: true orderable: true } { data: 'email' name: 'email' searchable: true orderable: true } # { # data: 'id_document_type' # name: 'id_document_type' # searchable: false # orderable: false # } { data: 'id_bill_type' name: 'id_document_type' searchable: false orderable: false } { data: 'updated_at' name: 'updated_at' searchable: false orderable: false } { data: 'verified' name: 'verified' searchable: false orderable: false } { data: 'view_user' name: 'view_user' searchable: false orderable: false } ] $('#unverified_datatable').dataTable processing: true serverSide: true ajax: $('#unverified_datatable').data('source') pagingType: 'full_numbers' searching: true language: { searchPlaceholder: "By Name or Email" } columns: [ { data:"name" name: "name" searchable: true orderable: true } { data: 'email' name: 'email' searchable: true orderable: true } # { # data: 'id_document_type' # name: 'id_document_type' # searchable: false # orderable: false # } { data: 'id_bill_type' name: 'id_document_type' searchable: false orderable: false } { data: 'updated_at' name: 'updated_at' searchable: false orderable: false } { data: 'verified' name: 'verified' searchable: false orderable: false } { data: 'view_user' name: 'view_user' searchable: false orderable: false } ]
44711
jQuery -> $('#verified_datatable').dataTable processing: true serverSide: true ajax: $('#verified_datatable').data('source') pagingType: 'full_numbers' searching: true language: { searchPlaceholder: "By Name or Email" } columns: [ { data:"name" name: "name" searchable: true orderable: true } { data: 'email' name: 'email' searchable: true orderable: true } # { # data: 'id_document_type' # name: 'id_document_type' # searchable: false # orderable: false # } { data: 'id_bill_type' name: 'id_document_type' searchable: false orderable: false } { data: 'updated_at' name: 'updated_at' searchable: false orderable: false } { data: 'verified' name: 'verified' searchable: false orderable: false } { data: 'view_user' name: 'view_user' searchable: false orderable: false } ] $('#unverified_datatable').dataTable processing: true serverSide: true ajax: $('#unverified_datatable').data('source') pagingType: 'full_numbers' searching: true language: { searchPlaceholder: "By Name or Email" } columns: [ { data:"name" name: "name" searchable: true orderable: true } { data: 'email' name: 'email' searchable: true orderable: true } # { # data: 'id_document_type' # name: 'id_document_type' # searchable: false # orderable: false # } { data: 'id_bill_type' name: 'id_document_type' searchable: false orderable: false } { data: 'updated_at' name: 'updated_at' searchable: false orderable: false } { data: 'verified' name: 'verified' searchable: false orderable: false } { data: 'view_user' name: '<NAME>_user' searchable: false orderable: false } ]
true
jQuery -> $('#verified_datatable').dataTable processing: true serverSide: true ajax: $('#verified_datatable').data('source') pagingType: 'full_numbers' searching: true language: { searchPlaceholder: "By Name or Email" } columns: [ { data:"name" name: "name" searchable: true orderable: true } { data: 'email' name: 'email' searchable: true orderable: true } # { # data: 'id_document_type' # name: 'id_document_type' # searchable: false # orderable: false # } { data: 'id_bill_type' name: 'id_document_type' searchable: false orderable: false } { data: 'updated_at' name: 'updated_at' searchable: false orderable: false } { data: 'verified' name: 'verified' searchable: false orderable: false } { data: 'view_user' name: 'view_user' searchable: false orderable: false } ] $('#unverified_datatable').dataTable processing: true serverSide: true ajax: $('#unverified_datatable').data('source') pagingType: 'full_numbers' searching: true language: { searchPlaceholder: "By Name or Email" } columns: [ { data:"name" name: "name" searchable: true orderable: true } { data: 'email' name: 'email' searchable: true orderable: true } # { # data: 'id_document_type' # name: 'id_document_type' # searchable: false # orderable: false # } { data: 'id_bill_type' name: 'id_document_type' searchable: false orderable: false } { data: 'updated_at' name: 'updated_at' searchable: false orderable: false } { data: 'verified' name: 'verified' searchable: false orderable: false } { data: 'view_user' name: 'PI:NAME:<NAME>END_PI_user' searchable: false orderable: false } ]
[ { "context": "/) and key not in hiddenFields\n if key is 'required'\n @mandatorySetting = new $viewMandatory", "end": 7893, "score": 0.9350880980491638, "start": 7885, "tag": "KEY", "value": "required" }, { "context": "s__constraint_message', (evt)=>\n rnkKey =...
kobo-docker/.vols/static/kpi/xlform/src/view.row.coffee
OpenOPx/kobotoolbox
0
_ = require 'underscore' Backbone = require 'backbone' $ = require 'jquery' $configs = require './model.configs' $rowSelector = require './view.rowSelector' $row = require './model.row' $modelUtils = require './model.utils' $viewTemplates = require './view.templates' $viewUtils = require './view.utils' $viewChoices = require './view.choices' $viewParams = require './view.params' $viewMandatorySetting = require './view.mandatorySetting' $acceptedFilesView = require './view.acceptedFiles' $viewRowDetail = require './view.rowDetail' renderKobomatrix = require('js/formbuild/renderInBackbone').renderKobomatrix _t = require('utils').t alertify = require 'alertifyjs' module.exports = do -> class BaseRowView extends Backbone.View tagName: "li" className: "survey__row xlf-row-view xlf-row-view--depr" events: "drop": "drop" initialize: (opts)-> @options = opts typeDetail = @model.get("type") @$el.attr("data-row-id", @model.cid) @ngScope = opts.ngScope @surveyView = @options.surveyView @model.on "detail-change", (key, value, ctxt)=> customEventName = $viewUtils.normalizeEventName("row-detail-change-#{key}") @$(".on-#{customEventName}").trigger(customEventName, key, value, ctxt) drop: (evt, index)-> @$el.trigger("update-sort", [@model, index]) getApp: -> @surveyView.getApp() # expandRowSelector: -> # new $rowSelector.RowSelector(el: @$el.find(".survey__row__spacer").get(0), ngScope: @ngScope, spawnedFromView: @).expand() render: (opts={})-> fixScroll = opts.fixScroll if @already_rendered return if fixScroll @$el.height(@$el.height()) @already_rendered = true if @model instanceof $row.RowError @_renderError() else @_renderRow() @is_expanded = @$card?.hasClass('card--expandedchoices') if fixScroll @$el.attr('style', '') @ _renderError: -> @$el.addClass("xlf-row-view-error") atts = $viewUtils.cleanStringify(@model.toJSON()) @$el.html $viewTemplates.$$render('row.rowErrorView', atts) @ _renderRow: -> @$el.html $viewTemplates.$$render('row.xlfRowView', @surveyView) @$label = @$('.js-card-label') @$hint = @$('.card__header-hint') @$card = @$('.card') @$header = @$('.card__header') context = {warnings: []} questionType = @model.get('type').get('typeId') if ( $configs.questionParams[questionType] and 'getParameters' of @model and questionType is 'range' ) @paramsView = new $viewParams.ParamsView({ rowView: @, parameters: @model.getParameters(), questionType: questionType }).render().insertInDOMAfter(@$header) if questionType is 'calculate' @$hint.hide() if 'getList' of @model and (cl = @model.getList()) @$card.addClass('card--selectquestion card--expandedchoices') @is_expanded = true @listView = new $viewChoices.ListView(model: cl, rowView: @).render() @cardSettingsWrap = @$('.card__settings').eq(0) @defaultRowDetailParent = @cardSettingsWrap.find('.card__settings__fields--question-options').eq(0) for [key, val] in @model.attributesArray() when key in ['label', 'hint', 'type'] view = new $viewRowDetail.DetailView(model: val, rowView: @) if key == 'label' and @model.get('type').get('value') == 'calculate' view.model = @model.get('calculation') @model.finalize() val.set('value', '') view.render().insertInDOM(@) if @model.getValue('required') @$card.addClass('card--required') @ toggleSettings: (show)-> if show is undefined show = !@_settingsExpanded if show and !@_settingsExpanded @_expandedRender() @$card.addClass('card--expanded-settings') @hideMultioptions?() @_settingsExpanded = true else if !show and @_settingsExpanded @$card.removeClass('card--expanded-settings') @_cleanupExpandedRender() @_settingsExpanded = false `` _cleanupExpandedRender: -> @$('.card__settings').detach() clone: (event) => parent = @model._parent model = @model if @model.get('type').get('typeId') in ['select_one', 'select_multiple'] model = @model.clone() else if @model.get('type').get('typeId') in ['rank', 'score'] model = @model.clone() @model.getSurvey().insert_row.call parent._parent, model, parent.models.indexOf(@model) + 1 add_row_to_question_library: (evt) => evt.stopPropagation() @ngScope?.add_row_to_question_library @model class GroupView extends BaseRowView className: "survey__row survey__row--group xlf-row-view xlf-row-view--depr" initialize: (opts)-> @options = opts @_shrunk = !!opts.shrunk @$el.attr("data-row-id", @model.cid) @surveyView = @options.surveyView deleteGroup: (evt)=> skipConfirm = $(evt.currentTarget).hasClass('js-force-delete-group') if skipConfirm or confirm(_t("Are you sure you want to split apart this group?")) @_deleteGroup() evt.preventDefault() _deleteGroup: () => @model.splitApart() @model._parent._parent.trigger('remove', @model) @surveyView.survey.trigger('change') @$el.detach() render: -> if !@already_rendered @$el.html $viewTemplates.row.groupView(@model) @$label = @$('.js-card-label') @$rows = @$('.group__rows').eq(0) @$card = @$('.card') @$header = @$('.card__header,.group__header').eq(0) @model.rows.each (row)=> @getApp().ensureElInView(row, @, @$rows).render() if !@already_rendered # only render the row details which are necessary for the initial view (ie 'label') view = new $viewRowDetail.DetailView(model: @model.get('label'), rowView: @) view.render().insertInDOM(@) @already_rendered = true @ hasNestedGroups: -> _.filter(@model.rows.models, (row) -> row.constructor.key == 'group').length > 0 _expandedRender: -> @$header.after($viewTemplates.row.groupSettingsView()) @cardSettingsWrap = @$('.card__settings').eq(0) @defaultRowDetailParent = @cardSettingsWrap.find('.card__settings__fields--active').eq(0) for [key, val] in @model.attributesArray() if key in ["name", "_isRepeat", "appearance", "relevant"] or key.match(/^.+::.+/) new $viewRowDetail.DetailView(model: val, rowView: @).render().insertInDOM(@) @model.on 'add', (row) => if row.constructor.key == 'group' $appearanceField = @$('.xlf-dv-appearance').eq(0) $appearanceField.hide() $appearanceField.find('input:checkbox').prop('checked', false) appearanceModel = @model.get('appearance') if appearanceModel.getValue() alertify.warning(_t("You can't display nested groups on the same screen - the setting has been removed from the parent group")) appearanceModel.set('value', '') @model.on 'remove', (row) => if row.constructor.key == 'group' && !@hasNestedGroups() @$('.xlf-dv-appearance').eq(0).show() @ class RowView extends BaseRowView _expandedRender: -> @$header.after($viewTemplates.row.rowSettingsView()) @cardSettingsWrap = @$('.card__settings').eq(0) @defaultRowDetailParent = @cardSettingsWrap.find('.card__settings__fields--question-options').eq(0) # don't display columns that start with a $ hiddenFields = ['label', 'hint', 'type', 'select_from_list_name', 'kobo--matrix_list', 'parameters'] for [key, val] in @model.attributesArray() when !key.match(/^\$/) and key not in hiddenFields if key is 'required' @mandatorySetting = new $viewMandatorySetting.MandatorySettingView({ model: @model.get('required') }).render().insertInDOM(@) else new $viewRowDetail.DetailView(model: val, rowView: @).render().insertInDOM(@) questionType = @model.get('type').get('typeId') if ( $configs.questionParams[questionType] and 'getParameters' of @model and questionType isnt 'range' ) @paramsView = new $viewParams.ParamsView({ rowView: @, parameters: @model.getParameters(), questionType: questionType }).render().insertInDOM(@) if questionType is 'file' @acceptedFilesView = new $acceptedFilesView.AcceptedFilesView({ rowView: @, acceptedFiles: @model.getAcceptedFiles() }).render().insertInDOM(@) return @ hideMultioptions: -> @$card.removeClass('card--expandedchoices') @is_expanded = false showMultioptions: -> @$card.addClass('card--expandedchoices') @$card.removeClass('card--expanded-settings') @toggleSettings(false) toggleMultioptions: -> if @is_expanded @hideMultioptions() else @showMultioptions() @is_expanded = true return class KoboMatrixView extends RowView className: "survey__row survey__row--kobo-matrix" _expandedRender: -> super() @$('.xlf-dv-required').hide() @$("li[data-card-settings-tab-id='validation-criteria']").hide() @$("li[data-card-settings-tab-id='skip-logic']").hide() _renderRow: -> @$el.html $viewTemplates.row.koboMatrixView() @matrix = @$('.card__kobomatrix') renderKobomatrix(@, @matrix) @$label = @$('.js-card-label') @$card = @$('.card') @$header = @$('.card__header') context = {warnings: []} for [key, val] in @model.attributesArray() when key is 'label' or key is 'type' view = new $viewRowDetail.DetailView(model: val, rowView: @) if key == 'label' and @model.get('type').get('value') == 'calculate' view.model = @model.get('calculation') @model.finalize() val.set('value', '') view.render().insertInDOM(@) @ class RankScoreView extends RowView _expandedRender: -> super() @$('.xlf-dv-required').hide() @$("li[data-card-settings-tab-id='validation-criteria']").hide() class ScoreView extends RankScoreView className: "survey__row survey__row--score" _renderRow: (args...)-> super(args) while @model._scoreChoices.options.length < 2 @model._scoreChoices.options.add(label: 'Option') score_choices = for sc in @model._scoreChoices.options.models autoname = '' if sc.get('name') in [undefined, ''] autoname = $modelUtils.sluggify(sc.get('label')) label: sc.get('label') name: sc.get('name') autoname: autoname cid: sc.cid if @model._scoreRows.length < 1 @model._scoreRows.add label: _t("Enter your question") name: '' score_rows = for sr in @model._scoreRows.models if sr.get('name') in [undefined, ''] autoname = $modelUtils.sluggify(sr.get('label'), validXmlTag: true) else autoname = '' label: sr.get('label') name: sr.get('name') autoname: autoname cid: sr.cid template_args = { score_rows: score_rows score_choices: score_choices } extra_score_contents = $viewTemplates.$$render('row.scoreView', template_args) @$('.card--selectquestion__expansion').eq(0).append(extra_score_contents).addClass('js-cancel-select-row') $rows = @$('.score__contents--rows').eq(0) $choices = @$('.score__contents--choices').eq(0) $el = @$el offOn = (evtName, selector, callback)-> $el.off(evtName).on(evtName, selector, callback) get_row = (cid)=> @model._scoreRows.get(cid) get_choice = (cid)=> @model._scoreChoices.options.get(cid) offOn 'click.deletescorerow', '.js-delete-scorerow', (evt)=> $et = $(evt.target) row_cid = $et.closest('tr').eq(0).data('row-cid') @model._scoreRows.remove(get_row(row_cid)) @already_rendered = false @render(fixScroll: true) offOn 'click.deletescorecol', '.js-delete-scorecol', (evt)=> $et = $(evt.target) @model._scoreChoices.options.remove(get_choice($et.closest('th').data('cid'))) @already_rendered = false @render(fixScroll: true) offOn 'input.editscorelabel', '.scorelabel__edit', (evt)-> $et = $(evt.target) row_cid = $et.closest('tr').eq(0).data('row-cid') get_row(row_cid).set('label', $et.text()) offOn 'input.namechange', '.scorelabel__name', (evt)=> $ect = $(evt.currentTarget) row_cid = $ect.closest('tr').eq(0).data('row-cid') _inpText = $ect.text() _text = $modelUtils.sluggify(_inpText, validXmlTag: true) get_row(row_cid).set('name', _text) if _text is '' $ect.addClass('scorelabel__name--automatic') else $ect.removeClass('scorelabel__name--automatic') $ect.off 'blur' $ect.on 'blur', ()-> if _inpText isnt _text $ect.text(_text) if _text is '' $ect.addClass('scorelabel__name--automatic') $ect.closest('td').find('.scorelabel__edit').trigger('keyup') else $ect.removeClass('scorelabel__name--automatic') offOn 'keyup.namekey', '.scorelabel__edit', (evt)=> $ect = $(evt.currentTarget) $nameWrap = $ect.closest('.scorelabel').find('.scorelabel__name') $nameWrap.attr('data-automatic-name', $modelUtils.sluggify($ect.text(), validXmlTag: true)) offOn 'input.choicechange', '.scorecell__label', (evt)=> $et = $(evt.target) get_choice($et.closest('th').data('cid')).set('label', $et.text()) offOn 'input.optvalchange', '.scorecell__name', (evt)=> $et = $(evt.target) _text = $et.text() if _text is '' $et.addClass('scorecell__name--automatic') else $et.removeClass('scorecell__name--automatic') get_choice($et.closest('th').eq(0).data('cid')).set('name', _text) offOn 'keyup.optlabelchange', '.scorecell__label', (evt)=> $ect = $(evt.currentTarget) $nameWrap = $ect.closest('.scorecell__col').find('.scorecell__name') $nameWrap.attr('data-automatic-name', $modelUtils.sluggify($ect.text())) offOn 'blur.choicechange', '.scorecell__label', (evt)=> @render() offOn 'click.addchoice', '.scorecell--add', (evt)=> @already_rendered = false @model._scoreChoices.options.add([label: 'Option']) @render(fixScroll: true) offOn 'click.addrow', '.scorerow--add', (evt)=> @already_rendered = false @model._scoreRows.add([label: 'Enter your question']) @render(fixScroll: true) class RankView extends RankScoreView className: "survey__row survey__row--rank" _renderRow: (args...)-> super(args) template_args = {} template_args.rank_constraint_msg = @model.get('kobo--rank-constraint-message')?.get('value') min_rank_levels_count = 2 if @model._rankRows.length > min_rank_levels_count min_rank_levels_count = @model._rankRows.length while @model._rankLevels.options.length < min_rank_levels_count @model._rankLevels.options.add label: "Item to be ranked" name: '' rank_levels = for model in @model._rankLevels.options.models _label = model.get('label') _name = model.get('name') _automatic = $modelUtils.sluggify(_label) label: _label name: _name automatic: _automatic set_automatic: _name is '' cid: model.cid template_args.rank_levels = rank_levels while @model._rankRows.length < 1 @model._rankRows.add label: '1st choice' name: '' rank_rows = for model in @model._rankRows.models _label = model.get('label') _name = model.get('name') _automatic = $modelUtils.sluggify(_label, validXmlTag: true) label: _label name: _name automatic: _automatic set_automatic: _name is '' cid: model.cid template_args.rank_rows = rank_rows extra_score_contents = $viewTemplates.$$render('row.rankView', @, template_args) @$('.card--selectquestion__expansion').eq(0).append(extra_score_contents).addClass('js-cancel-select-row') @editRanks() editRanks: -> @$([ '.rank_items__item__label', '.rank_items__level__label', '.rank_items__constraint_message', '.rank_items__name', ].join(',')).attr('contenteditable', 'true') $el = @$el offOn = (evtName, selector, callback)-> $el.off(evtName).on(evtName, selector, callback) get_item = (evt)=> parli = $(evt.target).parents('li').eq(0) cid = parli.eq(0).data('cid') if parli.hasClass('rank_items__level') @model._rankLevels.options.get(cid) else @model._rankRows.get(cid) offOn 'click.deleterankcell', '.js-delete-rankcell', (evt)=> if $(evt.target).parents('.rank__rows').length is 0 collection = @model._rankLevels.options else collection = @model._rankRows item = get_item(evt) collection.remove(item) @already_rendered = false @render(fixScroll: true) offOn 'input.ranklabelchange1', '.rank_items__item__label', (evt)-> $ect = $(evt.currentTarget) _text = $ect.text() _slugtext = $modelUtils.sluggify(_text, validXmlTag: true) $riName = $ect.closest('.rank_items__item').find('.rank_items__name') $riName.attr('data-automatic-name', _slugtext) get_item(evt).set('label', _text) offOn 'input.ranklabelchange2', '.rank_items__level__label', (evt)-> $ect = $(evt.currentTarget) _text = $ect.text() _slugtext = $modelUtils.sluggify(_text) $riName = $ect.closest('.rank_items__level').find('.rank_items__name') $riName.attr('data-automatic-name', _slugtext) get_item(evt).set('label', _text) offOn 'input.ranklabelchange3', '.rank_items__name', (evt)-> $ect = $(evt.currentTarget) _inptext = $ect.text() needs_valid_xml = $ect.parents('.rank_items__item').length > 0 _text = $modelUtils.sluggify(_inptext, validXmlTag: needs_valid_xml) $ect.off 'blur' $ect.one 'blur', -> if _text is '' $ect.addClass('rank_items__name--automatic') else if _inptext isnt _text log 'changin' $ect.text(_text) $ect.removeClass('rank_items__name--automatic') get_item(evt).set('name', _text) offOn 'focus', '.rank_items__constraint_message--prelim', (evt)-> $(evt.target).removeClass('rank_items__constraint_message--prelim').empty() offOn 'input.ranklabelchange4', '.rank_items__constraint_message', (evt)=> rnkKey = 'kobo--rank-constraint-message' @model.get(rnkKey).set('value', evt.target.textContent) offOn 'click.addrow', '.rank_items__add', (evt)=> if $(evt.target).parents('.rank__rows').length is 0 # add a level @model._rankLevels.options.add({label: 'Item', name: ''}) else chz = "1st 2nd 3rd".split(' ') # Please don't go up to 21 ch = if (@model._rankRows.length + 1 > chz.length) then "#{@model._rankRows.length + 1}th" else chz[@model._rankRows.length] @model._rankRows.add({label: "#{ch} choice", name: ''}) @already_rendered = false @render(fixScroll: true) RowView: RowView ScoreView: ScoreView KoboMatrixView: KoboMatrixView GroupView: GroupView RankView: RankView
61900
_ = require 'underscore' Backbone = require 'backbone' $ = require 'jquery' $configs = require './model.configs' $rowSelector = require './view.rowSelector' $row = require './model.row' $modelUtils = require './model.utils' $viewTemplates = require './view.templates' $viewUtils = require './view.utils' $viewChoices = require './view.choices' $viewParams = require './view.params' $viewMandatorySetting = require './view.mandatorySetting' $acceptedFilesView = require './view.acceptedFiles' $viewRowDetail = require './view.rowDetail' renderKobomatrix = require('js/formbuild/renderInBackbone').renderKobomatrix _t = require('utils').t alertify = require 'alertifyjs' module.exports = do -> class BaseRowView extends Backbone.View tagName: "li" className: "survey__row xlf-row-view xlf-row-view--depr" events: "drop": "drop" initialize: (opts)-> @options = opts typeDetail = @model.get("type") @$el.attr("data-row-id", @model.cid) @ngScope = opts.ngScope @surveyView = @options.surveyView @model.on "detail-change", (key, value, ctxt)=> customEventName = $viewUtils.normalizeEventName("row-detail-change-#{key}") @$(".on-#{customEventName}").trigger(customEventName, key, value, ctxt) drop: (evt, index)-> @$el.trigger("update-sort", [@model, index]) getApp: -> @surveyView.getApp() # expandRowSelector: -> # new $rowSelector.RowSelector(el: @$el.find(".survey__row__spacer").get(0), ngScope: @ngScope, spawnedFromView: @).expand() render: (opts={})-> fixScroll = opts.fixScroll if @already_rendered return if fixScroll @$el.height(@$el.height()) @already_rendered = true if @model instanceof $row.RowError @_renderError() else @_renderRow() @is_expanded = @$card?.hasClass('card--expandedchoices') if fixScroll @$el.attr('style', '') @ _renderError: -> @$el.addClass("xlf-row-view-error") atts = $viewUtils.cleanStringify(@model.toJSON()) @$el.html $viewTemplates.$$render('row.rowErrorView', atts) @ _renderRow: -> @$el.html $viewTemplates.$$render('row.xlfRowView', @surveyView) @$label = @$('.js-card-label') @$hint = @$('.card__header-hint') @$card = @$('.card') @$header = @$('.card__header') context = {warnings: []} questionType = @model.get('type').get('typeId') if ( $configs.questionParams[questionType] and 'getParameters' of @model and questionType is 'range' ) @paramsView = new $viewParams.ParamsView({ rowView: @, parameters: @model.getParameters(), questionType: questionType }).render().insertInDOMAfter(@$header) if questionType is 'calculate' @$hint.hide() if 'getList' of @model and (cl = @model.getList()) @$card.addClass('card--selectquestion card--expandedchoices') @is_expanded = true @listView = new $viewChoices.ListView(model: cl, rowView: @).render() @cardSettingsWrap = @$('.card__settings').eq(0) @defaultRowDetailParent = @cardSettingsWrap.find('.card__settings__fields--question-options').eq(0) for [key, val] in @model.attributesArray() when key in ['label', 'hint', 'type'] view = new $viewRowDetail.DetailView(model: val, rowView: @) if key == 'label' and @model.get('type').get('value') == 'calculate' view.model = @model.get('calculation') @model.finalize() val.set('value', '') view.render().insertInDOM(@) if @model.getValue('required') @$card.addClass('card--required') @ toggleSettings: (show)-> if show is undefined show = !@_settingsExpanded if show and !@_settingsExpanded @_expandedRender() @$card.addClass('card--expanded-settings') @hideMultioptions?() @_settingsExpanded = true else if !show and @_settingsExpanded @$card.removeClass('card--expanded-settings') @_cleanupExpandedRender() @_settingsExpanded = false `` _cleanupExpandedRender: -> @$('.card__settings').detach() clone: (event) => parent = @model._parent model = @model if @model.get('type').get('typeId') in ['select_one', 'select_multiple'] model = @model.clone() else if @model.get('type').get('typeId') in ['rank', 'score'] model = @model.clone() @model.getSurvey().insert_row.call parent._parent, model, parent.models.indexOf(@model) + 1 add_row_to_question_library: (evt) => evt.stopPropagation() @ngScope?.add_row_to_question_library @model class GroupView extends BaseRowView className: "survey__row survey__row--group xlf-row-view xlf-row-view--depr" initialize: (opts)-> @options = opts @_shrunk = !!opts.shrunk @$el.attr("data-row-id", @model.cid) @surveyView = @options.surveyView deleteGroup: (evt)=> skipConfirm = $(evt.currentTarget).hasClass('js-force-delete-group') if skipConfirm or confirm(_t("Are you sure you want to split apart this group?")) @_deleteGroup() evt.preventDefault() _deleteGroup: () => @model.splitApart() @model._parent._parent.trigger('remove', @model) @surveyView.survey.trigger('change') @$el.detach() render: -> if !@already_rendered @$el.html $viewTemplates.row.groupView(@model) @$label = @$('.js-card-label') @$rows = @$('.group__rows').eq(0) @$card = @$('.card') @$header = @$('.card__header,.group__header').eq(0) @model.rows.each (row)=> @getApp().ensureElInView(row, @, @$rows).render() if !@already_rendered # only render the row details which are necessary for the initial view (ie 'label') view = new $viewRowDetail.DetailView(model: @model.get('label'), rowView: @) view.render().insertInDOM(@) @already_rendered = true @ hasNestedGroups: -> _.filter(@model.rows.models, (row) -> row.constructor.key == 'group').length > 0 _expandedRender: -> @$header.after($viewTemplates.row.groupSettingsView()) @cardSettingsWrap = @$('.card__settings').eq(0) @defaultRowDetailParent = @cardSettingsWrap.find('.card__settings__fields--active').eq(0) for [key, val] in @model.attributesArray() if key in ["name", "_isRepeat", "appearance", "relevant"] or key.match(/^.+::.+/) new $viewRowDetail.DetailView(model: val, rowView: @).render().insertInDOM(@) @model.on 'add', (row) => if row.constructor.key == 'group' $appearanceField = @$('.xlf-dv-appearance').eq(0) $appearanceField.hide() $appearanceField.find('input:checkbox').prop('checked', false) appearanceModel = @model.get('appearance') if appearanceModel.getValue() alertify.warning(_t("You can't display nested groups on the same screen - the setting has been removed from the parent group")) appearanceModel.set('value', '') @model.on 'remove', (row) => if row.constructor.key == 'group' && !@hasNestedGroups() @$('.xlf-dv-appearance').eq(0).show() @ class RowView extends BaseRowView _expandedRender: -> @$header.after($viewTemplates.row.rowSettingsView()) @cardSettingsWrap = @$('.card__settings').eq(0) @defaultRowDetailParent = @cardSettingsWrap.find('.card__settings__fields--question-options').eq(0) # don't display columns that start with a $ hiddenFields = ['label', 'hint', 'type', 'select_from_list_name', 'kobo--matrix_list', 'parameters'] for [key, val] in @model.attributesArray() when !key.match(/^\$/) and key not in hiddenFields if key is '<KEY>' @mandatorySetting = new $viewMandatorySetting.MandatorySettingView({ model: @model.get('required') }).render().insertInDOM(@) else new $viewRowDetail.DetailView(model: val, rowView: @).render().insertInDOM(@) questionType = @model.get('type').get('typeId') if ( $configs.questionParams[questionType] and 'getParameters' of @model and questionType isnt 'range' ) @paramsView = new $viewParams.ParamsView({ rowView: @, parameters: @model.getParameters(), questionType: questionType }).render().insertInDOM(@) if questionType is 'file' @acceptedFilesView = new $acceptedFilesView.AcceptedFilesView({ rowView: @, acceptedFiles: @model.getAcceptedFiles() }).render().insertInDOM(@) return @ hideMultioptions: -> @$card.removeClass('card--expandedchoices') @is_expanded = false showMultioptions: -> @$card.addClass('card--expandedchoices') @$card.removeClass('card--expanded-settings') @toggleSettings(false) toggleMultioptions: -> if @is_expanded @hideMultioptions() else @showMultioptions() @is_expanded = true return class KoboMatrixView extends RowView className: "survey__row survey__row--kobo-matrix" _expandedRender: -> super() @$('.xlf-dv-required').hide() @$("li[data-card-settings-tab-id='validation-criteria']").hide() @$("li[data-card-settings-tab-id='skip-logic']").hide() _renderRow: -> @$el.html $viewTemplates.row.koboMatrixView() @matrix = @$('.card__kobomatrix') renderKobomatrix(@, @matrix) @$label = @$('.js-card-label') @$card = @$('.card') @$header = @$('.card__header') context = {warnings: []} for [key, val] in @model.attributesArray() when key is 'label' or key is 'type' view = new $viewRowDetail.DetailView(model: val, rowView: @) if key == 'label' and @model.get('type').get('value') == 'calculate' view.model = @model.get('calculation') @model.finalize() val.set('value', '') view.render().insertInDOM(@) @ class RankScoreView extends RowView _expandedRender: -> super() @$('.xlf-dv-required').hide() @$("li[data-card-settings-tab-id='validation-criteria']").hide() class ScoreView extends RankScoreView className: "survey__row survey__row--score" _renderRow: (args...)-> super(args) while @model._scoreChoices.options.length < 2 @model._scoreChoices.options.add(label: 'Option') score_choices = for sc in @model._scoreChoices.options.models autoname = '' if sc.get('name') in [undefined, ''] autoname = $modelUtils.sluggify(sc.get('label')) label: sc.get('label') name: sc.get('name') autoname: autoname cid: sc.cid if @model._scoreRows.length < 1 @model._scoreRows.add label: _t("Enter your question") name: '' score_rows = for sr in @model._scoreRows.models if sr.get('name') in [undefined, ''] autoname = $modelUtils.sluggify(sr.get('label'), validXmlTag: true) else autoname = '' label: sr.get('label') name: sr.get('name') autoname: autoname cid: sr.cid template_args = { score_rows: score_rows score_choices: score_choices } extra_score_contents = $viewTemplates.$$render('row.scoreView', template_args) @$('.card--selectquestion__expansion').eq(0).append(extra_score_contents).addClass('js-cancel-select-row') $rows = @$('.score__contents--rows').eq(0) $choices = @$('.score__contents--choices').eq(0) $el = @$el offOn = (evtName, selector, callback)-> $el.off(evtName).on(evtName, selector, callback) get_row = (cid)=> @model._scoreRows.get(cid) get_choice = (cid)=> @model._scoreChoices.options.get(cid) offOn 'click.deletescorerow', '.js-delete-scorerow', (evt)=> $et = $(evt.target) row_cid = $et.closest('tr').eq(0).data('row-cid') @model._scoreRows.remove(get_row(row_cid)) @already_rendered = false @render(fixScroll: true) offOn 'click.deletescorecol', '.js-delete-scorecol', (evt)=> $et = $(evt.target) @model._scoreChoices.options.remove(get_choice($et.closest('th').data('cid'))) @already_rendered = false @render(fixScroll: true) offOn 'input.editscorelabel', '.scorelabel__edit', (evt)-> $et = $(evt.target) row_cid = $et.closest('tr').eq(0).data('row-cid') get_row(row_cid).set('label', $et.text()) offOn 'input.namechange', '.scorelabel__name', (evt)=> $ect = $(evt.currentTarget) row_cid = $ect.closest('tr').eq(0).data('row-cid') _inpText = $ect.text() _text = $modelUtils.sluggify(_inpText, validXmlTag: true) get_row(row_cid).set('name', _text) if _text is '' $ect.addClass('scorelabel__name--automatic') else $ect.removeClass('scorelabel__name--automatic') $ect.off 'blur' $ect.on 'blur', ()-> if _inpText isnt _text $ect.text(_text) if _text is '' $ect.addClass('scorelabel__name--automatic') $ect.closest('td').find('.scorelabel__edit').trigger('keyup') else $ect.removeClass('scorelabel__name--automatic') offOn 'keyup.namekey', '.scorelabel__edit', (evt)=> $ect = $(evt.currentTarget) $nameWrap = $ect.closest('.scorelabel').find('.scorelabel__name') $nameWrap.attr('data-automatic-name', $modelUtils.sluggify($ect.text(), validXmlTag: true)) offOn 'input.choicechange', '.scorecell__label', (evt)=> $et = $(evt.target) get_choice($et.closest('th').data('cid')).set('label', $et.text()) offOn 'input.optvalchange', '.scorecell__name', (evt)=> $et = $(evt.target) _text = $et.text() if _text is '' $et.addClass('scorecell__name--automatic') else $et.removeClass('scorecell__name--automatic') get_choice($et.closest('th').eq(0).data('cid')).set('name', _text) offOn 'keyup.optlabelchange', '.scorecell__label', (evt)=> $ect = $(evt.currentTarget) $nameWrap = $ect.closest('.scorecell__col').find('.scorecell__name') $nameWrap.attr('data-automatic-name', $modelUtils.sluggify($ect.text())) offOn 'blur.choicechange', '.scorecell__label', (evt)=> @render() offOn 'click.addchoice', '.scorecell--add', (evt)=> @already_rendered = false @model._scoreChoices.options.add([label: 'Option']) @render(fixScroll: true) offOn 'click.addrow', '.scorerow--add', (evt)=> @already_rendered = false @model._scoreRows.add([label: 'Enter your question']) @render(fixScroll: true) class RankView extends RankScoreView className: "survey__row survey__row--rank" _renderRow: (args...)-> super(args) template_args = {} template_args.rank_constraint_msg = @model.get('kobo--rank-constraint-message')?.get('value') min_rank_levels_count = 2 if @model._rankRows.length > min_rank_levels_count min_rank_levels_count = @model._rankRows.length while @model._rankLevels.options.length < min_rank_levels_count @model._rankLevels.options.add label: "Item to be ranked" name: '' rank_levels = for model in @model._rankLevels.options.models _label = model.get('label') _name = model.get('name') _automatic = $modelUtils.sluggify(_label) label: _label name: _name automatic: _automatic set_automatic: _name is '' cid: model.cid template_args.rank_levels = rank_levels while @model._rankRows.length < 1 @model._rankRows.add label: '1st choice' name: '' rank_rows = for model in @model._rankRows.models _label = model.get('label') _name = model.get('name') _automatic = $modelUtils.sluggify(_label, validXmlTag: true) label: _label name: _name automatic: _automatic set_automatic: _name is '' cid: model.cid template_args.rank_rows = rank_rows extra_score_contents = $viewTemplates.$$render('row.rankView', @, template_args) @$('.card--selectquestion__expansion').eq(0).append(extra_score_contents).addClass('js-cancel-select-row') @editRanks() editRanks: -> @$([ '.rank_items__item__label', '.rank_items__level__label', '.rank_items__constraint_message', '.rank_items__name', ].join(',')).attr('contenteditable', 'true') $el = @$el offOn = (evtName, selector, callback)-> $el.off(evtName).on(evtName, selector, callback) get_item = (evt)=> parli = $(evt.target).parents('li').eq(0) cid = parli.eq(0).data('cid') if parli.hasClass('rank_items__level') @model._rankLevels.options.get(cid) else @model._rankRows.get(cid) offOn 'click.deleterankcell', '.js-delete-rankcell', (evt)=> if $(evt.target).parents('.rank__rows').length is 0 collection = @model._rankLevels.options else collection = @model._rankRows item = get_item(evt) collection.remove(item) @already_rendered = false @render(fixScroll: true) offOn 'input.ranklabelchange1', '.rank_items__item__label', (evt)-> $ect = $(evt.currentTarget) _text = $ect.text() _slugtext = $modelUtils.sluggify(_text, validXmlTag: true) $riName = $ect.closest('.rank_items__item').find('.rank_items__name') $riName.attr('data-automatic-name', _slugtext) get_item(evt).set('label', _text) offOn 'input.ranklabelchange2', '.rank_items__level__label', (evt)-> $ect = $(evt.currentTarget) _text = $ect.text() _slugtext = $modelUtils.sluggify(_text) $riName = $ect.closest('.rank_items__level').find('.rank_items__name') $riName.attr('data-automatic-name', _slugtext) get_item(evt).set('label', _text) offOn 'input.ranklabelchange3', '.rank_items__name', (evt)-> $ect = $(evt.currentTarget) _inptext = $ect.text() needs_valid_xml = $ect.parents('.rank_items__item').length > 0 _text = $modelUtils.sluggify(_inptext, validXmlTag: needs_valid_xml) $ect.off 'blur' $ect.one 'blur', -> if _text is '' $ect.addClass('rank_items__name--automatic') else if _inptext isnt _text log 'changin' $ect.text(_text) $ect.removeClass('rank_items__name--automatic') get_item(evt).set('name', _text) offOn 'focus', '.rank_items__constraint_message--prelim', (evt)-> $(evt.target).removeClass('rank_items__constraint_message--prelim').empty() offOn 'input.ranklabelchange4', '.rank_items__constraint_message', (evt)=> rnkKey = '<KEY>' @model.get(rnkKey).set('value', evt.target.textContent) offOn 'click.addrow', '.rank_items__add', (evt)=> if $(evt.target).parents('.rank__rows').length is 0 # add a level @model._rankLevels.options.add({label: 'Item', name: ''}) else chz = "1st 2nd 3rd".split(' ') # Please don't go up to 21 ch = if (@model._rankRows.length + 1 > chz.length) then "#{@model._rankRows.length + 1}th" else chz[@model._rankRows.length] @model._rankRows.add({label: "#{ch} choice", name: ''}) @already_rendered = false @render(fixScroll: true) RowView: RowView ScoreView: ScoreView KoboMatrixView: KoboMatrixView GroupView: GroupView RankView: RankView
true
_ = require 'underscore' Backbone = require 'backbone' $ = require 'jquery' $configs = require './model.configs' $rowSelector = require './view.rowSelector' $row = require './model.row' $modelUtils = require './model.utils' $viewTemplates = require './view.templates' $viewUtils = require './view.utils' $viewChoices = require './view.choices' $viewParams = require './view.params' $viewMandatorySetting = require './view.mandatorySetting' $acceptedFilesView = require './view.acceptedFiles' $viewRowDetail = require './view.rowDetail' renderKobomatrix = require('js/formbuild/renderInBackbone').renderKobomatrix _t = require('utils').t alertify = require 'alertifyjs' module.exports = do -> class BaseRowView extends Backbone.View tagName: "li" className: "survey__row xlf-row-view xlf-row-view--depr" events: "drop": "drop" initialize: (opts)-> @options = opts typeDetail = @model.get("type") @$el.attr("data-row-id", @model.cid) @ngScope = opts.ngScope @surveyView = @options.surveyView @model.on "detail-change", (key, value, ctxt)=> customEventName = $viewUtils.normalizeEventName("row-detail-change-#{key}") @$(".on-#{customEventName}").trigger(customEventName, key, value, ctxt) drop: (evt, index)-> @$el.trigger("update-sort", [@model, index]) getApp: -> @surveyView.getApp() # expandRowSelector: -> # new $rowSelector.RowSelector(el: @$el.find(".survey__row__spacer").get(0), ngScope: @ngScope, spawnedFromView: @).expand() render: (opts={})-> fixScroll = opts.fixScroll if @already_rendered return if fixScroll @$el.height(@$el.height()) @already_rendered = true if @model instanceof $row.RowError @_renderError() else @_renderRow() @is_expanded = @$card?.hasClass('card--expandedchoices') if fixScroll @$el.attr('style', '') @ _renderError: -> @$el.addClass("xlf-row-view-error") atts = $viewUtils.cleanStringify(@model.toJSON()) @$el.html $viewTemplates.$$render('row.rowErrorView', atts) @ _renderRow: -> @$el.html $viewTemplates.$$render('row.xlfRowView', @surveyView) @$label = @$('.js-card-label') @$hint = @$('.card__header-hint') @$card = @$('.card') @$header = @$('.card__header') context = {warnings: []} questionType = @model.get('type').get('typeId') if ( $configs.questionParams[questionType] and 'getParameters' of @model and questionType is 'range' ) @paramsView = new $viewParams.ParamsView({ rowView: @, parameters: @model.getParameters(), questionType: questionType }).render().insertInDOMAfter(@$header) if questionType is 'calculate' @$hint.hide() if 'getList' of @model and (cl = @model.getList()) @$card.addClass('card--selectquestion card--expandedchoices') @is_expanded = true @listView = new $viewChoices.ListView(model: cl, rowView: @).render() @cardSettingsWrap = @$('.card__settings').eq(0) @defaultRowDetailParent = @cardSettingsWrap.find('.card__settings__fields--question-options').eq(0) for [key, val] in @model.attributesArray() when key in ['label', 'hint', 'type'] view = new $viewRowDetail.DetailView(model: val, rowView: @) if key == 'label' and @model.get('type').get('value') == 'calculate' view.model = @model.get('calculation') @model.finalize() val.set('value', '') view.render().insertInDOM(@) if @model.getValue('required') @$card.addClass('card--required') @ toggleSettings: (show)-> if show is undefined show = !@_settingsExpanded if show and !@_settingsExpanded @_expandedRender() @$card.addClass('card--expanded-settings') @hideMultioptions?() @_settingsExpanded = true else if !show and @_settingsExpanded @$card.removeClass('card--expanded-settings') @_cleanupExpandedRender() @_settingsExpanded = false `` _cleanupExpandedRender: -> @$('.card__settings').detach() clone: (event) => parent = @model._parent model = @model if @model.get('type').get('typeId') in ['select_one', 'select_multiple'] model = @model.clone() else if @model.get('type').get('typeId') in ['rank', 'score'] model = @model.clone() @model.getSurvey().insert_row.call parent._parent, model, parent.models.indexOf(@model) + 1 add_row_to_question_library: (evt) => evt.stopPropagation() @ngScope?.add_row_to_question_library @model class GroupView extends BaseRowView className: "survey__row survey__row--group xlf-row-view xlf-row-view--depr" initialize: (opts)-> @options = opts @_shrunk = !!opts.shrunk @$el.attr("data-row-id", @model.cid) @surveyView = @options.surveyView deleteGroup: (evt)=> skipConfirm = $(evt.currentTarget).hasClass('js-force-delete-group') if skipConfirm or confirm(_t("Are you sure you want to split apart this group?")) @_deleteGroup() evt.preventDefault() _deleteGroup: () => @model.splitApart() @model._parent._parent.trigger('remove', @model) @surveyView.survey.trigger('change') @$el.detach() render: -> if !@already_rendered @$el.html $viewTemplates.row.groupView(@model) @$label = @$('.js-card-label') @$rows = @$('.group__rows').eq(0) @$card = @$('.card') @$header = @$('.card__header,.group__header').eq(0) @model.rows.each (row)=> @getApp().ensureElInView(row, @, @$rows).render() if !@already_rendered # only render the row details which are necessary for the initial view (ie 'label') view = new $viewRowDetail.DetailView(model: @model.get('label'), rowView: @) view.render().insertInDOM(@) @already_rendered = true @ hasNestedGroups: -> _.filter(@model.rows.models, (row) -> row.constructor.key == 'group').length > 0 _expandedRender: -> @$header.after($viewTemplates.row.groupSettingsView()) @cardSettingsWrap = @$('.card__settings').eq(0) @defaultRowDetailParent = @cardSettingsWrap.find('.card__settings__fields--active').eq(0) for [key, val] in @model.attributesArray() if key in ["name", "_isRepeat", "appearance", "relevant"] or key.match(/^.+::.+/) new $viewRowDetail.DetailView(model: val, rowView: @).render().insertInDOM(@) @model.on 'add', (row) => if row.constructor.key == 'group' $appearanceField = @$('.xlf-dv-appearance').eq(0) $appearanceField.hide() $appearanceField.find('input:checkbox').prop('checked', false) appearanceModel = @model.get('appearance') if appearanceModel.getValue() alertify.warning(_t("You can't display nested groups on the same screen - the setting has been removed from the parent group")) appearanceModel.set('value', '') @model.on 'remove', (row) => if row.constructor.key == 'group' && !@hasNestedGroups() @$('.xlf-dv-appearance').eq(0).show() @ class RowView extends BaseRowView _expandedRender: -> @$header.after($viewTemplates.row.rowSettingsView()) @cardSettingsWrap = @$('.card__settings').eq(0) @defaultRowDetailParent = @cardSettingsWrap.find('.card__settings__fields--question-options').eq(0) # don't display columns that start with a $ hiddenFields = ['label', 'hint', 'type', 'select_from_list_name', 'kobo--matrix_list', 'parameters'] for [key, val] in @model.attributesArray() when !key.match(/^\$/) and key not in hiddenFields if key is 'PI:KEY:<KEY>END_PI' @mandatorySetting = new $viewMandatorySetting.MandatorySettingView({ model: @model.get('required') }).render().insertInDOM(@) else new $viewRowDetail.DetailView(model: val, rowView: @).render().insertInDOM(@) questionType = @model.get('type').get('typeId') if ( $configs.questionParams[questionType] and 'getParameters' of @model and questionType isnt 'range' ) @paramsView = new $viewParams.ParamsView({ rowView: @, parameters: @model.getParameters(), questionType: questionType }).render().insertInDOM(@) if questionType is 'file' @acceptedFilesView = new $acceptedFilesView.AcceptedFilesView({ rowView: @, acceptedFiles: @model.getAcceptedFiles() }).render().insertInDOM(@) return @ hideMultioptions: -> @$card.removeClass('card--expandedchoices') @is_expanded = false showMultioptions: -> @$card.addClass('card--expandedchoices') @$card.removeClass('card--expanded-settings') @toggleSettings(false) toggleMultioptions: -> if @is_expanded @hideMultioptions() else @showMultioptions() @is_expanded = true return class KoboMatrixView extends RowView className: "survey__row survey__row--kobo-matrix" _expandedRender: -> super() @$('.xlf-dv-required').hide() @$("li[data-card-settings-tab-id='validation-criteria']").hide() @$("li[data-card-settings-tab-id='skip-logic']").hide() _renderRow: -> @$el.html $viewTemplates.row.koboMatrixView() @matrix = @$('.card__kobomatrix') renderKobomatrix(@, @matrix) @$label = @$('.js-card-label') @$card = @$('.card') @$header = @$('.card__header') context = {warnings: []} for [key, val] in @model.attributesArray() when key is 'label' or key is 'type' view = new $viewRowDetail.DetailView(model: val, rowView: @) if key == 'label' and @model.get('type').get('value') == 'calculate' view.model = @model.get('calculation') @model.finalize() val.set('value', '') view.render().insertInDOM(@) @ class RankScoreView extends RowView _expandedRender: -> super() @$('.xlf-dv-required').hide() @$("li[data-card-settings-tab-id='validation-criteria']").hide() class ScoreView extends RankScoreView className: "survey__row survey__row--score" _renderRow: (args...)-> super(args) while @model._scoreChoices.options.length < 2 @model._scoreChoices.options.add(label: 'Option') score_choices = for sc in @model._scoreChoices.options.models autoname = '' if sc.get('name') in [undefined, ''] autoname = $modelUtils.sluggify(sc.get('label')) label: sc.get('label') name: sc.get('name') autoname: autoname cid: sc.cid if @model._scoreRows.length < 1 @model._scoreRows.add label: _t("Enter your question") name: '' score_rows = for sr in @model._scoreRows.models if sr.get('name') in [undefined, ''] autoname = $modelUtils.sluggify(sr.get('label'), validXmlTag: true) else autoname = '' label: sr.get('label') name: sr.get('name') autoname: autoname cid: sr.cid template_args = { score_rows: score_rows score_choices: score_choices } extra_score_contents = $viewTemplates.$$render('row.scoreView', template_args) @$('.card--selectquestion__expansion').eq(0).append(extra_score_contents).addClass('js-cancel-select-row') $rows = @$('.score__contents--rows').eq(0) $choices = @$('.score__contents--choices').eq(0) $el = @$el offOn = (evtName, selector, callback)-> $el.off(evtName).on(evtName, selector, callback) get_row = (cid)=> @model._scoreRows.get(cid) get_choice = (cid)=> @model._scoreChoices.options.get(cid) offOn 'click.deletescorerow', '.js-delete-scorerow', (evt)=> $et = $(evt.target) row_cid = $et.closest('tr').eq(0).data('row-cid') @model._scoreRows.remove(get_row(row_cid)) @already_rendered = false @render(fixScroll: true) offOn 'click.deletescorecol', '.js-delete-scorecol', (evt)=> $et = $(evt.target) @model._scoreChoices.options.remove(get_choice($et.closest('th').data('cid'))) @already_rendered = false @render(fixScroll: true) offOn 'input.editscorelabel', '.scorelabel__edit', (evt)-> $et = $(evt.target) row_cid = $et.closest('tr').eq(0).data('row-cid') get_row(row_cid).set('label', $et.text()) offOn 'input.namechange', '.scorelabel__name', (evt)=> $ect = $(evt.currentTarget) row_cid = $ect.closest('tr').eq(0).data('row-cid') _inpText = $ect.text() _text = $modelUtils.sluggify(_inpText, validXmlTag: true) get_row(row_cid).set('name', _text) if _text is '' $ect.addClass('scorelabel__name--automatic') else $ect.removeClass('scorelabel__name--automatic') $ect.off 'blur' $ect.on 'blur', ()-> if _inpText isnt _text $ect.text(_text) if _text is '' $ect.addClass('scorelabel__name--automatic') $ect.closest('td').find('.scorelabel__edit').trigger('keyup') else $ect.removeClass('scorelabel__name--automatic') offOn 'keyup.namekey', '.scorelabel__edit', (evt)=> $ect = $(evt.currentTarget) $nameWrap = $ect.closest('.scorelabel').find('.scorelabel__name') $nameWrap.attr('data-automatic-name', $modelUtils.sluggify($ect.text(), validXmlTag: true)) offOn 'input.choicechange', '.scorecell__label', (evt)=> $et = $(evt.target) get_choice($et.closest('th').data('cid')).set('label', $et.text()) offOn 'input.optvalchange', '.scorecell__name', (evt)=> $et = $(evt.target) _text = $et.text() if _text is '' $et.addClass('scorecell__name--automatic') else $et.removeClass('scorecell__name--automatic') get_choice($et.closest('th').eq(0).data('cid')).set('name', _text) offOn 'keyup.optlabelchange', '.scorecell__label', (evt)=> $ect = $(evt.currentTarget) $nameWrap = $ect.closest('.scorecell__col').find('.scorecell__name') $nameWrap.attr('data-automatic-name', $modelUtils.sluggify($ect.text())) offOn 'blur.choicechange', '.scorecell__label', (evt)=> @render() offOn 'click.addchoice', '.scorecell--add', (evt)=> @already_rendered = false @model._scoreChoices.options.add([label: 'Option']) @render(fixScroll: true) offOn 'click.addrow', '.scorerow--add', (evt)=> @already_rendered = false @model._scoreRows.add([label: 'Enter your question']) @render(fixScroll: true) class RankView extends RankScoreView className: "survey__row survey__row--rank" _renderRow: (args...)-> super(args) template_args = {} template_args.rank_constraint_msg = @model.get('kobo--rank-constraint-message')?.get('value') min_rank_levels_count = 2 if @model._rankRows.length > min_rank_levels_count min_rank_levels_count = @model._rankRows.length while @model._rankLevels.options.length < min_rank_levels_count @model._rankLevels.options.add label: "Item to be ranked" name: '' rank_levels = for model in @model._rankLevels.options.models _label = model.get('label') _name = model.get('name') _automatic = $modelUtils.sluggify(_label) label: _label name: _name automatic: _automatic set_automatic: _name is '' cid: model.cid template_args.rank_levels = rank_levels while @model._rankRows.length < 1 @model._rankRows.add label: '1st choice' name: '' rank_rows = for model in @model._rankRows.models _label = model.get('label') _name = model.get('name') _automatic = $modelUtils.sluggify(_label, validXmlTag: true) label: _label name: _name automatic: _automatic set_automatic: _name is '' cid: model.cid template_args.rank_rows = rank_rows extra_score_contents = $viewTemplates.$$render('row.rankView', @, template_args) @$('.card--selectquestion__expansion').eq(0).append(extra_score_contents).addClass('js-cancel-select-row') @editRanks() editRanks: -> @$([ '.rank_items__item__label', '.rank_items__level__label', '.rank_items__constraint_message', '.rank_items__name', ].join(',')).attr('contenteditable', 'true') $el = @$el offOn = (evtName, selector, callback)-> $el.off(evtName).on(evtName, selector, callback) get_item = (evt)=> parli = $(evt.target).parents('li').eq(0) cid = parli.eq(0).data('cid') if parli.hasClass('rank_items__level') @model._rankLevels.options.get(cid) else @model._rankRows.get(cid) offOn 'click.deleterankcell', '.js-delete-rankcell', (evt)=> if $(evt.target).parents('.rank__rows').length is 0 collection = @model._rankLevels.options else collection = @model._rankRows item = get_item(evt) collection.remove(item) @already_rendered = false @render(fixScroll: true) offOn 'input.ranklabelchange1', '.rank_items__item__label', (evt)-> $ect = $(evt.currentTarget) _text = $ect.text() _slugtext = $modelUtils.sluggify(_text, validXmlTag: true) $riName = $ect.closest('.rank_items__item').find('.rank_items__name') $riName.attr('data-automatic-name', _slugtext) get_item(evt).set('label', _text) offOn 'input.ranklabelchange2', '.rank_items__level__label', (evt)-> $ect = $(evt.currentTarget) _text = $ect.text() _slugtext = $modelUtils.sluggify(_text) $riName = $ect.closest('.rank_items__level').find('.rank_items__name') $riName.attr('data-automatic-name', _slugtext) get_item(evt).set('label', _text) offOn 'input.ranklabelchange3', '.rank_items__name', (evt)-> $ect = $(evt.currentTarget) _inptext = $ect.text() needs_valid_xml = $ect.parents('.rank_items__item').length > 0 _text = $modelUtils.sluggify(_inptext, validXmlTag: needs_valid_xml) $ect.off 'blur' $ect.one 'blur', -> if _text is '' $ect.addClass('rank_items__name--automatic') else if _inptext isnt _text log 'changin' $ect.text(_text) $ect.removeClass('rank_items__name--automatic') get_item(evt).set('name', _text) offOn 'focus', '.rank_items__constraint_message--prelim', (evt)-> $(evt.target).removeClass('rank_items__constraint_message--prelim').empty() offOn 'input.ranklabelchange4', '.rank_items__constraint_message', (evt)=> rnkKey = 'PI:KEY:<KEY>END_PI' @model.get(rnkKey).set('value', evt.target.textContent) offOn 'click.addrow', '.rank_items__add', (evt)=> if $(evt.target).parents('.rank__rows').length is 0 # add a level @model._rankLevels.options.add({label: 'Item', name: ''}) else chz = "1st 2nd 3rd".split(' ') # Please don't go up to 21 ch = if (@model._rankRows.length + 1 > chz.length) then "#{@model._rankRows.length + 1}th" else chz[@model._rankRows.length] @model._rankRows.add({label: "#{ch} choice", name: ''}) @already_rendered = false @render(fixScroll: true) RowView: RowView ScoreView: ScoreView KoboMatrixView: KoboMatrixView GroupView: GroupView RankView: RankView
[ { "context": "oject_id, version, pathname} = req.params\n\t\t\tkey = \"#{project_id}:#{version}:#{pathname}\"\n\t\t\tif @oldFiles[key]?\n\t\t\t\tres.send @oldFiles[key]", "end": 601, "score": 0.9945926666259766, "start": 563, "tag": "KEY", "value": "\"#{project_id}:#{version}:#{pathname}\"" ...
test/acceptance/coffee/helpers/MockProjectHistoryApi.coffee
davidmehren/web-sharelatex
0
express = require("express") app = express() module.exports = MockProjectHistoryApi = docs: {} oldFiles: {} projectVersions: {} addOldFile: (project_id, version, pathname, content) -> @oldFiles["#{project_id}:#{version}:#{pathname}"] = content setProjectVersion: (project_id, version) -> @projectVersions[project_id] = version run: () -> app.post "/project", (req, res, next) => res.json project: id: 1 app.get "/project/:project_id/version/:version/:pathname", (req, res, next) => {project_id, version, pathname} = req.params key = "#{project_id}:#{version}:#{pathname}" if @oldFiles[key]? res.send @oldFiles[key] else res.send 404 app.get "/project/:project_id/version", (req, res, next) => {project_id} = req.params if @projectVersions[project_id]? res.json version: @projectVersions[project_id] else res.send 404 app.listen 3054, (error) -> throw error if error? .on "error", (error) -> console.error "error starting MockProjectHistoryApi:", error.message process.exit(1) MockProjectHistoryApi.run()
106199
express = require("express") app = express() module.exports = MockProjectHistoryApi = docs: {} oldFiles: {} projectVersions: {} addOldFile: (project_id, version, pathname, content) -> @oldFiles["#{project_id}:#{version}:#{pathname}"] = content setProjectVersion: (project_id, version) -> @projectVersions[project_id] = version run: () -> app.post "/project", (req, res, next) => res.json project: id: 1 app.get "/project/:project_id/version/:version/:pathname", (req, res, next) => {project_id, version, pathname} = req.params key = <KEY> if @oldFiles[key]? res.send @oldFiles[key] else res.send 404 app.get "/project/:project_id/version", (req, res, next) => {project_id} = req.params if @projectVersions[project_id]? res.json version: @projectVersions[project_id] else res.send 404 app.listen 3054, (error) -> throw error if error? .on "error", (error) -> console.error "error starting MockProjectHistoryApi:", error.message process.exit(1) MockProjectHistoryApi.run()
true
express = require("express") app = express() module.exports = MockProjectHistoryApi = docs: {} oldFiles: {} projectVersions: {} addOldFile: (project_id, version, pathname, content) -> @oldFiles["#{project_id}:#{version}:#{pathname}"] = content setProjectVersion: (project_id, version) -> @projectVersions[project_id] = version run: () -> app.post "/project", (req, res, next) => res.json project: id: 1 app.get "/project/:project_id/version/:version/:pathname", (req, res, next) => {project_id, version, pathname} = req.params key = PI:KEY:<KEY>END_PI if @oldFiles[key]? res.send @oldFiles[key] else res.send 404 app.get "/project/:project_id/version", (req, res, next) => {project_id} = req.params if @projectVersions[project_id]? res.json version: @projectVersions[project_id] else res.send 404 app.listen 3054, (error) -> throw error if error? .on "error", (error) -> console.error "error starting MockProjectHistoryApi:", error.message process.exit(1) MockProjectHistoryApi.run()
[ { "context": "re is licensed under the MIT License.\n\n Copyright Fedor Indutny, 2011.\n\n Permission is hereby granted, free of c", "end": 110, "score": 0.9996153116226196, "start": 97, "tag": "NAME", "value": "Fedor Indutny" } ]
node_modules/index/lib/index/core/compact.coffee
beshrkayali/monkey-release-action
12
### Compaction for Node Index This software is licensed under the MIT License. Copyright Fedor Indutny, 2011. 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. ### step = require 'step' utils = require '../../index/utils' exports.compact = (_callback) -> storage = @storage callback = (err, data) => @releaseLock() process.nextTick -> _callback and _callback err, data if @lock(=> @compact _callback) return iterate = (callback) -> (err, page) -> if err return callback err in_leaf = page[0] && page[0][2] fns = page.map (item) -> -> step -> storage.read item[1], @parallel(), in_leaf return , (err, data) -> if err throw err if in_leaf # data is actual value storage.write data, @parallel(), in_leaf return iterate(@parallel()) null, data return , (err, new_pos) -> if err throw err item[1] = new_pos @parallel() null return , @parallel() fns.push (err) -> if err throw err storage.write page, @parallel() return fns.push callback step.apply null, fns step -> # will allow storage controller # to prepare it for if storage.beforeCompact storage.beforeCompact @parallel() else @parallel() null return , (err) -> if err throw err storage.readRoot iterate @parallel() return , (err, new_root_pos) -> if err throw err storage.writeRoot new_root_pos, @parallel() return , (err) -> if err throw err # @will allow storage to finalize all actions if storage.afterCompact storage.afterCompact @parallel() else @parallel() null return , callback
60491
### Compaction for Node Index This software is licensed under the MIT License. Copyright <NAME>, 2011. 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. ### step = require 'step' utils = require '../../index/utils' exports.compact = (_callback) -> storage = @storage callback = (err, data) => @releaseLock() process.nextTick -> _callback and _callback err, data if @lock(=> @compact _callback) return iterate = (callback) -> (err, page) -> if err return callback err in_leaf = page[0] && page[0][2] fns = page.map (item) -> -> step -> storage.read item[1], @parallel(), in_leaf return , (err, data) -> if err throw err if in_leaf # data is actual value storage.write data, @parallel(), in_leaf return iterate(@parallel()) null, data return , (err, new_pos) -> if err throw err item[1] = new_pos @parallel() null return , @parallel() fns.push (err) -> if err throw err storage.write page, @parallel() return fns.push callback step.apply null, fns step -> # will allow storage controller # to prepare it for if storage.beforeCompact storage.beforeCompact @parallel() else @parallel() null return , (err) -> if err throw err storage.readRoot iterate @parallel() return , (err, new_root_pos) -> if err throw err storage.writeRoot new_root_pos, @parallel() return , (err) -> if err throw err # @will allow storage to finalize all actions if storage.afterCompact storage.afterCompact @parallel() else @parallel() null return , callback
true
### Compaction for Node Index This software is licensed under the MIT License. Copyright PI:NAME:<NAME>END_PI, 2011. 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. ### step = require 'step' utils = require '../../index/utils' exports.compact = (_callback) -> storage = @storage callback = (err, data) => @releaseLock() process.nextTick -> _callback and _callback err, data if @lock(=> @compact _callback) return iterate = (callback) -> (err, page) -> if err return callback err in_leaf = page[0] && page[0][2] fns = page.map (item) -> -> step -> storage.read item[1], @parallel(), in_leaf return , (err, data) -> if err throw err if in_leaf # data is actual value storage.write data, @parallel(), in_leaf return iterate(@parallel()) null, data return , (err, new_pos) -> if err throw err item[1] = new_pos @parallel() null return , @parallel() fns.push (err) -> if err throw err storage.write page, @parallel() return fns.push callback step.apply null, fns step -> # will allow storage controller # to prepare it for if storage.beforeCompact storage.beforeCompact @parallel() else @parallel() null return , (err) -> if err throw err storage.readRoot iterate @parallel() return , (err, new_root_pos) -> if err throw err storage.writeRoot new_root_pos, @parallel() return , (err) -> if err throw err # @will allow storage to finalize all actions if storage.afterCompact storage.afterCompact @parallel() else @parallel() null return , callback
[ { "context": "ms =\n name: formData.name\n password: formData.password\n confirmation_token: $scope.confirmationTo", "end": 776, "score": 0.9990962147712708, "start": 759, "tag": "PASSWORD", "value": "formData.password" }, { "context": "inParams = { email: data.u...
ui/app/components/confirm-account-page/confirm-account-page.coffee
Metaburn/cobudget
1
module.exports = onExit: ($location) -> $location.url($location.path()) resolve: clearSession: (Session) -> Session.clear() url: '/confirm_account?confirmation_token&setup_group&email&name' template: require('./confirm-account-page.html') reloadOnSearch: false controller: ($scope, $auth, LoadBar, $location, $stateParams, Records, Session, Toast) -> $scope.confirmationToken = $stateParams.confirmation_token $scope.email = $stateParams.email $scope.name = $stateParams.name $scope.setupGroup = $stateParams.setup_group $scope.formData = [] $scope.formData.name = $stateParams.name $scope.confirmAccount = (formData) -> LoadBar.start() params = name: formData.name password: formData.password confirmation_token: $scope.confirmationToken Records.users.confirmAccount(params) .then (data) -> loginParams = { email: data.users[0].email, password: formData.password } if $scope.setupGroup Session.create(loginParams).then -> $location.path("/setup_group") else Session.create(loginParams, {redirectTo: 'group'}) .catch -> Toast.show('Sorry, that confirmation token has expired.') $location.path('/')
129112
module.exports = onExit: ($location) -> $location.url($location.path()) resolve: clearSession: (Session) -> Session.clear() url: '/confirm_account?confirmation_token&setup_group&email&name' template: require('./confirm-account-page.html') reloadOnSearch: false controller: ($scope, $auth, LoadBar, $location, $stateParams, Records, Session, Toast) -> $scope.confirmationToken = $stateParams.confirmation_token $scope.email = $stateParams.email $scope.name = $stateParams.name $scope.setupGroup = $stateParams.setup_group $scope.formData = [] $scope.formData.name = $stateParams.name $scope.confirmAccount = (formData) -> LoadBar.start() params = name: formData.name password: <PASSWORD> confirmation_token: $scope.confirmationToken Records.users.confirmAccount(params) .then (data) -> loginParams = { email: data.users[0].email, password: <PASSWORD> } if $scope.setupGroup Session.create(loginParams).then -> $location.path("/setup_group") else Session.create(loginParams, {redirectTo: 'group'}) .catch -> Toast.show('Sorry, that confirmation token has expired.') $location.path('/')
true
module.exports = onExit: ($location) -> $location.url($location.path()) resolve: clearSession: (Session) -> Session.clear() url: '/confirm_account?confirmation_token&setup_group&email&name' template: require('./confirm-account-page.html') reloadOnSearch: false controller: ($scope, $auth, LoadBar, $location, $stateParams, Records, Session, Toast) -> $scope.confirmationToken = $stateParams.confirmation_token $scope.email = $stateParams.email $scope.name = $stateParams.name $scope.setupGroup = $stateParams.setup_group $scope.formData = [] $scope.formData.name = $stateParams.name $scope.confirmAccount = (formData) -> LoadBar.start() params = name: formData.name password: PI:PASSWORD:<PASSWORD>END_PI confirmation_token: $scope.confirmationToken Records.users.confirmAccount(params) .then (data) -> loginParams = { email: data.users[0].email, password: PI:PASSWORD:<PASSWORD>END_PI } if $scope.setupGroup Session.create(loginParams).then -> $location.path("/setup_group") else Session.create(loginParams, {redirectTo: 'group'}) .catch -> Toast.show('Sorry, that confirmation token has expired.') $location.path('/')
[ { "context": "rt.equal '0', len\n assert.equal \"DELETE hello: bob\", body\n client\n .header('user-agent', 'fr", "end": 996, "score": 0.5217334032058716, "start": 993, "tag": "NAME", "value": "bob" }, { "context": "ob\", body\n client\n .header('user-agent', 'fre...
test/request_test.coffee
woledzki/node-scoped-http-client
4
ScopedClient = require('../src') http = require('http') assert = require('assert') called = 0 curr = null ua = null len = null server = http.createServer (req, res) -> body = '' req.on 'data', (chunk) -> body += chunk req.on 'end', -> curr = req.method ua = req.headers['user-agent'] len = req.headers['content-length'] respBody = "#{curr} hello: #{body} #{ua}" res.writeHead 200, 'content-type': 'text/plain' 'content-length': Buffer.byteLength(respBody) 'x-sent-authorization': req.headers.authorization res.write respBody if curr != 'HEAD' res.end() server.listen 9999 server.addListener 'listening', -> client = ScopedClient.create('http://localhost:9999') .headers({'user-agent':'bob'}) client.del("") (err, resp, body) -> called++ assert.equal 'DELETE', curr assert.equal 'bob', ua assert.equal '0', len assert.equal "DELETE hello: bob", body client .header('user-agent', 'fred') .auth('monkey', 'town') .put('yéå') (err, resp, body) -> called++ assert.equal 'PUT', curr assert.equal 'fred', ua assert.equal "PUT hello: yéå fred", body assert.equal 'Basic bW9ua2V5OnRvd24=', resp.headers['x-sent-authorization'] client .auth('mode:selektor') .head() (err, resp, body) -> called++ assert.equal 'HEAD', curr assert.equal 'Basic bW9kZTpzZWxla3Rvcg==', resp.headers['x-sent-authorization'] server.close() process.on 'exit', -> assert.equal 3, called
194610
ScopedClient = require('../src') http = require('http') assert = require('assert') called = 0 curr = null ua = null len = null server = http.createServer (req, res) -> body = '' req.on 'data', (chunk) -> body += chunk req.on 'end', -> curr = req.method ua = req.headers['user-agent'] len = req.headers['content-length'] respBody = "#{curr} hello: #{body} #{ua}" res.writeHead 200, 'content-type': 'text/plain' 'content-length': Buffer.byteLength(respBody) 'x-sent-authorization': req.headers.authorization res.write respBody if curr != 'HEAD' res.end() server.listen 9999 server.addListener 'listening', -> client = ScopedClient.create('http://localhost:9999') .headers({'user-agent':'bob'}) client.del("") (err, resp, body) -> called++ assert.equal 'DELETE', curr assert.equal 'bob', ua assert.equal '0', len assert.equal "DELETE hello: <NAME>", body client .header('user-agent', '<NAME>') .auth('monkey', 'town') .put('yéå') (err, resp, body) -> called++ assert.equal 'PUT', curr assert.equal 'fred', ua assert.equal "PUT hello: <NAME>", body assert.equal 'Basic bW9ua2V5OnRvd24=', resp.headers['x-sent-authorization'] client .auth('mode:selektor') .head() (err, resp, body) -> called++ assert.equal 'HEAD', curr assert.equal 'Basic bW9kZTpzZWxla3Rvcg==', resp.headers['x-sent-authorization'] server.close() process.on 'exit', -> assert.equal 3, called
true
ScopedClient = require('../src') http = require('http') assert = require('assert') called = 0 curr = null ua = null len = null server = http.createServer (req, res) -> body = '' req.on 'data', (chunk) -> body += chunk req.on 'end', -> curr = req.method ua = req.headers['user-agent'] len = req.headers['content-length'] respBody = "#{curr} hello: #{body} #{ua}" res.writeHead 200, 'content-type': 'text/plain' 'content-length': Buffer.byteLength(respBody) 'x-sent-authorization': req.headers.authorization res.write respBody if curr != 'HEAD' res.end() server.listen 9999 server.addListener 'listening', -> client = ScopedClient.create('http://localhost:9999') .headers({'user-agent':'bob'}) client.del("") (err, resp, body) -> called++ assert.equal 'DELETE', curr assert.equal 'bob', ua assert.equal '0', len assert.equal "DELETE hello: PI:NAME:<NAME>END_PI", body client .header('user-agent', 'PI:NAME:<NAME>END_PI') .auth('monkey', 'town') .put('yéå') (err, resp, body) -> called++ assert.equal 'PUT', curr assert.equal 'fred', ua assert.equal "PUT hello: PI:NAME:<NAME>END_PI", body assert.equal 'Basic bW9ua2V5OnRvd24=', resp.headers['x-sent-authorization'] client .auth('mode:selektor') .head() (err, resp, body) -> called++ assert.equal 'HEAD', curr assert.equal 'Basic bW9kZTpzZWxla3Rvcg==', resp.headers['x-sent-authorization'] server.close() process.on 'exit', -> assert.equal 3, called
[ { "context": "enario Amlinellol:'\n 'Enghreifftiau:'\n 'Anrhegedig a '\n 'Pryd '\n 'Yna '\n 'Ond '\n '", "end": 206, "score": 0.9004349112510681, "start": 194, "tag": "NAME", "value": "Anrhegedig a" }, { "context": " 'Enghreifftiau:'\n 'Anrhegedi...
settings/language-gherkin_cy-GB.cson
mackoj/language-gherkin-i18n
17
'.text.gherkin.feature.cy-GB': 'editor': 'completions': [ 'Arwedd:' 'Cefndir:' 'Enghraifft:' 'Scenario:' 'Scenario Amlinellol:' 'Enghreifftiau:' 'Anrhegedig a ' 'Pryd ' 'Yna ' 'Ond ' 'A ' ] 'increaseIndentPattern': 'Enghraifft: .*' 'Scenario: .*' 'commentStart': '# '
41023
'.text.gherkin.feature.cy-GB': 'editor': 'completions': [ 'Arwedd:' 'Cefndir:' 'Enghraifft:' 'Scenario:' 'Scenario Amlinellol:' 'Enghreifftiau:' '<NAME> ' '<NAME> ' '<NAME> ' '<NAME> ' 'A ' ] 'increaseIndentPattern': 'Enghraifft: .*' 'Scenario: .*' 'commentStart': '# '
true
'.text.gherkin.feature.cy-GB': 'editor': 'completions': [ 'Arwedd:' 'Cefndir:' 'Enghraifft:' 'Scenario:' 'Scenario Amlinellol:' 'Enghreifftiau:' 'PI:NAME:<NAME>END_PI ' 'PI:NAME:<NAME>END_PI ' 'PI:NAME:<NAME>END_PI ' 'PI:NAME:<NAME>END_PI ' 'A ' ] 'increaseIndentPattern': 'Enghraifft: .*' 'Scenario: .*' 'commentStart': '# '
[ { "context": "# 1900-2100区间内的公历、农历互转\n# charset UTF-8\n# Auth 程巍巍\n# 公历转农历:calendar.solar2lunar 1987,11,01\n\n# 农历1900", "end": 50, "score": 0.6575340032577515, "start": 47, "tag": "USERNAME", "value": "程巍巍" }, { "context": "摩羯座'}\n]\n\n# 1900-2100各年的24节气日期速查表\nsTermInfo = [\t\n\t'9...
CommonTool/ScriptsLibrary/SuperCalendar.coffee
LittoCats/IOSDevelopExtension
0
# 1900-2100区间内的公历、农历互转 # charset UTF-8 # Auth 程巍巍 # 公历转农历:calendar.solar2lunar 1987,11,01 # 农历1900-2100的润大小信息表 LunarInfo = [ 0x04bd8,0x04ae0,0x0a570,0x054d5,0x0d260,0x0d950,0x16554,0x056a0,0x09ad0,0x055d2, 0x04ae0,0x0a5b6,0x0a4d0,0x0d250,0x1d255,0x0b540,0x0d6a0,0x0ada2,0x095b0,0x14977, 0x04970,0x0a4b0,0x0b4b5,0x06a50,0x06d40,0x1ab54,0x02b60,0x09570,0x052f2,0x04970, 0x06566,0x0d4a0,0x0ea50,0x06e95,0x05ad0,0x02b60,0x186e3,0x092e0,0x1c8d7,0x0c950, 0x0d4a0,0x1d8a6,0x0b550,0x056a0,0x1a5b4,0x025d0,0x092d0,0x0d2b2,0x0a950,0x0b557, 0x06ca0,0x0b550,0x15355,0x04da0,0x0a5b0,0x14573,0x052b0,0x0a9a8,0x0e950,0x06aa0, 0x0aea6,0x0ab50,0x04b60,0x0aae4,0x0a570,0x05260,0x0f263,0x0d950,0x05b57,0x056a0, 0x096d0,0x04dd5,0x04ad0,0x0a4d0,0x0d4d4,0x0d250,0x0d558,0x0b540,0x0b6a0,0x195a6, 0x095b0,0x049b0,0x0a974,0x0a4b0,0x0b27a,0x06a50,0x06d40,0x0af46,0x0ab60,0x09570, 0x04af5,0x04970,0x064b0,0x074a3,0x0ea50,0x06b58,0x055c0,0x0ab60,0x096d5,0x092e0, 0x0c960,0x0d954,0x0d4a0,0x0da50,0x07552,0x056a0,0x0abb7,0x025d0,0x092d0,0x0cab5, 0x0a950,0x0b4a0,0x0baa4,0x0ad50,0x055d9,0x04ba0,0x0a5b0,0x15176,0x052b0,0x0a930, 0x07954,0x06aa0,0x0ad50,0x05b52,0x04b60,0x0a6e6,0x0a4e0,0x0d260,0x0ea65,0x0d530, 0x05aa0,0x076a3,0x096d0,0x04bd7,0x04ad0,0x0a4d0,0x1d0b6,0x0d250,0x0d520,0x0dd45, 0x0b5a0,0x056d0,0x055b2,0x049b0,0x0a577,0x0a4b0,0x0aa50,0x1b255,0x06d20,0x0ada0, 0x14b63,0x09370,0x049f8,0x04970,0x064b0,0x168a6,0x0ea50,0x06b20,0x1a6c4,0x0aae0, 0x0a2e0,0x0d2e3,0x0c960,0x0d557,0x0d4a0,0x0da50,0x05d55,0x056a0,0x0a6d0,0x055d4, 0x052d0,0x0a9b8,0x0a950,0x0b4a0,0x0b6a6,0x0ad50,0x055a0,0x0aba4,0x0a5b0,0x052b0, 0x0b273,0x06930,0x07337,0x06aa0,0x0ad50,0x14b55,0x04b60,0x0a570,0x054e4,0x0d160, 0x0e968,0x0d520,0x0daa0,0x16aa6,0x056d0,0x04ae0,0x0a9d4,0x0a2d0,0x0d150,0x0f252, 0x0d520 ] # 公历每个月份的天数普通表 SolarMonth = [31,28,31,30,31,30,31,31,30,31,30,31] # 天干地支之天干速查表 Gan = ['甲','乙','丙','丁','戊','己','庚','辛','壬','癸'] # 天干地支之地支速查表 Zhi = ['子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥'] # 天干地支之地支速查表<=>生肖 Animals = ['鼠','牛','虎','兔','龙','蛇','马','羊','猴','鸡','狗','猪'] # 24节气速查表 SolarTerm = ['小寒','大寒','立春','雨水','惊蛰','春分','清明','谷雨','立夏','小满','芒种','夏至','小暑','大暑','立秋','处暑','白露','秋分','寒露','霜降','立冬','小雪','大雪','冬至'] # 十二星座速查表 AstronomyInfo = [ {1223:'摩羯座'} {121:'水瓶座'} {220:'双鱼座'} {321:'牡羊座'} {421:'金牛座'} {522:'双子座'} {622:'巨蟹座'} {724:'狮子座'} {824:'处女座'} {924:'天秤座'} {1024:'天蝎座'} {1123:'射手座'} {1223:'摩羯座'} ] # 1900-2100各年的24节气日期速查表 sTermInfo = [ '9778397bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e','97bcf97c3598082c95f8c965cc920f', '97bd0b06bdb0722c965ce1cfcc920f','b027097bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f','97bd0b06bdb0722c965ce1cfcc920f','b027097bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e','97bcf97c359801ec95f8c965cc920f','97bd0b06bdb0722c965ce1cfcc920f', 'b027097bd097c36b0b6fc9274c91aa','9778397bd19801ec9210c965cc920e','97b6b97bd19801ec95f8c965cc920f', '97bd09801d98082c95f8e1cfcc920f','97bd097bd097c36b0b6fc9210c8dc2','9778397bd197c36c9210c9274c91aa', '97b6b97bd19801ec95f8c965cc920e','97bd09801d98082c95f8e1cfcc920f','97bd097bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c91aa','97b6b97bd19801ec95f8c965cc920e','97bcf97c3598082c95f8e1cfcc920f', '97bd097bd097c36b0b6fc9210c8dc2','9778397bd097c36c9210c9274c91aa','97b6b97bd19801ec9210c965cc920e', '97bcf97c3598082c95f8c965cc920f','97bd097bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e','97bcf97c3598082c95f8c965cc920f','97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e','97bcf97c359801ec95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f','97bd097bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e','97bcf97c359801ec95f8c965cc920f','97bd097bd07f595b0b6fc920fb0722', '9778397bd097c36b0b6fc9210c8dc2','9778397bd19801ec9210c9274c920e','97b6b97bd19801ec95f8c965cc920f', '97bd07f5307f595b0b0bc920fb0722','7f0e397bd097c36b0b6fc9210c8dc2','9778397bd097c36c9210c9274c920e', '97b6b97bd19801ec95f8c965cc920f','97bd07f5307f595b0b0bc920fb0722','7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c91aa','97b6b97bd19801ec9210c965cc920e','97bd07f1487f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2','9778397bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f595b0b0bb0b6fb0722','7f0e397bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e','97bcf7f1487f595b0b0bb0b6fb0722','7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e','97bcf7f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa','97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f531b0b0bb0b6fb0722','7f0e397bd07f595b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c9274c920e','97bcf7f0e47f531b0b0bb0b6fb0722','7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c91aa','97b6b97bd197c36c9210c9274c920e','97bcf7f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722','9778397bd097c36b0b6fc9210c8dc2','9778397bd097c36c9210c9274c920e', '97b6b7f0e47f531b0723b0b6fb0722','7f0e37f5307f595b0b0bc920fb0722','7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36b0b70c9274c91aa','97b6b7f0e47f531b0723b0b6fb0721','7f0e37f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc9210c8dc2','9778397bd097c36b0b6fc9274c91aa','97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f595b0b0bb0b6fb0722','7f0e397bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722','7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa','97b6b7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722','9778397bd097c36b0b6fc9274c91aa','97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722','7f0e397bd07f595b0b0bc920fb0722','9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0787b0721','7f0e27f0e47f531b0b0bb0b6fb0722','7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c91aa','97b6b7f0e47f149b0723b0787b0721','7f0e27f0e47f531b0723b0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722','9778397bd097c36b0b6fc9210c8dc2','977837f0e37f149b0723b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722','7f0e37f5307f595b0b0bc920fb0722','7f0e397bd097c35b0b6fc9210c8dc2', '977837f0e37f14998082b0787b0721','7f07e7f0e47f531b0723b0b6fb0721','7f0e37f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc9210c8dc2','977837f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722','7f0e397bd097c35b0b6fc920fb0722','977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722','7f0e397bd097c35b0b6fc920fb0722', '977837f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722','977837f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722','7f0e397bd07f595b0b0bc920fb0722','977837f0e37f14998082b0787b06bd', '7f07e7f0e47f149b0723b0787b0721','7f0e27f0e47f531b0b0bb0b6fb0722','7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14998082b0723b06bd','7f07e7f0e37f149b0723b0787b0721','7f0e27f0e47f531b0723b0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722','977837f0e37f14898082b0723b02d5','7ec967f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722','7f0e37f1487f595b0b0bb0b6fb0722','7f0e37f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b0721','7f07e7f0e47f531b0723b0b6fb0722','7f0e37f1487f531b0b0bb0b6fb0722', '7f0e37f0e37f14898082b0723b02d5','7ec967f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721', '7f0e37f1487f531b0b0bb0b6fb0722','7f0e37f0e37f14898082b072297c35','7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722','7f0e37f0e37f14898082b072297c35', '7ec967f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722', '7f0e37f0e366aa89801eb072297c35','7ec967f0e37f14998082b0787b06bd','7f07e7f0e47f149b0723b0787b0721', '7f0e27f1487f531b0b0bb0b6fb0722','7f0e37f0e366aa89801eb072297c35','7ec967f0e37f14998082b0723b06bd', '7f07e7f0e47f149b0723b0787b0721','7f0e27f0e47f531b0723b0b6fb0722','7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14998082b0723b06bd','7f07e7f0e37f14998083b0787b0721','7f0e27f0e47f531b0723b0b6fb0722', '7f0e37f0e366aa89801eb072297c35','7ec967f0e37f14898082b0723b02d5','7f07e7f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722','7f0e36665b66aa89801e9808297c35','665f67f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b0721','7f07e7f0e47f531b0723b0b6fb0722','7f0e36665b66a449801e9808297c35', '665f67f0e37f14898082b0723b02d5','7ec967f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721', '7f0e36665b66a449801e9808297c35','665f67f0e37f14898082b072297c35','7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721','7f0e26665b66a449801e9808297c35','665f67f0e37f1489801eb072297c35', '7ec967f0e37f14998082b0787b06bd','7f07e7f0e47f531b0723b0b6fb0721','7f0e27f1487f531b0b0bb0b6fb0722' ] # 数字转中文速查表 nStr1 = ['〇','一','二','三','四','五','六','七','八','九','十'] # 日期转农历称呼速查表 nStr2 = ['初','十','廿','卅'] # 月份转农历称呼速查表 nStr3 = ['正','二','三','四','五','六','七','八','九','十','冬','腊'] # 返回农历y年闰月是哪个月;若y年没有闰月 则返回0 # param lunar Year # return Number (0-12) leapMonth = (y)-> LunarInfo[y-1900] & 0xf # 返回农历y年闰月的天数 若该年没有闰月则返回0 # param lunar Year # return Number (0、29、30) leapMonthDays = (y)-> if leapMonth y return if LunarInfo[y-1900] & 0x10000 then 30 else 29 0 # 返回农历y年一整年的总天数 # param lunar Year # return Number lunarYearDays = (y)-> sum = 348; i = 0x8000 while i > 0x8 sum += 1 if (LunarInfo[y-1900] & i) i >>= 1 sum + leapMonthDays y # 返回农历y年m月(非闰月)的总天数,计算m为闰月时的天数请使用leapMonthDays方法 # param lunar Year # return Number (-1、29、30) lunarMonthDays = (y,m)-> return -1 if m > 12 or m < 1 #月份参数从1至12,参数错误返回-1 return if LunarInfo[y-1900] & (0x10000>>m) then 30 else 29 # 返回公历(!)y年m月的天数 # param solar Year # return Number (-1、28、29、30、31) solarDays = (y,m)-> return -1 if m>12 or m<1 #若参数错误 返回-1 ms = m-1; return SolarMonth[ms] if ms isnt 1 return if (y%4 is 0) && (y%100 isnt 0) or (y%400 is 0) then 29 else 28 #2月份的闰平规律测算后确认返回28或29 # 传入offset偏移量返回干支 # param offset 相对甲子的偏移量 # return 中文 toGanZhi = (offset)-> Gan[offset%10] + Zhi[offset%12] # 公历(!)y年获得该年第n个节气的公历日期 # param y公历年(1900-2100);n二十四节气中的第几个节气(1~24);从n=1(小寒)算起 # return day Number getSolarTerm = (y,n)-> return -1 if y < 1900 or y > 2100 or n < 1 or n > 24 n -= 1 _table = sTermInfo[y-1900] _info = parseInt '0x'+_table.substr parseInt(n/4)*5,5 .toString() parseInt _info.substr [0,1,3,4][n%4], [1,2][n%4%2] # 传入农历数字年份返回汉语通俗表示法 # param lunar year # return Cn string # 若参数错误 返回 "" toChinaYear = (y)-> yStr = ''+y ret = '' ret += nStr1[parseInt yStr.substr i, 1] for i in [0...yStr.length] ret + '年' # 传入农历数字月份返回汉语通俗表示法 # param lunar month # return Cn string # 若参数错误 返回 "" toChinaMonth = (m)-> return if m>12 or m<1 then '' else nStr3[m-1] + '月' # 传入农历日期数字返回汉字表示法 # param lunar day # return Cn string # return Cn string # eg: cnDay = toChinaDay 21 #cnMonth='廿一' toChinaDay = (d)-> nStr2[Math.floor(d/10)]+nStr1[d%10] # 年份转生肖[!仅能大致转换] => 精确划分生肖分界线是“立春” # param y year # return Cn string getAnimal = (y)-> Animals[(y - 4) % 12] # 根据生日计算十二星座 # param solar month 1 ~ 12 # param solar day # return Cn string getAstronomy = (m,d)-> for key, value of AstronomyInfo[m] return value if m*100+d >= key return value for key, value of AstronomyInfo[m-1] # 传入公历年月日获得详细的公历、农历object信息 <=>JSON # param y solar year # param m solar month # param d solar day # return JSON object # 参数区间1900.1.31~2100.12.31 solar2lunar = (y,m,d)-> return -1 if y < 1900 or y > 2100 #年份限定、上限 return -1 if y is 1900 and m is 1 and d < 31 #下限 objDate = new Date y,parseInt(m - 1),d leap = 0 temp = 0 # 修正ymd参数 y = objDate.getFullYear() m = objDate.getMonth()+1 d = objDate.getDate() offset = (Date.UTC(y,m - 1,d) - Date.UTC(1900,0,31))/86400000 for i in [1900...2100] break if offset <= 0 temp = lunarYearDays i offset -= temp if offset<0 then offset += temp; i-- # 是否今天 isTodayObj = new Date() isToday = isTodayObj.getFullYear()==y && isTodayObj.getMonth()+1==m && isTodayObj.getDate()==d # 星期几 nWeek = objDate.getDay() cWeek = nStr1[nWeek] nWeek = 7 if nWeek is 0 #数字表示周几顺应天朝周一开始的惯例 # 农历年 year = i # 闰哪个月 leap = leapMonth i isLeap = false; # 效验闰月 for i in [1...12] break if offset <= 0 # 闰月 if leap>0 && i==(leap+1) && isLeap==false --i; isLeap = true; temp = leapMonthDays year #计算农历闰月天数 else temp = lunarMonthDays year, i #计算农历普通月天数 # 解除闰月 isLeap = false if isLeap is true && i is leap+1 offset -= temp; if(offset==0 && leap>0 && i==leap+1) if isLeap then isLeap = false else isLeap = true; --i; if offset < 0 then offset += temp; --i # 农历月 month = i # 农历日 day = offset + 1 # 天干地支处理 sm = m-1 term3 = getSolarTerm year,3 #该农历年立春日期 gzY = toGanZhi year-4 #普通按年份计算,下方尚需按立春节气来修正 # 依据立春日进行修正gzY gzY = if sm<2 and d<term3 then toGanZhi year-5 else toGanZhi year-4 # 月柱 1900年1月小寒以前为 丙子月(60进制12) firstNode = getSolarTerm y,m*2-1 #返回当月「节」为几日开始 secondNode = getSolarTerm y,m*2 #返回当月「节」为几日开始 # 依据12节气修正干支月 gzM = if d<firstNode then toGanZhi (y-1900)*12+m+11 else toGanZhi (y-1900)*12+m+12 # 传入的日期的节气与否 isSolarTerm = false solarTerm = '' if firstNode is d isSolarTerm = true solarTerm = SolarTerm[m*2-2] if secondNode is d isSolarTerm = true solarTerm = SolarTerm[m*2-1] # 日柱 当月一日与 1900/1/1 相差天数 dayCyclical = Date.UTC(y,sm,1,0,0,0,0)/86400000+25567+10 gzD = toGanZhi dayCyclical+d-1 return { 'SolarYear':y 'SolarMonth':m 'SolarDay':d 'Week':nWeek 'LunarYear':year 'LunarMonth':month 'LunarDay':day 'LunarYearCN': toChinaYear year 'LunarMonthCN':(if isLeap then '闰' else '')+toChinaMonth month 'LunarDayCN':toChinaDay day 'GZYear':gzY 'GZMonth':gzM 'GZDay':gzD 'AnimalCN':getAnimal year 'AstronomyCN': getAstronomy m, d 'SolarTermCN':solarTerm 'WeekNameCN':'星期'+cWeek 'isSolarTerm':isSolarTerm 'isToday':isToday 'isLeapMonth':isLeap } # 传入公历年月日以及传入的月份是否闰月获得详细的公历、农历object信息 <=>JSON # param y lunar year # param m lunar month # param d lunar day # param isLeapMonth lunar month is leap or not. # return JSON object # 参数区间1900.1.31~2100.12.1 lunar2solar = (y,m,d,isLeapMonth)-> leapOffset = 0; leap_month = leapMonth y return -1 if isLeapMonth and leap_month isnt m #传参要求计算该闰月公历 但该年得出的闰月与传参的月份并不同 return -1 if (y is 2100 and m is 12 and d > 1) or (y is 1900 and m is 1 and d < 31) #超出了最大极限值 day = lunarMonthDays y,m return -1 if y < 1900 or y > 2100 or d > day #参数合法性效验 # 计算农历的时间差 offset = 0 offset += lunarYearDays i for i in [1900...y] leap = 0 isAdd= false for i in [1...m] leap = leapMonth y if !isAdd and (leap <= i and leap > 0) offset += leapMonthDays y isAdd = true offset += lunarMonthDays y, i # 转换闰月农历 需补充该年闰月的前一个月的时差 offset += day if isLeapMonth # 1900年农历正月一日的公历时间为1900年1月30日0时0分0秒(该时间也是本农历的最开始起始点) stmap = Date.UTC 1900,1,30,0,0,0 calObj = new Date (offset+d-31)*86400000+stmap solar2lunar calObj.getUTCFullYear(),calObj.getUTCMonth()+1,calObj.getUTCDate() @SuperCalendar = { lunar2solar: lunar2solar solar2lunar: solar2lunar leapMonth: leapMonth leapMonthDays: leapMonthDays lunarYearDays: lunarYearDays lunarMonthDays: lunarMonthDays solarDays: solarDays getSolarTerm: getSolarTerm getAnimal: getAnimal getAstronomy: getAstronomy } console.log @SuperCalendar.lunar2solar 2015,2,1 # console.log lunarYearDays 2015 # lunar2solar 2015,1,27
172413
# 1900-2100区间内的公历、农历互转 # charset UTF-8 # Auth 程巍巍 # 公历转农历:calendar.solar2lunar 1987,11,01 # 农历1900-2100的润大小信息表 LunarInfo = [ 0x04bd8,0x04ae0,0x0a570,0x054d5,0x0d260,0x0d950,0x16554,0x056a0,0x09ad0,0x055d2, 0x04ae0,0x0a5b6,0x0a4d0,0x0d250,0x1d255,0x0b540,0x0d6a0,0x0ada2,0x095b0,0x14977, 0x04970,0x0a4b0,0x0b4b5,0x06a50,0x06d40,0x1ab54,0x02b60,0x09570,0x052f2,0x04970, 0x06566,0x0d4a0,0x0ea50,0x06e95,0x05ad0,0x02b60,0x186e3,0x092e0,0x1c8d7,0x0c950, 0x0d4a0,0x1d8a6,0x0b550,0x056a0,0x1a5b4,0x025d0,0x092d0,0x0d2b2,0x0a950,0x0b557, 0x06ca0,0x0b550,0x15355,0x04da0,0x0a5b0,0x14573,0x052b0,0x0a9a8,0x0e950,0x06aa0, 0x0aea6,0x0ab50,0x04b60,0x0aae4,0x0a570,0x05260,0x0f263,0x0d950,0x05b57,0x056a0, 0x096d0,0x04dd5,0x04ad0,0x0a4d0,0x0d4d4,0x0d250,0x0d558,0x0b540,0x0b6a0,0x195a6, 0x095b0,0x049b0,0x0a974,0x0a4b0,0x0b27a,0x06a50,0x06d40,0x0af46,0x0ab60,0x09570, 0x04af5,0x04970,0x064b0,0x074a3,0x0ea50,0x06b58,0x055c0,0x0ab60,0x096d5,0x092e0, 0x0c960,0x0d954,0x0d4a0,0x0da50,0x07552,0x056a0,0x0abb7,0x025d0,0x092d0,0x0cab5, 0x0a950,0x0b4a0,0x0baa4,0x0ad50,0x055d9,0x04ba0,0x0a5b0,0x15176,0x052b0,0x0a930, 0x07954,0x06aa0,0x0ad50,0x05b52,0x04b60,0x0a6e6,0x0a4e0,0x0d260,0x0ea65,0x0d530, 0x05aa0,0x076a3,0x096d0,0x04bd7,0x04ad0,0x0a4d0,0x1d0b6,0x0d250,0x0d520,0x0dd45, 0x0b5a0,0x056d0,0x055b2,0x049b0,0x0a577,0x0a4b0,0x0aa50,0x1b255,0x06d20,0x0ada0, 0x14b63,0x09370,0x049f8,0x04970,0x064b0,0x168a6,0x0ea50,0x06b20,0x1a6c4,0x0aae0, 0x0a2e0,0x0d2e3,0x0c960,0x0d557,0x0d4a0,0x0da50,0x05d55,0x056a0,0x0a6d0,0x055d4, 0x052d0,0x0a9b8,0x0a950,0x0b4a0,0x0b6a6,0x0ad50,0x055a0,0x0aba4,0x0a5b0,0x052b0, 0x0b273,0x06930,0x07337,0x06aa0,0x0ad50,0x14b55,0x04b60,0x0a570,0x054e4,0x0d160, 0x0e968,0x0d520,0x0daa0,0x16aa6,0x056d0,0x04ae0,0x0a9d4,0x0a2d0,0x0d150,0x0f252, 0x0d520 ] # 公历每个月份的天数普通表 SolarMonth = [31,28,31,30,31,30,31,31,30,31,30,31] # 天干地支之天干速查表 Gan = ['甲','乙','丙','丁','戊','己','庚','辛','壬','癸'] # 天干地支之地支速查表 Zhi = ['子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥'] # 天干地支之地支速查表<=>生肖 Animals = ['鼠','牛','虎','兔','龙','蛇','马','羊','猴','鸡','狗','猪'] # 24节气速查表 SolarTerm = ['小寒','大寒','立春','雨水','惊蛰','春分','清明','谷雨','立夏','小满','芒种','夏至','小暑','大暑','立秋','处暑','白露','秋分','寒露','霜降','立冬','小雪','大雪','冬至'] # 十二星座速查表 AstronomyInfo = [ {1223:'摩羯座'} {121:'水瓶座'} {220:'双鱼座'} {321:'牡羊座'} {421:'金牛座'} {522:'双子座'} {622:'巨蟹座'} {724:'狮子座'} {824:'处女座'} {924:'天秤座'} {1024:'天蝎座'} {1123:'射手座'} {1223:'摩羯座'} ] # 1900-2100各年的24节气日期速查表 sTermInfo = [ '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>', '<KEY>','<KEY>','<KEY>2' ] # 数字转中文速查表 nStr1 = ['〇','一','二','三','四','五','六','七','八','九','十'] # 日期转农历称呼速查表 nStr2 = ['初','十','廿','卅'] # 月份转农历称呼速查表 nStr3 = ['正','二','三','四','五','六','七','八','九','十','冬','腊'] # 返回农历y年闰月是哪个月;若y年没有闰月 则返回0 # param lunar Year # return Number (0-12) leapMonth = (y)-> LunarInfo[y-1900] & 0xf # 返回农历y年闰月的天数 若该年没有闰月则返回0 # param lunar Year # return Number (0、29、30) leapMonthDays = (y)-> if leapMonth y return if LunarInfo[y-1900] & 0x10000 then 30 else 29 0 # 返回农历y年一整年的总天数 # param lunar Year # return Number lunarYearDays = (y)-> sum = 348; i = 0x8000 while i > 0x8 sum += 1 if (LunarInfo[y-1900] & i) i >>= 1 sum + leapMonthDays y # 返回农历y年m月(非闰月)的总天数,计算m为闰月时的天数请使用leapMonthDays方法 # param lunar Year # return Number (-1、29、30) lunarMonthDays = (y,m)-> return -1 if m > 12 or m < 1 #月份参数从1至12,参数错误返回-1 return if LunarInfo[y-1900] & (0x10000>>m) then 30 else 29 # 返回公历(!)y年m月的天数 # param solar Year # return Number (-1、28、29、30、31) solarDays = (y,m)-> return -1 if m>12 or m<1 #若参数错误 返回-1 ms = m-1; return SolarMonth[ms] if ms isnt 1 return if (y%4 is 0) && (y%100 isnt 0) or (y%400 is 0) then 29 else 28 #2月份的闰平规律测算后确认返回28或29 # 传入offset偏移量返回干支 # param offset 相对甲子的偏移量 # return 中文 toGanZhi = (offset)-> Gan[offset%10] + Zhi[offset%12] # 公历(!)y年获得该年第n个节气的公历日期 # param y公历年(1900-2100);n二十四节气中的第几个节气(1~24);从n=1(小寒)算起 # return day Number getSolarTerm = (y,n)-> return -1 if y < 1900 or y > 2100 or n < 1 or n > 24 n -= 1 _table = sTermInfo[y-1900] _info = parseInt '0x'+_table.substr parseInt(n/4)*5,5 .toString() parseInt _info.substr [0,1,3,4][n%4], [1,2][n%4%2] # 传入农历数字年份返回汉语通俗表示法 # param lunar year # return Cn string # 若参数错误 返回 "" toChinaYear = (y)-> yStr = ''+y ret = '' ret += nStr1[parseInt yStr.substr i, 1] for i in [0...yStr.length] ret + '年' # 传入农历数字月份返回汉语通俗表示法 # param lunar month # return Cn string # 若参数错误 返回 "" toChinaMonth = (m)-> return if m>12 or m<1 then '' else nStr3[m-1] + '月' # 传入农历日期数字返回汉字表示法 # param lunar day # return Cn string # return Cn string # eg: cnDay = toChinaDay 21 #cnMonth='廿一' toChinaDay = (d)-> nStr2[Math.floor(d/10)]+nStr1[d%10] # 年份转生肖[!仅能大致转换] => 精确划分生肖分界线是“立春” # param y year # return Cn string getAnimal = (y)-> Animals[(y - 4) % 12] # 根据生日计算十二星座 # param solar month 1 ~ 12 # param solar day # return Cn string getAstronomy = (m,d)-> for key, value of AstronomyInfo[m] return value if m*100+d >= key return value for key, value of AstronomyInfo[m-1] # 传入公历年月日获得详细的公历、农历object信息 <=>JSON # param y solar year # param m solar month # param d solar day # return JSON object # 参数区间1900.1.31~2100.12.31 solar2lunar = (y,m,d)-> return -1 if y < 1900 or y > 2100 #年份限定、上限 return -1 if y is 1900 and m is 1 and d < 31 #下限 objDate = new Date y,parseInt(m - 1),d leap = 0 temp = 0 # 修正ymd参数 y = objDate.getFullYear() m = objDate.getMonth()+1 d = objDate.getDate() offset = (Date.UTC(y,m - 1,d) - Date.UTC(1900,0,31))/86400000 for i in [1900...2100] break if offset <= 0 temp = lunarYearDays i offset -= temp if offset<0 then offset += temp; i-- # 是否今天 isTodayObj = new Date() isToday = isTodayObj.getFullYear()==y && isTodayObj.getMonth()+1==m && isTodayObj.getDate()==d # 星期几 nWeek = objDate.getDay() cWeek = nStr1[nWeek] nWeek = 7 if nWeek is 0 #数字表示周几顺应天朝周一开始的惯例 # 农历年 year = i # 闰哪个月 leap = leapMonth i isLeap = false; # 效验闰月 for i in [1...12] break if offset <= 0 # 闰月 if leap>0 && i==(leap+1) && isLeap==false --i; isLeap = true; temp = leapMonthDays year #计算农历闰月天数 else temp = lunarMonthDays year, i #计算农历普通月天数 # 解除闰月 isLeap = false if isLeap is true && i is leap+1 offset -= temp; if(offset==0 && leap>0 && i==leap+1) if isLeap then isLeap = false else isLeap = true; --i; if offset < 0 then offset += temp; --i # 农历月 month = i # 农历日 day = offset + 1 # 天干地支处理 sm = m-1 term3 = getSolarTerm year,3 #该农历年立春日期 gzY = toGanZhi year-4 #普通按年份计算,下方尚需按立春节气来修正 # 依据立春日进行修正gzY gzY = if sm<2 and d<term3 then toGanZhi year-5 else toGanZhi year-4 # 月柱 1900年1月小寒以前为 丙子月(60进制12) firstNode = getSolarTerm y,m*2-1 #返回当月「节」为几日开始 secondNode = getSolarTerm y,m*2 #返回当月「节」为几日开始 # 依据12节气修正干支月 gzM = if d<firstNode then toGanZhi (y-1900)*12+m+11 else toGanZhi (y-1900)*12+m+12 # 传入的日期的节气与否 isSolarTerm = false solarTerm = '' if firstNode is d isSolarTerm = true solarTerm = SolarTerm[m*2-2] if secondNode is d isSolarTerm = true solarTerm = SolarTerm[m*2-1] # 日柱 当月一日与 1900/1/1 相差天数 dayCyclical = Date.UTC(y,sm,1,0,0,0,0)/86400000+25567+10 gzD = toGanZhi dayCyclical+d-1 return { 'SolarYear':y 'SolarMonth':m 'SolarDay':d 'Week':nWeek 'LunarYear':year 'LunarMonth':month 'LunarDay':day 'LunarYearCN': toChinaYear year 'LunarMonthCN':(if isLeap then '闰' else '')+toChinaMonth month 'LunarDayCN':toChinaDay day 'GZYear':gzY 'GZMonth':gzM 'GZDay':gzD 'AnimalCN':getAnimal year 'AstronomyCN': getAstronomy m, d 'SolarTermCN':solarTerm 'WeekNameCN':'星期'+cWeek 'isSolarTerm':isSolarTerm 'isToday':isToday 'isLeapMonth':isLeap } # 传入公历年月日以及传入的月份是否闰月获得详细的公历、农历object信息 <=>JSON # param y lunar year # param m lunar month # param d lunar day # param isLeapMonth lunar month is leap or not. # return JSON object # 参数区间1900.1.31~2100.12.1 lunar2solar = (y,m,d,isLeapMonth)-> leapOffset = 0; leap_month = leapMonth y return -1 if isLeapMonth and leap_month isnt m #传参要求计算该闰月公历 但该年得出的闰月与传参的月份并不同 return -1 if (y is 2100 and m is 12 and d > 1) or (y is 1900 and m is 1 and d < 31) #超出了最大极限值 day = lunarMonthDays y,m return -1 if y < 1900 or y > 2100 or d > day #参数合法性效验 # 计算农历的时间差 offset = 0 offset += lunarYearDays i for i in [1900...y] leap = 0 isAdd= false for i in [1...m] leap = leapMonth y if !isAdd and (leap <= i and leap > 0) offset += leapMonthDays y isAdd = true offset += lunarMonthDays y, i # 转换闰月农历 需补充该年闰月的前一个月的时差 offset += day if isLeapMonth # 1900年农历正月一日的公历时间为1900年1月30日0时0分0秒(该时间也是本农历的最开始起始点) stmap = Date.UTC 1900,1,30,0,0,0 calObj = new Date (offset+d-31)*86400000+stmap solar2lunar calObj.getUTCFullYear(),calObj.getUTCMonth()+1,calObj.getUTCDate() @SuperCalendar = { lunar2solar: lunar2solar solar2lunar: solar2lunar leapMonth: leapMonth leapMonthDays: leapMonthDays lunarYearDays: lunarYearDays lunarMonthDays: lunarMonthDays solarDays: solarDays getSolarTerm: getSolarTerm getAnimal: getAnimal getAstronomy: getAstronomy } console.log @SuperCalendar.lunar2solar 2015,2,1 # console.log lunarYearDays 2015 # lunar2solar 2015,1,27
true
# 1900-2100区间内的公历、农历互转 # charset UTF-8 # Auth 程巍巍 # 公历转农历:calendar.solar2lunar 1987,11,01 # 农历1900-2100的润大小信息表 LunarInfo = [ 0x04bd8,0x04ae0,0x0a570,0x054d5,0x0d260,0x0d950,0x16554,0x056a0,0x09ad0,0x055d2, 0x04ae0,0x0a5b6,0x0a4d0,0x0d250,0x1d255,0x0b540,0x0d6a0,0x0ada2,0x095b0,0x14977, 0x04970,0x0a4b0,0x0b4b5,0x06a50,0x06d40,0x1ab54,0x02b60,0x09570,0x052f2,0x04970, 0x06566,0x0d4a0,0x0ea50,0x06e95,0x05ad0,0x02b60,0x186e3,0x092e0,0x1c8d7,0x0c950, 0x0d4a0,0x1d8a6,0x0b550,0x056a0,0x1a5b4,0x025d0,0x092d0,0x0d2b2,0x0a950,0x0b557, 0x06ca0,0x0b550,0x15355,0x04da0,0x0a5b0,0x14573,0x052b0,0x0a9a8,0x0e950,0x06aa0, 0x0aea6,0x0ab50,0x04b60,0x0aae4,0x0a570,0x05260,0x0f263,0x0d950,0x05b57,0x056a0, 0x096d0,0x04dd5,0x04ad0,0x0a4d0,0x0d4d4,0x0d250,0x0d558,0x0b540,0x0b6a0,0x195a6, 0x095b0,0x049b0,0x0a974,0x0a4b0,0x0b27a,0x06a50,0x06d40,0x0af46,0x0ab60,0x09570, 0x04af5,0x04970,0x064b0,0x074a3,0x0ea50,0x06b58,0x055c0,0x0ab60,0x096d5,0x092e0, 0x0c960,0x0d954,0x0d4a0,0x0da50,0x07552,0x056a0,0x0abb7,0x025d0,0x092d0,0x0cab5, 0x0a950,0x0b4a0,0x0baa4,0x0ad50,0x055d9,0x04ba0,0x0a5b0,0x15176,0x052b0,0x0a930, 0x07954,0x06aa0,0x0ad50,0x05b52,0x04b60,0x0a6e6,0x0a4e0,0x0d260,0x0ea65,0x0d530, 0x05aa0,0x076a3,0x096d0,0x04bd7,0x04ad0,0x0a4d0,0x1d0b6,0x0d250,0x0d520,0x0dd45, 0x0b5a0,0x056d0,0x055b2,0x049b0,0x0a577,0x0a4b0,0x0aa50,0x1b255,0x06d20,0x0ada0, 0x14b63,0x09370,0x049f8,0x04970,0x064b0,0x168a6,0x0ea50,0x06b20,0x1a6c4,0x0aae0, 0x0a2e0,0x0d2e3,0x0c960,0x0d557,0x0d4a0,0x0da50,0x05d55,0x056a0,0x0a6d0,0x055d4, 0x052d0,0x0a9b8,0x0a950,0x0b4a0,0x0b6a6,0x0ad50,0x055a0,0x0aba4,0x0a5b0,0x052b0, 0x0b273,0x06930,0x07337,0x06aa0,0x0ad50,0x14b55,0x04b60,0x0a570,0x054e4,0x0d160, 0x0e968,0x0d520,0x0daa0,0x16aa6,0x056d0,0x04ae0,0x0a9d4,0x0a2d0,0x0d150,0x0f252, 0x0d520 ] # 公历每个月份的天数普通表 SolarMonth = [31,28,31,30,31,30,31,31,30,31,30,31] # 天干地支之天干速查表 Gan = ['甲','乙','丙','丁','戊','己','庚','辛','壬','癸'] # 天干地支之地支速查表 Zhi = ['子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥'] # 天干地支之地支速查表<=>生肖 Animals = ['鼠','牛','虎','兔','龙','蛇','马','羊','猴','鸡','狗','猪'] # 24节气速查表 SolarTerm = ['小寒','大寒','立春','雨水','惊蛰','春分','清明','谷雨','立夏','小满','芒种','夏至','小暑','大暑','立秋','处暑','白露','秋分','寒露','霜降','立冬','小雪','大雪','冬至'] # 十二星座速查表 AstronomyInfo = [ {1223:'摩羯座'} {121:'水瓶座'} {220:'双鱼座'} {321:'牡羊座'} {421:'金牛座'} {522:'双子座'} {622:'巨蟹座'} {724:'狮子座'} {824:'处女座'} {924:'天秤座'} {1024:'天蝎座'} {1123:'射手座'} {1223:'摩羯座'} ] # 1900-2100各年的24节气日期速查表 sTermInfo = [ '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', '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', 'PI:KEY:<KEY>END_PI','PI:KEY:<KEY>END_PI','PI:KEY:<KEY>END_PI2' ] # 数字转中文速查表 nStr1 = ['〇','一','二','三','四','五','六','七','八','九','十'] # 日期转农历称呼速查表 nStr2 = ['初','十','廿','卅'] # 月份转农历称呼速查表 nStr3 = ['正','二','三','四','五','六','七','八','九','十','冬','腊'] # 返回农历y年闰月是哪个月;若y年没有闰月 则返回0 # param lunar Year # return Number (0-12) leapMonth = (y)-> LunarInfo[y-1900] & 0xf # 返回农历y年闰月的天数 若该年没有闰月则返回0 # param lunar Year # return Number (0、29、30) leapMonthDays = (y)-> if leapMonth y return if LunarInfo[y-1900] & 0x10000 then 30 else 29 0 # 返回农历y年一整年的总天数 # param lunar Year # return Number lunarYearDays = (y)-> sum = 348; i = 0x8000 while i > 0x8 sum += 1 if (LunarInfo[y-1900] & i) i >>= 1 sum + leapMonthDays y # 返回农历y年m月(非闰月)的总天数,计算m为闰月时的天数请使用leapMonthDays方法 # param lunar Year # return Number (-1、29、30) lunarMonthDays = (y,m)-> return -1 if m > 12 or m < 1 #月份参数从1至12,参数错误返回-1 return if LunarInfo[y-1900] & (0x10000>>m) then 30 else 29 # 返回公历(!)y年m月的天数 # param solar Year # return Number (-1、28、29、30、31) solarDays = (y,m)-> return -1 if m>12 or m<1 #若参数错误 返回-1 ms = m-1; return SolarMonth[ms] if ms isnt 1 return if (y%4 is 0) && (y%100 isnt 0) or (y%400 is 0) then 29 else 28 #2月份的闰平规律测算后确认返回28或29 # 传入offset偏移量返回干支 # param offset 相对甲子的偏移量 # return 中文 toGanZhi = (offset)-> Gan[offset%10] + Zhi[offset%12] # 公历(!)y年获得该年第n个节气的公历日期 # param y公历年(1900-2100);n二十四节气中的第几个节气(1~24);从n=1(小寒)算起 # return day Number getSolarTerm = (y,n)-> return -1 if y < 1900 or y > 2100 or n < 1 or n > 24 n -= 1 _table = sTermInfo[y-1900] _info = parseInt '0x'+_table.substr parseInt(n/4)*5,5 .toString() parseInt _info.substr [0,1,3,4][n%4], [1,2][n%4%2] # 传入农历数字年份返回汉语通俗表示法 # param lunar year # return Cn string # 若参数错误 返回 "" toChinaYear = (y)-> yStr = ''+y ret = '' ret += nStr1[parseInt yStr.substr i, 1] for i in [0...yStr.length] ret + '年' # 传入农历数字月份返回汉语通俗表示法 # param lunar month # return Cn string # 若参数错误 返回 "" toChinaMonth = (m)-> return if m>12 or m<1 then '' else nStr3[m-1] + '月' # 传入农历日期数字返回汉字表示法 # param lunar day # return Cn string # return Cn string # eg: cnDay = toChinaDay 21 #cnMonth='廿一' toChinaDay = (d)-> nStr2[Math.floor(d/10)]+nStr1[d%10] # 年份转生肖[!仅能大致转换] => 精确划分生肖分界线是“立春” # param y year # return Cn string getAnimal = (y)-> Animals[(y - 4) % 12] # 根据生日计算十二星座 # param solar month 1 ~ 12 # param solar day # return Cn string getAstronomy = (m,d)-> for key, value of AstronomyInfo[m] return value if m*100+d >= key return value for key, value of AstronomyInfo[m-1] # 传入公历年月日获得详细的公历、农历object信息 <=>JSON # param y solar year # param m solar month # param d solar day # return JSON object # 参数区间1900.1.31~2100.12.31 solar2lunar = (y,m,d)-> return -1 if y < 1900 or y > 2100 #年份限定、上限 return -1 if y is 1900 and m is 1 and d < 31 #下限 objDate = new Date y,parseInt(m - 1),d leap = 0 temp = 0 # 修正ymd参数 y = objDate.getFullYear() m = objDate.getMonth()+1 d = objDate.getDate() offset = (Date.UTC(y,m - 1,d) - Date.UTC(1900,0,31))/86400000 for i in [1900...2100] break if offset <= 0 temp = lunarYearDays i offset -= temp if offset<0 then offset += temp; i-- # 是否今天 isTodayObj = new Date() isToday = isTodayObj.getFullYear()==y && isTodayObj.getMonth()+1==m && isTodayObj.getDate()==d # 星期几 nWeek = objDate.getDay() cWeek = nStr1[nWeek] nWeek = 7 if nWeek is 0 #数字表示周几顺应天朝周一开始的惯例 # 农历年 year = i # 闰哪个月 leap = leapMonth i isLeap = false; # 效验闰月 for i in [1...12] break if offset <= 0 # 闰月 if leap>0 && i==(leap+1) && isLeap==false --i; isLeap = true; temp = leapMonthDays year #计算农历闰月天数 else temp = lunarMonthDays year, i #计算农历普通月天数 # 解除闰月 isLeap = false if isLeap is true && i is leap+1 offset -= temp; if(offset==0 && leap>0 && i==leap+1) if isLeap then isLeap = false else isLeap = true; --i; if offset < 0 then offset += temp; --i # 农历月 month = i # 农历日 day = offset + 1 # 天干地支处理 sm = m-1 term3 = getSolarTerm year,3 #该农历年立春日期 gzY = toGanZhi year-4 #普通按年份计算,下方尚需按立春节气来修正 # 依据立春日进行修正gzY gzY = if sm<2 and d<term3 then toGanZhi year-5 else toGanZhi year-4 # 月柱 1900年1月小寒以前为 丙子月(60进制12) firstNode = getSolarTerm y,m*2-1 #返回当月「节」为几日开始 secondNode = getSolarTerm y,m*2 #返回当月「节」为几日开始 # 依据12节气修正干支月 gzM = if d<firstNode then toGanZhi (y-1900)*12+m+11 else toGanZhi (y-1900)*12+m+12 # 传入的日期的节气与否 isSolarTerm = false solarTerm = '' if firstNode is d isSolarTerm = true solarTerm = SolarTerm[m*2-2] if secondNode is d isSolarTerm = true solarTerm = SolarTerm[m*2-1] # 日柱 当月一日与 1900/1/1 相差天数 dayCyclical = Date.UTC(y,sm,1,0,0,0,0)/86400000+25567+10 gzD = toGanZhi dayCyclical+d-1 return { 'SolarYear':y 'SolarMonth':m 'SolarDay':d 'Week':nWeek 'LunarYear':year 'LunarMonth':month 'LunarDay':day 'LunarYearCN': toChinaYear year 'LunarMonthCN':(if isLeap then '闰' else '')+toChinaMonth month 'LunarDayCN':toChinaDay day 'GZYear':gzY 'GZMonth':gzM 'GZDay':gzD 'AnimalCN':getAnimal year 'AstronomyCN': getAstronomy m, d 'SolarTermCN':solarTerm 'WeekNameCN':'星期'+cWeek 'isSolarTerm':isSolarTerm 'isToday':isToday 'isLeapMonth':isLeap } # 传入公历年月日以及传入的月份是否闰月获得详细的公历、农历object信息 <=>JSON # param y lunar year # param m lunar month # param d lunar day # param isLeapMonth lunar month is leap or not. # return JSON object # 参数区间1900.1.31~2100.12.1 lunar2solar = (y,m,d,isLeapMonth)-> leapOffset = 0; leap_month = leapMonth y return -1 if isLeapMonth and leap_month isnt m #传参要求计算该闰月公历 但该年得出的闰月与传参的月份并不同 return -1 if (y is 2100 and m is 12 and d > 1) or (y is 1900 and m is 1 and d < 31) #超出了最大极限值 day = lunarMonthDays y,m return -1 if y < 1900 or y > 2100 or d > day #参数合法性效验 # 计算农历的时间差 offset = 0 offset += lunarYearDays i for i in [1900...y] leap = 0 isAdd= false for i in [1...m] leap = leapMonth y if !isAdd and (leap <= i and leap > 0) offset += leapMonthDays y isAdd = true offset += lunarMonthDays y, i # 转换闰月农历 需补充该年闰月的前一个月的时差 offset += day if isLeapMonth # 1900年农历正月一日的公历时间为1900年1月30日0时0分0秒(该时间也是本农历的最开始起始点) stmap = Date.UTC 1900,1,30,0,0,0 calObj = new Date (offset+d-31)*86400000+stmap solar2lunar calObj.getUTCFullYear(),calObj.getUTCMonth()+1,calObj.getUTCDate() @SuperCalendar = { lunar2solar: lunar2solar solar2lunar: solar2lunar leapMonth: leapMonth leapMonthDays: leapMonthDays lunarYearDays: lunarYearDays lunarMonthDays: lunarMonthDays solarDays: solarDays getSolarTerm: getSolarTerm getAnimal: getAnimal getAstronomy: getAstronomy } console.log @SuperCalendar.lunar2solar 2015,2,1 # console.log lunarYearDays 2015 # lunar2solar 2015,1,27
[ { "context": "\n\t\t\t@contacts = [\n\t\t\t\t{ _id: \"contact-1\", email: \"joe@example.com\", first_name: \"Joe\", last_name: \"Example\", unsued", "end": 1106, "score": 0.999920666217804, "start": 1091, "tag": "EMAIL", "value": "joe@example.com" }, { "context": "ontact-1\", email: ...
test/unit/coffee/Contact/ContactControllerTests.coffee
davidmehren/web-sharelatex
1
sinon = require('sinon') chai = require('chai') should = chai.should() assert = chai.assert expect = chai.expect modulePath = "../../../../app/js/Features/Contacts/ContactController.js" SandboxedModule = require('sandboxed-module') describe "ContactController", -> beforeEach -> @AuthenticationController = getLoggedInUserId: sinon.stub() @ContactController = SandboxedModule.require modulePath, requires: "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub() } "../User/UserGetter": @UserGetter = {} "./ContactManager": @ContactManager = {} "../Authentication/AuthenticationController": @AuthenticationController = {} "../../infrastructure/Modules": @Modules = { hooks: {} } '../Authentication/AuthenticationController': @AuthenticationController @next = sinon.stub() @req = {} @res = {} @res.status = sinon.stub().returns @req @res.send = sinon.stub() describe "getContacts", -> beforeEach -> @user_id = "mock-user-id" @contact_ids = ["contact-1", "contact-2", "contact-3"] @contacts = [ { _id: "contact-1", email: "joe@example.com", first_name: "Joe", last_name: "Example", unsued: "foo" } { _id: "contact-2", email: "jane@example.com", first_name: "Jane", last_name: "Example", unsued: "foo", holdingAccount: true } { _id: "contact-3", email: "jim@example.com", first_name: "Jim", last_name: "Example", unsued: "foo" } ] @AuthenticationController.getLoggedInUserId = sinon.stub().returns(@user_id) @ContactManager.getContactIds = sinon.stub().callsArgWith(2, null, @contact_ids) @UserGetter.getUsers = sinon.stub().callsArgWith(2, null, @contacts) @Modules.hooks.fire = sinon.stub().callsArg(3) @ContactController.getContacts @req, @res, @next it "should look up the logged in user id", -> @AuthenticationController.getLoggedInUserId .calledWith(@req) .should.equal true it "should get the users contact ids", -> @ContactManager.getContactIds .calledWith(@user_id, { limit: 50 }) .should.equal true it "should populate the users contacts ids", -> @UserGetter.getUsers .calledWith(@contact_ids, { email: 1, first_name: 1, last_name: 1, holdingAccount: 1 }) .should.equal true it "should fire the getContact module hook", -> @Modules.hooks.fire .calledWith("getContacts", @user_id) .should.equal true it "should return a formatted list of contacts in contact list order, without holding accounts", -> @res.send.args[0][0].contacts.should.deep.equal [ { id: "contact-1", email: "joe@example.com", first_name: "Joe", last_name: "Example", type: "user" } { id: "contact-3", email: "jim@example.com", first_name: "Jim", last_name: "Example", type: "user" } ]
71671
sinon = require('sinon') chai = require('chai') should = chai.should() assert = chai.assert expect = chai.expect modulePath = "../../../../app/js/Features/Contacts/ContactController.js" SandboxedModule = require('sandboxed-module') describe "ContactController", -> beforeEach -> @AuthenticationController = getLoggedInUserId: sinon.stub() @ContactController = SandboxedModule.require modulePath, requires: "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub() } "../User/UserGetter": @UserGetter = {} "./ContactManager": @ContactManager = {} "../Authentication/AuthenticationController": @AuthenticationController = {} "../../infrastructure/Modules": @Modules = { hooks: {} } '../Authentication/AuthenticationController': @AuthenticationController @next = sinon.stub() @req = {} @res = {} @res.status = sinon.stub().returns @req @res.send = sinon.stub() describe "getContacts", -> beforeEach -> @user_id = "mock-user-id" @contact_ids = ["contact-1", "contact-2", "contact-3"] @contacts = [ { _id: "contact-1", email: "<EMAIL>", first_name: "<NAME>", last_name: "Example", unsued: "foo" } { _id: "contact-2", email: "<EMAIL>", first_name: "<NAME>", last_name: "Example", unsued: "foo", holdingAccount: true } { _id: "contact-3", email: "<EMAIL>", first_name: "<NAME>", last_name: "Example", unsued: "foo" } ] @AuthenticationController.getLoggedInUserId = sinon.stub().returns(@user_id) @ContactManager.getContactIds = sinon.stub().callsArgWith(2, null, @contact_ids) @UserGetter.getUsers = sinon.stub().callsArgWith(2, null, @contacts) @Modules.hooks.fire = sinon.stub().callsArg(3) @ContactController.getContacts @req, @res, @next it "should look up the logged in user id", -> @AuthenticationController.getLoggedInUserId .calledWith(@req) .should.equal true it "should get the users contact ids", -> @ContactManager.getContactIds .calledWith(@user_id, { limit: 50 }) .should.equal true it "should populate the users contacts ids", -> @UserGetter.getUsers .calledWith(@contact_ids, { email: 1, first_name: 1, last_name: 1, holdingAccount: 1 }) .should.equal true it "should fire the getContact module hook", -> @Modules.hooks.fire .calledWith("getContacts", @user_id) .should.equal true it "should return a formatted list of contacts in contact list order, without holding accounts", -> @res.send.args[0][0].contacts.should.deep.equal [ { id: "contact-1", email: "<EMAIL>", first_name: "<NAME>", last_name: "<NAME>", type: "user" } { id: "contact-3", email: "<EMAIL>", first_name: "<NAME>", last_name: "<NAME>", type: "user" } ]
true
sinon = require('sinon') chai = require('chai') should = chai.should() assert = chai.assert expect = chai.expect modulePath = "../../../../app/js/Features/Contacts/ContactController.js" SandboxedModule = require('sandboxed-module') describe "ContactController", -> beforeEach -> @AuthenticationController = getLoggedInUserId: sinon.stub() @ContactController = SandboxedModule.require modulePath, requires: "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub() } "../User/UserGetter": @UserGetter = {} "./ContactManager": @ContactManager = {} "../Authentication/AuthenticationController": @AuthenticationController = {} "../../infrastructure/Modules": @Modules = { hooks: {} } '../Authentication/AuthenticationController': @AuthenticationController @next = sinon.stub() @req = {} @res = {} @res.status = sinon.stub().returns @req @res.send = sinon.stub() describe "getContacts", -> beforeEach -> @user_id = "mock-user-id" @contact_ids = ["contact-1", "contact-2", "contact-3"] @contacts = [ { _id: "contact-1", email: "PI:EMAIL:<EMAIL>END_PI", first_name: "PI:NAME:<NAME>END_PI", last_name: "Example", unsued: "foo" } { _id: "contact-2", email: "PI:EMAIL:<EMAIL>END_PI", first_name: "PI:NAME:<NAME>END_PI", last_name: "Example", unsued: "foo", holdingAccount: true } { _id: "contact-3", email: "PI:EMAIL:<EMAIL>END_PI", first_name: "PI:NAME:<NAME>END_PI", last_name: "Example", unsued: "foo" } ] @AuthenticationController.getLoggedInUserId = sinon.stub().returns(@user_id) @ContactManager.getContactIds = sinon.stub().callsArgWith(2, null, @contact_ids) @UserGetter.getUsers = sinon.stub().callsArgWith(2, null, @contacts) @Modules.hooks.fire = sinon.stub().callsArg(3) @ContactController.getContacts @req, @res, @next it "should look up the logged in user id", -> @AuthenticationController.getLoggedInUserId .calledWith(@req) .should.equal true it "should get the users contact ids", -> @ContactManager.getContactIds .calledWith(@user_id, { limit: 50 }) .should.equal true it "should populate the users contacts ids", -> @UserGetter.getUsers .calledWith(@contact_ids, { email: 1, first_name: 1, last_name: 1, holdingAccount: 1 }) .should.equal true it "should fire the getContact module hook", -> @Modules.hooks.fire .calledWith("getContacts", @user_id) .should.equal true it "should return a formatted list of contacts in contact list order, without holding accounts", -> @res.send.args[0][0].contacts.should.deep.equal [ { id: "contact-1", email: "PI:EMAIL:<EMAIL>END_PI", first_name: "PI:NAME:<NAME>END_PI", last_name: "PI:NAME:<NAME>END_PI", type: "user" } { id: "contact-3", email: "PI:EMAIL:<EMAIL>END_PI", first_name: "PI:NAME:<NAME>END_PI", last_name: "PI:NAME:<NAME>END_PI", type: "user" } ]
[ { "context": "orOpenMax = 3\n\n @balloons = null\n\n @keyId = 0\n @lockId = 0\n\n @distMax = 20\n @distMax *", "end": 305, "score": 0.5024864077568054, "start": 304, "tag": "KEY", "value": "0" } ]
project_code/prod/app/src/coffee/m11s/lockers/bodyitems.coffee
kikko/devart-template
6
class mk.m11s.lockers.BodyItems extends mk.m11s.base.BodyItems setupItems : () -> @flys = [] @locks = [] @addLockers() # delayed 1000, => @flyPile 2 # @doors = [] @door = null # @addDoor() @numDoorOpen = 0 @numDoorOpenMax = 3 @balloons = null @keyId = 0 @lockId = 0 @distMax = 20 @distMax *= @distMax @timeSinceKey = -4000 @timeBeforeNextKey = 0 # @pilesCanFly = false @MODE_NOTHING = -1 @MODE_PILE = 0 @MODE_DOORS = 1 @MODE_INSIDE = 2 @currMode = @MODE_NOTHING @setModePile() # @setModeInside() setOutdoorPelvisColor : -> color = mk.Scene::settings.getHexColor 'blue' parts = @getParts ['leftUpperLeg', 'rightUpperLeg', 'pelvis'] p.setColor color,false for p in parts onMusicEvent : (evId) -> switch evId # when 1 # @pilesCanFly = true when 3 delayed 10, => @currMode = @MODE_NOTHING if @piles while @piles.length @piles.shift().fly() delayed 7000, => @addDoor() @currMode = @MODE_DOORS # @onUnlock() # when 5 # @setModeInside() # @pilesCanFly = true # @flyInterval() # @scaleFactor = 0.1 # for pile in @piles # scaling = mk.m11s.lockers.Pile::SCALE_MAX_BEFORE_FLY # if pile.pile.scaling.x > scaling # @flyPile pile.type setModePile : -> @piles = [] @addPile type for type in [0...3] @currMode = @MODE_PILE setModeInside : -> @addDoor() if !@door @setOutdoorPelvisColor() @door.setupInside() @balloons = new mk.m11s.lockers.Balloons @joints[NiTE.LEFT_HAND], @joints[NiTE.RIGHT_HAND] @items.push @balloons @currMode = @MODE_INSIDE addDoor : -> @door = new mk.m11s.lockers.DoorOpen @joints[NiTE.HEAD], @doorAnimComplete @items.push @door doorAnimComplete : (d) => console.log 'anim complete' removeDoor : -> setTimeout => @items.splice @items.indexOf(d),1 d.clean() , 1 addLockers : -> parts = @getPartsExcluding ['head'] rngk = 'addLockers' for p in parts max = 3 if p.name is "torso" max = 6 for i in [1..max] type = rngi(rngk,0,2) lock = new mk.m11s.lockers.Lock type, p, 'Lockers'+@items.length @locks.push lock @items.push lock lock = new mk.m11s.lockers.Lock 0, @getPart('head'), 'Lockers'+@items.length @locks.push lock @items.push lock addKey : -> asset = null if @currMode is @MODE_INSIDE then asset = 'key2' key = new mk.m11s.lockers.Key @flys.length, asset @items.push key @flys.push key getBiggestPile : -> if !@piles.length then return null biggest = @piles[0] for p in @piles if p.pile.scaling.x > biggest.pile.scaling.x biggest = p return biggest addPile : (type) -> pile = new mk.m11s.lockers.Pile type pile.fullCallback = @pileFullCallback @items.push pile @piles.splice type, 0, pile pileFullCallback : (pile) => if @currMode is @MODE_PILE @flyPile pile.type flyPile : (type, add=true) -> # if !@pilesCanFly then return @piles[type].fly() @piles.splice type, 1 @addPile type if add flyInterval : => p = @getBiggestPile() if p @flyPile(p.type) delayed 4080, @flyInterval getKeyInLock : (fly) -> for lock in @locks if !lock.available then continue d = fly.view.position.getDistance lock.view.position, true if d < @distMax diff = lock.item.scaling.y-fly.view.scaling.y if diff < 0.8 and diff > -0.8 return lock return null onUnlock : (fly, lock) -> switch @currMode when @MODE_PILE @piles[lock.type].addSome() when @MODE_DOORS @numDoorOpen++ if @numDoorOpen > @numDoorOpenMax @setModeInside() else @door.popupAndShineYouBeautiful() when @MODE_INSIDE @balloons.addBalloon() # @door.addParticlesTime += 2000 update : (dt) -> super dt for i in [@flys.length-1..0] by -1 fly = @flys[i] lock = @getKeyInLock fly if lock fly.view.position = new paper.Point 0, -10 * lock.item.scaling.y lock.available = false do (fly, lock) => fly.turn => lock.breakFree() @onUnlock fly, lock if lock || fly.view.position.x > 500 fly.clean() @items.splice @items.indexOf(fly),1 @flys.splice i,1 if lock lock.view.addChild fly.view for i in [@locks.length-1..0] by -1 l = @locks[i] if l.out l.clean() @items.splice @items.indexOf(l),1 @locks.splice i,1 @timeSinceKey+=dt if @flys.length < 10 and @timeSinceKey > @timeBeforeNextKey @timeSinceKey -= @timeBeforeNextKey @timeBeforeNextKey = rng('LockersUpdate') * 3000 + 3000 @addKey()
15337
class mk.m11s.lockers.BodyItems extends mk.m11s.base.BodyItems setupItems : () -> @flys = [] @locks = [] @addLockers() # delayed 1000, => @flyPile 2 # @doors = [] @door = null # @addDoor() @numDoorOpen = 0 @numDoorOpenMax = 3 @balloons = null @keyId = <KEY> @lockId = 0 @distMax = 20 @distMax *= @distMax @timeSinceKey = -4000 @timeBeforeNextKey = 0 # @pilesCanFly = false @MODE_NOTHING = -1 @MODE_PILE = 0 @MODE_DOORS = 1 @MODE_INSIDE = 2 @currMode = @MODE_NOTHING @setModePile() # @setModeInside() setOutdoorPelvisColor : -> color = mk.Scene::settings.getHexColor 'blue' parts = @getParts ['leftUpperLeg', 'rightUpperLeg', 'pelvis'] p.setColor color,false for p in parts onMusicEvent : (evId) -> switch evId # when 1 # @pilesCanFly = true when 3 delayed 10, => @currMode = @MODE_NOTHING if @piles while @piles.length @piles.shift().fly() delayed 7000, => @addDoor() @currMode = @MODE_DOORS # @onUnlock() # when 5 # @setModeInside() # @pilesCanFly = true # @flyInterval() # @scaleFactor = 0.1 # for pile in @piles # scaling = mk.m11s.lockers.Pile::SCALE_MAX_BEFORE_FLY # if pile.pile.scaling.x > scaling # @flyPile pile.type setModePile : -> @piles = [] @addPile type for type in [0...3] @currMode = @MODE_PILE setModeInside : -> @addDoor() if !@door @setOutdoorPelvisColor() @door.setupInside() @balloons = new mk.m11s.lockers.Balloons @joints[NiTE.LEFT_HAND], @joints[NiTE.RIGHT_HAND] @items.push @balloons @currMode = @MODE_INSIDE addDoor : -> @door = new mk.m11s.lockers.DoorOpen @joints[NiTE.HEAD], @doorAnimComplete @items.push @door doorAnimComplete : (d) => console.log 'anim complete' removeDoor : -> setTimeout => @items.splice @items.indexOf(d),1 d.clean() , 1 addLockers : -> parts = @getPartsExcluding ['head'] rngk = 'addLockers' for p in parts max = 3 if p.name is "torso" max = 6 for i in [1..max] type = rngi(rngk,0,2) lock = new mk.m11s.lockers.Lock type, p, 'Lockers'+@items.length @locks.push lock @items.push lock lock = new mk.m11s.lockers.Lock 0, @getPart('head'), 'Lockers'+@items.length @locks.push lock @items.push lock addKey : -> asset = null if @currMode is @MODE_INSIDE then asset = 'key2' key = new mk.m11s.lockers.Key @flys.length, asset @items.push key @flys.push key getBiggestPile : -> if !@piles.length then return null biggest = @piles[0] for p in @piles if p.pile.scaling.x > biggest.pile.scaling.x biggest = p return biggest addPile : (type) -> pile = new mk.m11s.lockers.Pile type pile.fullCallback = @pileFullCallback @items.push pile @piles.splice type, 0, pile pileFullCallback : (pile) => if @currMode is @MODE_PILE @flyPile pile.type flyPile : (type, add=true) -> # if !@pilesCanFly then return @piles[type].fly() @piles.splice type, 1 @addPile type if add flyInterval : => p = @getBiggestPile() if p @flyPile(p.type) delayed 4080, @flyInterval getKeyInLock : (fly) -> for lock in @locks if !lock.available then continue d = fly.view.position.getDistance lock.view.position, true if d < @distMax diff = lock.item.scaling.y-fly.view.scaling.y if diff < 0.8 and diff > -0.8 return lock return null onUnlock : (fly, lock) -> switch @currMode when @MODE_PILE @piles[lock.type].addSome() when @MODE_DOORS @numDoorOpen++ if @numDoorOpen > @numDoorOpenMax @setModeInside() else @door.popupAndShineYouBeautiful() when @MODE_INSIDE @balloons.addBalloon() # @door.addParticlesTime += 2000 update : (dt) -> super dt for i in [@flys.length-1..0] by -1 fly = @flys[i] lock = @getKeyInLock fly if lock fly.view.position = new paper.Point 0, -10 * lock.item.scaling.y lock.available = false do (fly, lock) => fly.turn => lock.breakFree() @onUnlock fly, lock if lock || fly.view.position.x > 500 fly.clean() @items.splice @items.indexOf(fly),1 @flys.splice i,1 if lock lock.view.addChild fly.view for i in [@locks.length-1..0] by -1 l = @locks[i] if l.out l.clean() @items.splice @items.indexOf(l),1 @locks.splice i,1 @timeSinceKey+=dt if @flys.length < 10 and @timeSinceKey > @timeBeforeNextKey @timeSinceKey -= @timeBeforeNextKey @timeBeforeNextKey = rng('LockersUpdate') * 3000 + 3000 @addKey()
true
class mk.m11s.lockers.BodyItems extends mk.m11s.base.BodyItems setupItems : () -> @flys = [] @locks = [] @addLockers() # delayed 1000, => @flyPile 2 # @doors = [] @door = null # @addDoor() @numDoorOpen = 0 @numDoorOpenMax = 3 @balloons = null @keyId = PI:KEY:<KEY>END_PI @lockId = 0 @distMax = 20 @distMax *= @distMax @timeSinceKey = -4000 @timeBeforeNextKey = 0 # @pilesCanFly = false @MODE_NOTHING = -1 @MODE_PILE = 0 @MODE_DOORS = 1 @MODE_INSIDE = 2 @currMode = @MODE_NOTHING @setModePile() # @setModeInside() setOutdoorPelvisColor : -> color = mk.Scene::settings.getHexColor 'blue' parts = @getParts ['leftUpperLeg', 'rightUpperLeg', 'pelvis'] p.setColor color,false for p in parts onMusicEvent : (evId) -> switch evId # when 1 # @pilesCanFly = true when 3 delayed 10, => @currMode = @MODE_NOTHING if @piles while @piles.length @piles.shift().fly() delayed 7000, => @addDoor() @currMode = @MODE_DOORS # @onUnlock() # when 5 # @setModeInside() # @pilesCanFly = true # @flyInterval() # @scaleFactor = 0.1 # for pile in @piles # scaling = mk.m11s.lockers.Pile::SCALE_MAX_BEFORE_FLY # if pile.pile.scaling.x > scaling # @flyPile pile.type setModePile : -> @piles = [] @addPile type for type in [0...3] @currMode = @MODE_PILE setModeInside : -> @addDoor() if !@door @setOutdoorPelvisColor() @door.setupInside() @balloons = new mk.m11s.lockers.Balloons @joints[NiTE.LEFT_HAND], @joints[NiTE.RIGHT_HAND] @items.push @balloons @currMode = @MODE_INSIDE addDoor : -> @door = new mk.m11s.lockers.DoorOpen @joints[NiTE.HEAD], @doorAnimComplete @items.push @door doorAnimComplete : (d) => console.log 'anim complete' removeDoor : -> setTimeout => @items.splice @items.indexOf(d),1 d.clean() , 1 addLockers : -> parts = @getPartsExcluding ['head'] rngk = 'addLockers' for p in parts max = 3 if p.name is "torso" max = 6 for i in [1..max] type = rngi(rngk,0,2) lock = new mk.m11s.lockers.Lock type, p, 'Lockers'+@items.length @locks.push lock @items.push lock lock = new mk.m11s.lockers.Lock 0, @getPart('head'), 'Lockers'+@items.length @locks.push lock @items.push lock addKey : -> asset = null if @currMode is @MODE_INSIDE then asset = 'key2' key = new mk.m11s.lockers.Key @flys.length, asset @items.push key @flys.push key getBiggestPile : -> if !@piles.length then return null biggest = @piles[0] for p in @piles if p.pile.scaling.x > biggest.pile.scaling.x biggest = p return biggest addPile : (type) -> pile = new mk.m11s.lockers.Pile type pile.fullCallback = @pileFullCallback @items.push pile @piles.splice type, 0, pile pileFullCallback : (pile) => if @currMode is @MODE_PILE @flyPile pile.type flyPile : (type, add=true) -> # if !@pilesCanFly then return @piles[type].fly() @piles.splice type, 1 @addPile type if add flyInterval : => p = @getBiggestPile() if p @flyPile(p.type) delayed 4080, @flyInterval getKeyInLock : (fly) -> for lock in @locks if !lock.available then continue d = fly.view.position.getDistance lock.view.position, true if d < @distMax diff = lock.item.scaling.y-fly.view.scaling.y if diff < 0.8 and diff > -0.8 return lock return null onUnlock : (fly, lock) -> switch @currMode when @MODE_PILE @piles[lock.type].addSome() when @MODE_DOORS @numDoorOpen++ if @numDoorOpen > @numDoorOpenMax @setModeInside() else @door.popupAndShineYouBeautiful() when @MODE_INSIDE @balloons.addBalloon() # @door.addParticlesTime += 2000 update : (dt) -> super dt for i in [@flys.length-1..0] by -1 fly = @flys[i] lock = @getKeyInLock fly if lock fly.view.position = new paper.Point 0, -10 * lock.item.scaling.y lock.available = false do (fly, lock) => fly.turn => lock.breakFree() @onUnlock fly, lock if lock || fly.view.position.x > 500 fly.clean() @items.splice @items.indexOf(fly),1 @flys.splice i,1 if lock lock.view.addChild fly.view for i in [@locks.length-1..0] by -1 l = @locks[i] if l.out l.clean() @items.splice @items.indexOf(l),1 @locks.splice i,1 @timeSinceKey+=dt if @flys.length < 10 and @timeSinceKey > @timeBeforeNextKey @timeSinceKey -= @timeBeforeNextKey @timeBeforeNextKey = rng('LockersUpdate') * 3000 + 3000 @addKey()
[ { "context": "ch file to show.\n#\n# Requires jQuery.\n#\n# Based on Mark Selby's async-gists.js:\n# https://gist.github.com/marks", "end": 124, "score": 0.9997510313987732, "start": 114, "tag": "NAME", "value": "Mark Selby" }, { "context": "Selby's async-gists.js:\n# https://gist.gi...
javascripts/main.coffee
razor-x/gist-async
6
# Load GitHub Gists asynchronously # and optionally specify which file to show. # # Requires jQuery. # # Based on Mark Selby's async-gists.js: # https://gist.github.com/markselby/7209751 # # This version by Evan Sosenko. # # Source, license, and usage instructions: # https://github.com/razor-x/gist-async # 'use strict' this.gistAsync = -> $ = jQuery $ -> GIST_HOST = 'https://gist.github.com' elements = $('div[data-gist]') gists = {} code = [] stylesheets = [] # The asynchronous asset loader function. loader = (url) -> link = document.createElement 'link' link.type = 'text/css' link.rel = 'stylesheet' link.href = url document.getElementsByTagName('head')[0].appendChild link return elements.addClass('loading') # Get elements referencing a gist # and build a gists hash referencing # the elements that use it. elements.each (index, element) -> element = $(element) gist = element.data 'gist' gists[gist] ?= targets: [] gists[gist].targets.push element # Load the gists. $.each gists, (id, data) -> $.getJSON "#{GIST_HOST}/#{id}.json?callback=?", (data) -> gist = gists[id] gist.data = data # Only insert the stylesheets once. stylesheet = gist.data.stylesheet if stylesheets.indexOf(stylesheet) < 0 stylesheets.push stylesheet loader(stylesheet) div = gist.data.div gist.files = $(div).find('.gist-file') gist.outer = $(div).first().html('') # Iterate elements refering to this gist. $(gist.targets).each (index, target) -> file = target.data 'gist-file' if file outer = gist.outer.clone() inner = "<div class=\"gist-file\">" \ + $(gist.files.get(gist.data.files.indexOf(file))).html() \ + "</div>" outer.html inner else outer = $(div) outer.hide() target.fadeOut 'fast', -> $(this).replaceWith(outer) outer.fadeIn()
206815
# Load GitHub Gists asynchronously # and optionally specify which file to show. # # Requires jQuery. # # Based on <NAME>'s async-gists.js: # https://gist.github.com/markselby/7209751 # # This version by <NAME>. # # Source, license, and usage instructions: # https://github.com/razor-x/gist-async # 'use strict' this.gistAsync = -> $ = jQuery $ -> GIST_HOST = 'https://gist.github.com' elements = $('div[data-gist]') gists = {} code = [] stylesheets = [] # The asynchronous asset loader function. loader = (url) -> link = document.createElement 'link' link.type = 'text/css' link.rel = 'stylesheet' link.href = url document.getElementsByTagName('head')[0].appendChild link return elements.addClass('loading') # Get elements referencing a gist # and build a gists hash referencing # the elements that use it. elements.each (index, element) -> element = $(element) gist = element.data 'gist' gists[gist] ?= targets: [] gists[gist].targets.push element # Load the gists. $.each gists, (id, data) -> $.getJSON "#{GIST_HOST}/#{id}.json?callback=?", (data) -> gist = gists[id] gist.data = data # Only insert the stylesheets once. stylesheet = gist.data.stylesheet if stylesheets.indexOf(stylesheet) < 0 stylesheets.push stylesheet loader(stylesheet) div = gist.data.div gist.files = $(div).find('.gist-file') gist.outer = $(div).first().html('') # Iterate elements refering to this gist. $(gist.targets).each (index, target) -> file = target.data 'gist-file' if file outer = gist.outer.clone() inner = "<div class=\"gist-file\">" \ + $(gist.files.get(gist.data.files.indexOf(file))).html() \ + "</div>" outer.html inner else outer = $(div) outer.hide() target.fadeOut 'fast', -> $(this).replaceWith(outer) outer.fadeIn()
true
# Load GitHub Gists asynchronously # and optionally specify which file to show. # # Requires jQuery. # # Based on PI:NAME:<NAME>END_PI's async-gists.js: # https://gist.github.com/markselby/7209751 # # This version by PI:NAME:<NAME>END_PI. # # Source, license, and usage instructions: # https://github.com/razor-x/gist-async # 'use strict' this.gistAsync = -> $ = jQuery $ -> GIST_HOST = 'https://gist.github.com' elements = $('div[data-gist]') gists = {} code = [] stylesheets = [] # The asynchronous asset loader function. loader = (url) -> link = document.createElement 'link' link.type = 'text/css' link.rel = 'stylesheet' link.href = url document.getElementsByTagName('head')[0].appendChild link return elements.addClass('loading') # Get elements referencing a gist # and build a gists hash referencing # the elements that use it. elements.each (index, element) -> element = $(element) gist = element.data 'gist' gists[gist] ?= targets: [] gists[gist].targets.push element # Load the gists. $.each gists, (id, data) -> $.getJSON "#{GIST_HOST}/#{id}.json?callback=?", (data) -> gist = gists[id] gist.data = data # Only insert the stylesheets once. stylesheet = gist.data.stylesheet if stylesheets.indexOf(stylesheet) < 0 stylesheets.push stylesheet loader(stylesheet) div = gist.data.div gist.files = $(div).find('.gist-file') gist.outer = $(div).first().html('') # Iterate elements refering to this gist. $(gist.targets).each (index, target) -> file = target.data 'gist-file' if file outer = gist.outer.clone() inner = "<div class=\"gist-file\">" \ + $(gist.files.get(gist.data.files.indexOf(file))).html() \ + "</div>" outer.html inner else outer = $(div) outer.hide() target.fadeOut 'fast', -> $(this).replaceWith(outer) outer.fadeIn()
[ { "context": ": 'nofish'\n meta name: 'author', content: '简聊'\n meta name: 'description', content: '简聊是一", "end": 1298, "score": 0.6244077086448669, "start": 1296, "tag": "NAME", "value": "简聊" } ]
talk-web/entry/template.coffee
ikingye/talk-os
3,084
fs = require 'fs' stir = require 'stir-template' React = require 'react' ReactDOMServer = require 'react-dom/server' recorder = require 'actions-recorder' Immutable = require 'immutable' ContainerWireframe = React.createFactory require '../client/app/container-wireframe' schema = require '../client/schema' baidu = fs.readFileSync 'entry/baidu.html' mixpanel = fs.readFileSync 'entry/mixpanel.html' googleAnalytics = fs.readFileSync 'entry/google-analytics.html' cssLoading = fs.readFileSync 'entry/loading.css' triggerLoading = fs.readFileSync 'entry/triggerLoading.js' {html, head, title, body, script, meta, link, div} = stir style = stir.createFactory 'style' module.exports = (assets, config) -> initialStore = schema.database.set 'config', Immutable.fromJS(config) recorder.setup initial: initialStore updater: (x) -> x # updater is not called in rendering template inProduction: false store = recorder.getStore() stir.render stir.doctype(), html null, head null, title null, '简聊' meta charset: 'utf-8' meta 'http-equiv': 'X-UA-Compatible', content: 'IE=edge, chrome=1' meta name: 'referrer', content: 'origin-when-cross-origin' meta name: 'superfish', content: 'nofish' meta name: 'author', content: '简聊' meta name: 'description', content: '简聊是一个团队协作即时通讯工具, 拥有多种消息文本类型, 话题, 内容分享, 搜索, 文件整理以及一系列精彩的功能. 我们希望你的团队能通过简聊变得更有效率' meta name: 'keywords', content: '分享, 工作, 沟通, 话题, 即使通讯, 团队协作, 效率' meta name: 'apple-itunes-app', content: 'app-id=922425179' meta property: 'og:description', content: '简聊是一个团队协作即时通讯工具, 拥有多种消息文本类型, 话题, 内容分享, 搜索, 文件整理以及一系列精彩的功能. 我们希望你的团队能通过简聊变得更有效率' meta property: 'og:image', content: 'https://dn-talk.oss.aliyuncs.com/icons/preview.png' meta property: 'og:site_name', content: '简聊' meta property: 'og:title', content: '简聊 | 谈工作,用简聊' meta property: 'og:type', content: 'website' meta property: 'og:url', content: 'https://jianliao.com' link rel: 'shortcut icon', type: 'image/x-icon', href: '/favicon.ico' if assets.style? link rel: 'stylesheet', type: 'text/css', href: assets.style style null, cssLoading body null, div class: 'app', ReactDOMServer.renderToStaticMarkup ContainerWireframe(sentence: '') script null, "window._initialStore = (#{JSON.stringify(store)});" script null, triggerLoading googleAnalytics if config.useAnalytics mixpanel if config.useAnalytics baidu if config.useAnalytics script crossorigin:"anonymous", src: assets.vendor script crossorigin:"anonymous", src: assets.main
218486
fs = require 'fs' stir = require 'stir-template' React = require 'react' ReactDOMServer = require 'react-dom/server' recorder = require 'actions-recorder' Immutable = require 'immutable' ContainerWireframe = React.createFactory require '../client/app/container-wireframe' schema = require '../client/schema' baidu = fs.readFileSync 'entry/baidu.html' mixpanel = fs.readFileSync 'entry/mixpanel.html' googleAnalytics = fs.readFileSync 'entry/google-analytics.html' cssLoading = fs.readFileSync 'entry/loading.css' triggerLoading = fs.readFileSync 'entry/triggerLoading.js' {html, head, title, body, script, meta, link, div} = stir style = stir.createFactory 'style' module.exports = (assets, config) -> initialStore = schema.database.set 'config', Immutable.fromJS(config) recorder.setup initial: initialStore updater: (x) -> x # updater is not called in rendering template inProduction: false store = recorder.getStore() stir.render stir.doctype(), html null, head null, title null, '简聊' meta charset: 'utf-8' meta 'http-equiv': 'X-UA-Compatible', content: 'IE=edge, chrome=1' meta name: 'referrer', content: 'origin-when-cross-origin' meta name: 'superfish', content: 'nofish' meta name: 'author', content: '<NAME>' meta name: 'description', content: '简聊是一个团队协作即时通讯工具, 拥有多种消息文本类型, 话题, 内容分享, 搜索, 文件整理以及一系列精彩的功能. 我们希望你的团队能通过简聊变得更有效率' meta name: 'keywords', content: '分享, 工作, 沟通, 话题, 即使通讯, 团队协作, 效率' meta name: 'apple-itunes-app', content: 'app-id=922425179' meta property: 'og:description', content: '简聊是一个团队协作即时通讯工具, 拥有多种消息文本类型, 话题, 内容分享, 搜索, 文件整理以及一系列精彩的功能. 我们希望你的团队能通过简聊变得更有效率' meta property: 'og:image', content: 'https://dn-talk.oss.aliyuncs.com/icons/preview.png' meta property: 'og:site_name', content: '简聊' meta property: 'og:title', content: '简聊 | 谈工作,用简聊' meta property: 'og:type', content: 'website' meta property: 'og:url', content: 'https://jianliao.com' link rel: 'shortcut icon', type: 'image/x-icon', href: '/favicon.ico' if assets.style? link rel: 'stylesheet', type: 'text/css', href: assets.style style null, cssLoading body null, div class: 'app', ReactDOMServer.renderToStaticMarkup ContainerWireframe(sentence: '') script null, "window._initialStore = (#{JSON.stringify(store)});" script null, triggerLoading googleAnalytics if config.useAnalytics mixpanel if config.useAnalytics baidu if config.useAnalytics script crossorigin:"anonymous", src: assets.vendor script crossorigin:"anonymous", src: assets.main
true
fs = require 'fs' stir = require 'stir-template' React = require 'react' ReactDOMServer = require 'react-dom/server' recorder = require 'actions-recorder' Immutable = require 'immutable' ContainerWireframe = React.createFactory require '../client/app/container-wireframe' schema = require '../client/schema' baidu = fs.readFileSync 'entry/baidu.html' mixpanel = fs.readFileSync 'entry/mixpanel.html' googleAnalytics = fs.readFileSync 'entry/google-analytics.html' cssLoading = fs.readFileSync 'entry/loading.css' triggerLoading = fs.readFileSync 'entry/triggerLoading.js' {html, head, title, body, script, meta, link, div} = stir style = stir.createFactory 'style' module.exports = (assets, config) -> initialStore = schema.database.set 'config', Immutable.fromJS(config) recorder.setup initial: initialStore updater: (x) -> x # updater is not called in rendering template inProduction: false store = recorder.getStore() stir.render stir.doctype(), html null, head null, title null, '简聊' meta charset: 'utf-8' meta 'http-equiv': 'X-UA-Compatible', content: 'IE=edge, chrome=1' meta name: 'referrer', content: 'origin-when-cross-origin' meta name: 'superfish', content: 'nofish' meta name: 'author', content: 'PI:NAME:<NAME>END_PI' meta name: 'description', content: '简聊是一个团队协作即时通讯工具, 拥有多种消息文本类型, 话题, 内容分享, 搜索, 文件整理以及一系列精彩的功能. 我们希望你的团队能通过简聊变得更有效率' meta name: 'keywords', content: '分享, 工作, 沟通, 话题, 即使通讯, 团队协作, 效率' meta name: 'apple-itunes-app', content: 'app-id=922425179' meta property: 'og:description', content: '简聊是一个团队协作即时通讯工具, 拥有多种消息文本类型, 话题, 内容分享, 搜索, 文件整理以及一系列精彩的功能. 我们希望你的团队能通过简聊变得更有效率' meta property: 'og:image', content: 'https://dn-talk.oss.aliyuncs.com/icons/preview.png' meta property: 'og:site_name', content: '简聊' meta property: 'og:title', content: '简聊 | 谈工作,用简聊' meta property: 'og:type', content: 'website' meta property: 'og:url', content: 'https://jianliao.com' link rel: 'shortcut icon', type: 'image/x-icon', href: '/favicon.ico' if assets.style? link rel: 'stylesheet', type: 'text/css', href: assets.style style null, cssLoading body null, div class: 'app', ReactDOMServer.renderToStaticMarkup ContainerWireframe(sentence: '') script null, "window._initialStore = (#{JSON.stringify(store)});" script null, triggerLoading googleAnalytics if config.useAnalytics mixpanel if config.useAnalytics baidu if config.useAnalytics script crossorigin:"anonymous", src: assets.vendor script crossorigin:"anonymous", src: assets.main
[ { "context": "###\n@author Pirhoo\n@description Home route binder\n###\nmodule.exports", "end": 18, "score": 0.9997470378875732, "start": 12, "tag": "NAME", "value": "Pirhoo" } ]
controllers/404.coffee
jplusplus/v1.jplusplus.org
0
### @author Pirhoo @description Home route binder ### module.exports = (app, db, controllers) -> # GET home page. app.get "/404", (req, res) -> res.render "404.jade", title: "404 - Journalism++"
50179
### @author <NAME> @description Home route binder ### module.exports = (app, db, controllers) -> # GET home page. app.get "/404", (req, res) -> res.render "404.jade", title: "404 - Journalism++"
true
### @author PI:NAME:<NAME>END_PI @description Home route binder ### module.exports = (app, db, controllers) -> # GET home page. app.get "/404", (req, res) -> res.render "404.jade", title: "404 - Journalism++"
[ { "context": "om'\nhttp = require 'http'\n{filter} = require 'fuzzaldrin'\nCP = require 'child_process'\nfs = require 'fs'\n\n", "end": 103, "score": 0.6586617827415466, "start": 97, "tag": "USERNAME", "value": "aldrin" }, { "context": " candidates = json.map (c) ->\n c.searc...
lib/zotero-bibtex-autocomplete.coffee
lierdakil/atom-zotero-bibtex-autocomplete
1
{Range,Point,CompositeDisposable} = require 'atom' http = require 'http' {filter} = require 'fuzzaldrin' CP = require 'child_process' fs = require 'fs' module.exports = ZoteroBibtexAutocomplete = activate: (state) -> autocompleteProvider: () -> selector: '.source.gfm' getSuggestions: ({editor, bufferPosition}) => filePath=editor.getBuffer().getPath() rng = editor.bufferRangeForBufferRow bufferPosition.row rng=new Range rng.start, bufferPosition txt = editor.getTextInRange(rng) match = txt.match /@([^@\];,]+)$/ prefix = match?[1] return [] if not prefix? or prefix?.length<2 url=null editor.scanInBufferRange /^bibliography:\s*(https?:\/\/.*)$/m, editor.getBuffer().getRange(), ({match}) -> url=match[1] url = 'http://localhost:23119/better-bibtex/library?library.betterbiblatex' new Promise (resolve) => http.get(url, (res) => str = '' res.on 'data', (chunk) -> str += chunk.toString() res.on 'end', => fs.writeFile '/tmp/biblio.bib', str, => CP.exec 'pandoc-citeproc -j /tmp/biblio.bib', {encoding: 'utf-8'}, (e, sto, ste) => console.warn ste resolve @getBibSuggestions sto, prefix ).on('error', (e) -> console.log("Got error: " + e.message) resolve [] ).end() dispose: -> # Your dispose logic here getBibSuggestions: (str, prefix) -> json=JSON.parse(str) candidates = json.map (c) -> c.searchKey="#{c.id}: #{c.title}" for a,v of c.entryTags c.searchKey+=' '+v if v? and a in ['author','title','date'] c s=filter candidates, prefix, key:'searchKey' return s.map (c) -> text: '@'+c.id replacementPrefix: '@'+prefix description: c.title deactivate: ->
106299
{Range,Point,CompositeDisposable} = require 'atom' http = require 'http' {filter} = require 'fuzzaldrin' CP = require 'child_process' fs = require 'fs' module.exports = ZoteroBibtexAutocomplete = activate: (state) -> autocompleteProvider: () -> selector: '.source.gfm' getSuggestions: ({editor, bufferPosition}) => filePath=editor.getBuffer().getPath() rng = editor.bufferRangeForBufferRow bufferPosition.row rng=new Range rng.start, bufferPosition txt = editor.getTextInRange(rng) match = txt.match /@([^@\];,]+)$/ prefix = match?[1] return [] if not prefix? or prefix?.length<2 url=null editor.scanInBufferRange /^bibliography:\s*(https?:\/\/.*)$/m, editor.getBuffer().getRange(), ({match}) -> url=match[1] url = 'http://localhost:23119/better-bibtex/library?library.betterbiblatex' new Promise (resolve) => http.get(url, (res) => str = '' res.on 'data', (chunk) -> str += chunk.toString() res.on 'end', => fs.writeFile '/tmp/biblio.bib', str, => CP.exec 'pandoc-citeproc -j /tmp/biblio.bib', {encoding: 'utf-8'}, (e, sto, ste) => console.warn ste resolve @getBibSuggestions sto, prefix ).on('error', (e) -> console.log("Got error: " + e.message) resolve [] ).end() dispose: -> # Your dispose logic here getBibSuggestions: (str, prefix) -> json=JSON.parse(str) candidates = json.map (c) -> c.searchKey="<KEY> for a,v of c.entryTags c.searchKey+=' '+v if v? and a in ['author','title','date'] c s=filter candidates, prefix, key:'searchKey' return s.map (c) -> text: '@'+c.id replacementPrefix: '@'+prefix description: c.title deactivate: ->
true
{Range,Point,CompositeDisposable} = require 'atom' http = require 'http' {filter} = require 'fuzzaldrin' CP = require 'child_process' fs = require 'fs' module.exports = ZoteroBibtexAutocomplete = activate: (state) -> autocompleteProvider: () -> selector: '.source.gfm' getSuggestions: ({editor, bufferPosition}) => filePath=editor.getBuffer().getPath() rng = editor.bufferRangeForBufferRow bufferPosition.row rng=new Range rng.start, bufferPosition txt = editor.getTextInRange(rng) match = txt.match /@([^@\];,]+)$/ prefix = match?[1] return [] if not prefix? or prefix?.length<2 url=null editor.scanInBufferRange /^bibliography:\s*(https?:\/\/.*)$/m, editor.getBuffer().getRange(), ({match}) -> url=match[1] url = 'http://localhost:23119/better-bibtex/library?library.betterbiblatex' new Promise (resolve) => http.get(url, (res) => str = '' res.on 'data', (chunk) -> str += chunk.toString() res.on 'end', => fs.writeFile '/tmp/biblio.bib', str, => CP.exec 'pandoc-citeproc -j /tmp/biblio.bib', {encoding: 'utf-8'}, (e, sto, ste) => console.warn ste resolve @getBibSuggestions sto, prefix ).on('error', (e) -> console.log("Got error: " + e.message) resolve [] ).end() dispose: -> # Your dispose logic here getBibSuggestions: (str, prefix) -> json=JSON.parse(str) candidates = json.map (c) -> c.searchKey="PI:KEY:<KEY>END_PI for a,v of c.entryTags c.searchKey+=' '+v if v? and a in ['author','title','date'] c s=filter candidates, prefix, key:'searchKey' return s.map (c) -> text: '@'+c.id replacementPrefix: '@'+prefix description: c.title deactivate: ->
[ { "context": "'./images/body-1-1.jpg',\n englishCaption: 'Musée du Louvre',\n caption:\n simplified: '卢浮宫',\n ", "end": 218, "score": 0.9817621111869812, "start": 203, "tag": "NAME", "value": "Musée du Louvre" } ]
components/body/data.coffee
artsy/continuum
1
module.exports = artWorld: sectionTitle: { simplified: '艺术品在线', traditional: '藝術品在線' }, carousel: [ { image_url: './images/body-1-1.jpg', englishCaption: 'Musée du Louvre', caption: simplified: '卢浮宫', traditional: '盧浮宮' }, { image_url: './images/body-1-2.jpg', englishCaption: 'Los Angeles Modern Auctions', caption: simplified: '拍卖行', traditional: '拍賣行' }, { image_url: './images/body-1-3.jpg', englishCaption: 'Pearl Lam', caption: simplified: '艺术门', traditional: '藝術門' }, { image_url: "./images/body-1-4.jpg", englishCaption: 'The Armory Show', caption: simplified: '博览会', traditional: '博覽會' } ], artWorldBody: { simplified: 'Artsy 拥有全世界最领先的画廊、博物馆、基金会、艺术品展览与拍卖的综合资源。我们的藏品数据库涵盖全球4万多位艺术家的作品, 28万多幅美术、建筑与生活艺术品佳作,横跨古代、现代与当代艺术风格。当代艺术的网上藏品数量尤为丰富,居全球之首。无论是资深收藏家和学者,还是艺术赞助人、博物馆爱好者或学生,都可以通过 Artsy 发掘艺术的价值,找到真正打动心灵的艺术作品。', traditional: 'Artsy 擁有全世界最領先的畫廊、博物館、基金會、藝術品展覽與拍賣的綜合資源。我們的藏品資料庫涵蓋全球4萬多位藝術家的作品, 28萬多幅美術、建築與生活藝術品佳作,橫跨古代、現代與當代藝術風格。當代藝術的網上藏品數量尤為豐富,居全球之首。無論是資深收藏家和學者,還是藝術贊助者、博物館愛好者或學生,都可以通過 Artsy 發掘藝術的價值,找到真正打動心靈的藝術作品' } collecting: collectingTitle: { simplified: '在 Artsy 寻宝', traditional: '在 Artsy 尋寶' }, text: { simplified: '在 Artsy 可购买的艺术品多达16万件,均为全球顶尖画廊、公益以及商业竞拍之精品。每日有新艺术品上线,价格从100美元到100万美元不等。买家可以通过 Artsy 免费与画廊建立联系,参与竞拍或直接购买心仪的作品。', traditional: '在 Artsy 可購買的藝術品多達16萬件,均為全球頂尖畫廊、公益以及商業競拍之精品。每日有新藝術品上線,價格從100美元到100萬美元不等。買家可以通過 Artsy 免費與畫廊建立聯繫,參與競拍或直接購買心儀的作品。' } genome: genomeTitle: { simplified: '艺术基因测序 (The Art Genome Project)', traditional: '藝術基因測序 (The Art Genome Project)' }, text: { simplified: '艺术基因测序是 Artsy 特有的艺术品评级系统和技术架构,是 Artsy 的核心价值所在。它分析出每一件艺术品的“独特基因” (“genes”),用以追溯艺术家与艺术作品在历史上的纵横关系。现在我们已分析出1000多种基于历史进程、创作主旨和作品质量的“基因”。', traditional: '藝術基因測序是 Artsy 特有的藝術品分類系統和技術架構,是 Artsy 的核心價值所在。它分析出每一件藝術品的“獨特基因” (“genes”),用以追溯藝術家與藝術作品在歷史上的縱橫關係。現在我們已分析出1000多種基於歷史進程、創作主旨和作品質量的“基因”。' }, ios: iosTitle: { simplified: 'Artsy 与 iOS', traditional: 'Artsy 與 iOS' }, text: { simplified: '通过 Artsy 的 iPhone 与 iPad App,您可以随时随地接入我们庞大的数据库,在线上浏览、收藏、研究和购买艺术品,并在参观线下博览会时定制随身向导。扫描本页下方二维条码,即可在 App Store 中下载本 App。', traditional: '通過 Artsy 的 iPhone 與 iPad App,您可以隨時隨地接入我們龐大的資料庫,在線上瀏覽、收藏、研究和購買藝術品,並在參觀博覽會時訂製隨身嚮導。掃描本頁下方二維條碼,即可在 App Store 中下載本 App。' }, link: { simplified: '下载 App', traditional: '下載 App' } partnership: partnershipTitle: { simplified: '成为 Artsy 的合作伙伴', traditional: '成為 Artsy 的合作夥伴' }, gallery: subTitle: { simplified: '画廊' traditional: '畫廊' }, text: { simplified: 'Artsy 为画廊提供面向全球观众、艺术爱好者和收藏家的网络平台枢纽。在推广宣传画廊作品的基础上,Artsy 平台还可以提供馆藏管理与运营的后台支持,包括在云端的线上展品管理以及 iOS 系统下的管理软件。Artsy 的合作伙伴仅限于收到邀请的画廊,合作方每月缴纳会员费用。', traditional: 'Artsy 為畫廊提供面向全球觀眾、藝術愛好者和收藏家的網路平台樞紐。在推廣宣傳畫廊作品的基礎上,Artsy 平台更提供館藏管理與營運的後台系統,包括雲端的線上展品管理以及 iOS 系統下的管理軟體。 Artsy 的合作夥伴僅限於收到邀請的畫廊,合作方每月繳納會員費用。' }, link: { simplified: '了解更多', traditional: '了解更多' }, institution: subTitle: { simplified: '基金会与博物馆', traditional: '基金會與博物館' }, text: { simplified: '基金会与博物馆可以在 Artsy 平台上推广展览、馆藏以及其他活动,通过 Artsy 的网上交易平台出售限量版艺术品。', traditional: '基金會與博物館可以在 Ar​​tsy 平台上推廣展覽、館藏以及其他活動,通過 Artsy 的線上交易平台出售限量版藝術品。' }, link: { simplified: '了解更多', traditional: '了解更多' }, auction: subTitle: { simplified: '拍卖行', traditional: '拍賣行' }, text: { simplified: 'Artsy 愿与公益拍卖和商业拍卖行进行合作。' traditional: 'Artsy 願與公益拍賣和商業拍賣行進行合作。' }, link: { simplified: '了解更多', traditional: '申請加盟' }
197475
module.exports = artWorld: sectionTitle: { simplified: '艺术品在线', traditional: '藝術品在線' }, carousel: [ { image_url: './images/body-1-1.jpg', englishCaption: '<NAME>', caption: simplified: '卢浮宫', traditional: '盧浮宮' }, { image_url: './images/body-1-2.jpg', englishCaption: 'Los Angeles Modern Auctions', caption: simplified: '拍卖行', traditional: '拍賣行' }, { image_url: './images/body-1-3.jpg', englishCaption: 'Pearl Lam', caption: simplified: '艺术门', traditional: '藝術門' }, { image_url: "./images/body-1-4.jpg", englishCaption: 'The Armory Show', caption: simplified: '博览会', traditional: '博覽會' } ], artWorldBody: { simplified: 'Artsy 拥有全世界最领先的画廊、博物馆、基金会、艺术品展览与拍卖的综合资源。我们的藏品数据库涵盖全球4万多位艺术家的作品, 28万多幅美术、建筑与生活艺术品佳作,横跨古代、现代与当代艺术风格。当代艺术的网上藏品数量尤为丰富,居全球之首。无论是资深收藏家和学者,还是艺术赞助人、博物馆爱好者或学生,都可以通过 Artsy 发掘艺术的价值,找到真正打动心灵的艺术作品。', traditional: 'Artsy 擁有全世界最領先的畫廊、博物館、基金會、藝術品展覽與拍賣的綜合資源。我們的藏品資料庫涵蓋全球4萬多位藝術家的作品, 28萬多幅美術、建築與生活藝術品佳作,橫跨古代、現代與當代藝術風格。當代藝術的網上藏品數量尤為豐富,居全球之首。無論是資深收藏家和學者,還是藝術贊助者、博物館愛好者或學生,都可以通過 Artsy 發掘藝術的價值,找到真正打動心靈的藝術作品' } collecting: collectingTitle: { simplified: '在 Artsy 寻宝', traditional: '在 Artsy 尋寶' }, text: { simplified: '在 Artsy 可购买的艺术品多达16万件,均为全球顶尖画廊、公益以及商业竞拍之精品。每日有新艺术品上线,价格从100美元到100万美元不等。买家可以通过 Artsy 免费与画廊建立联系,参与竞拍或直接购买心仪的作品。', traditional: '在 Artsy 可購買的藝術品多達16萬件,均為全球頂尖畫廊、公益以及商業競拍之精品。每日有新藝術品上線,價格從100美元到100萬美元不等。買家可以通過 Artsy 免費與畫廊建立聯繫,參與競拍或直接購買心儀的作品。' } genome: genomeTitle: { simplified: '艺术基因测序 (The Art Genome Project)', traditional: '藝術基因測序 (The Art Genome Project)' }, text: { simplified: '艺术基因测序是 Artsy 特有的艺术品评级系统和技术架构,是 Artsy 的核心价值所在。它分析出每一件艺术品的“独特基因” (“genes”),用以追溯艺术家与艺术作品在历史上的纵横关系。现在我们已分析出1000多种基于历史进程、创作主旨和作品质量的“基因”。', traditional: '藝術基因測序是 Artsy 特有的藝術品分類系統和技術架構,是 Artsy 的核心價值所在。它分析出每一件藝術品的“獨特基因” (“genes”),用以追溯藝術家與藝術作品在歷史上的縱橫關係。現在我們已分析出1000多種基於歷史進程、創作主旨和作品質量的“基因”。' }, ios: iosTitle: { simplified: 'Artsy 与 iOS', traditional: 'Artsy 與 iOS' }, text: { simplified: '通过 Artsy 的 iPhone 与 iPad App,您可以随时随地接入我们庞大的数据库,在线上浏览、收藏、研究和购买艺术品,并在参观线下博览会时定制随身向导。扫描本页下方二维条码,即可在 App Store 中下载本 App。', traditional: '通過 Artsy 的 iPhone 與 iPad App,您可以隨時隨地接入我們龐大的資料庫,在線上瀏覽、收藏、研究和購買藝術品,並在參觀博覽會時訂製隨身嚮導。掃描本頁下方二維條碼,即可在 App Store 中下載本 App。' }, link: { simplified: '下载 App', traditional: '下載 App' } partnership: partnershipTitle: { simplified: '成为 Artsy 的合作伙伴', traditional: '成為 Artsy 的合作夥伴' }, gallery: subTitle: { simplified: '画廊' traditional: '畫廊' }, text: { simplified: 'Artsy 为画廊提供面向全球观众、艺术爱好者和收藏家的网络平台枢纽。在推广宣传画廊作品的基础上,Artsy 平台还可以提供馆藏管理与运营的后台支持,包括在云端的线上展品管理以及 iOS 系统下的管理软件。Artsy 的合作伙伴仅限于收到邀请的画廊,合作方每月缴纳会员费用。', traditional: 'Artsy 為畫廊提供面向全球觀眾、藝術愛好者和收藏家的網路平台樞紐。在推廣宣傳畫廊作品的基礎上,Artsy 平台更提供館藏管理與營運的後台系統,包括雲端的線上展品管理以及 iOS 系統下的管理軟體。 Artsy 的合作夥伴僅限於收到邀請的畫廊,合作方每月繳納會員費用。' }, link: { simplified: '了解更多', traditional: '了解更多' }, institution: subTitle: { simplified: '基金会与博物馆', traditional: '基金會與博物館' }, text: { simplified: '基金会与博物馆可以在 Artsy 平台上推广展览、馆藏以及其他活动,通过 Artsy 的网上交易平台出售限量版艺术品。', traditional: '基金會與博物館可以在 Ar​​tsy 平台上推廣展覽、館藏以及其他活動,通過 Artsy 的線上交易平台出售限量版藝術品。' }, link: { simplified: '了解更多', traditional: '了解更多' }, auction: subTitle: { simplified: '拍卖行', traditional: '拍賣行' }, text: { simplified: 'Artsy 愿与公益拍卖和商业拍卖行进行合作。' traditional: 'Artsy 願與公益拍賣和商業拍賣行進行合作。' }, link: { simplified: '了解更多', traditional: '申請加盟' }
true
module.exports = artWorld: sectionTitle: { simplified: '艺术品在线', traditional: '藝術品在線' }, carousel: [ { image_url: './images/body-1-1.jpg', englishCaption: 'PI:NAME:<NAME>END_PI', caption: simplified: '卢浮宫', traditional: '盧浮宮' }, { image_url: './images/body-1-2.jpg', englishCaption: 'Los Angeles Modern Auctions', caption: simplified: '拍卖行', traditional: '拍賣行' }, { image_url: './images/body-1-3.jpg', englishCaption: 'Pearl Lam', caption: simplified: '艺术门', traditional: '藝術門' }, { image_url: "./images/body-1-4.jpg", englishCaption: 'The Armory Show', caption: simplified: '博览会', traditional: '博覽會' } ], artWorldBody: { simplified: 'Artsy 拥有全世界最领先的画廊、博物馆、基金会、艺术品展览与拍卖的综合资源。我们的藏品数据库涵盖全球4万多位艺术家的作品, 28万多幅美术、建筑与生活艺术品佳作,横跨古代、现代与当代艺术风格。当代艺术的网上藏品数量尤为丰富,居全球之首。无论是资深收藏家和学者,还是艺术赞助人、博物馆爱好者或学生,都可以通过 Artsy 发掘艺术的价值,找到真正打动心灵的艺术作品。', traditional: 'Artsy 擁有全世界最領先的畫廊、博物館、基金會、藝術品展覽與拍賣的綜合資源。我們的藏品資料庫涵蓋全球4萬多位藝術家的作品, 28萬多幅美術、建築與生活藝術品佳作,橫跨古代、現代與當代藝術風格。當代藝術的網上藏品數量尤為豐富,居全球之首。無論是資深收藏家和學者,還是藝術贊助者、博物館愛好者或學生,都可以通過 Artsy 發掘藝術的價值,找到真正打動心靈的藝術作品' } collecting: collectingTitle: { simplified: '在 Artsy 寻宝', traditional: '在 Artsy 尋寶' }, text: { simplified: '在 Artsy 可购买的艺术品多达16万件,均为全球顶尖画廊、公益以及商业竞拍之精品。每日有新艺术品上线,价格从100美元到100万美元不等。买家可以通过 Artsy 免费与画廊建立联系,参与竞拍或直接购买心仪的作品。', traditional: '在 Artsy 可購買的藝術品多達16萬件,均為全球頂尖畫廊、公益以及商業競拍之精品。每日有新藝術品上線,價格從100美元到100萬美元不等。買家可以通過 Artsy 免費與畫廊建立聯繫,參與競拍或直接購買心儀的作品。' } genome: genomeTitle: { simplified: '艺术基因测序 (The Art Genome Project)', traditional: '藝術基因測序 (The Art Genome Project)' }, text: { simplified: '艺术基因测序是 Artsy 特有的艺术品评级系统和技术架构,是 Artsy 的核心价值所在。它分析出每一件艺术品的“独特基因” (“genes”),用以追溯艺术家与艺术作品在历史上的纵横关系。现在我们已分析出1000多种基于历史进程、创作主旨和作品质量的“基因”。', traditional: '藝術基因測序是 Artsy 特有的藝術品分類系統和技術架構,是 Artsy 的核心價值所在。它分析出每一件藝術品的“獨特基因” (“genes”),用以追溯藝術家與藝術作品在歷史上的縱橫關係。現在我們已分析出1000多種基於歷史進程、創作主旨和作品質量的“基因”。' }, ios: iosTitle: { simplified: 'Artsy 与 iOS', traditional: 'Artsy 與 iOS' }, text: { simplified: '通过 Artsy 的 iPhone 与 iPad App,您可以随时随地接入我们庞大的数据库,在线上浏览、收藏、研究和购买艺术品,并在参观线下博览会时定制随身向导。扫描本页下方二维条码,即可在 App Store 中下载本 App。', traditional: '通過 Artsy 的 iPhone 與 iPad App,您可以隨時隨地接入我們龐大的資料庫,在線上瀏覽、收藏、研究和購買藝術品,並在參觀博覽會時訂製隨身嚮導。掃描本頁下方二維條碼,即可在 App Store 中下載本 App。' }, link: { simplified: '下载 App', traditional: '下載 App' } partnership: partnershipTitle: { simplified: '成为 Artsy 的合作伙伴', traditional: '成為 Artsy 的合作夥伴' }, gallery: subTitle: { simplified: '画廊' traditional: '畫廊' }, text: { simplified: 'Artsy 为画廊提供面向全球观众、艺术爱好者和收藏家的网络平台枢纽。在推广宣传画廊作品的基础上,Artsy 平台还可以提供馆藏管理与运营的后台支持,包括在云端的线上展品管理以及 iOS 系统下的管理软件。Artsy 的合作伙伴仅限于收到邀请的画廊,合作方每月缴纳会员费用。', traditional: 'Artsy 為畫廊提供面向全球觀眾、藝術愛好者和收藏家的網路平台樞紐。在推廣宣傳畫廊作品的基礎上,Artsy 平台更提供館藏管理與營運的後台系統,包括雲端的線上展品管理以及 iOS 系統下的管理軟體。 Artsy 的合作夥伴僅限於收到邀請的畫廊,合作方每月繳納會員費用。' }, link: { simplified: '了解更多', traditional: '了解更多' }, institution: subTitle: { simplified: '基金会与博物馆', traditional: '基金會與博物館' }, text: { simplified: '基金会与博物馆可以在 Artsy 平台上推广展览、馆藏以及其他活动,通过 Artsy 的网上交易平台出售限量版艺术品。', traditional: '基金會與博物館可以在 Ar​​tsy 平台上推廣展覽、館藏以及其他活動,通過 Artsy 的線上交易平台出售限量版藝術品。' }, link: { simplified: '了解更多', traditional: '了解更多' }, auction: subTitle: { simplified: '拍卖行', traditional: '拍賣行' }, text: { simplified: 'Artsy 愿与公益拍卖和商业拍卖行进行合作。' traditional: 'Artsy 願與公益拍賣和商業拍賣行進行合作。' }, link: { simplified: '了解更多', traditional: '申請加盟' }
[ { "context": "nome = 'Alberto Borguesani'", "end": 26, "score": 0.9998683929443359, "start": 8, "tag": "NAME", "value": "Alberto Borguesani" } ]
public/coffee/teste.coffee
BetoVerzemiassi/gruntjs
0
nome = 'Alberto Borguesani'
191124
nome = '<NAME>'
true
nome = 'PI:NAME:<NAME>END_PI'