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": "gnorable\n # token expressions between tokens. (Jyrki Niemi 2016-02-02)\n addExpandedCQP : (data, cqp = nul", "end": 853, "score": 0.9996961951255798, "start": 842, "tag": "NAME", "value": "Jyrki Niemi" }, { "context": "nly if\n # settings.addBackendLogInfo is ...
app/scripts/model.coffee
CSCfi/Kielipankki-korp-frontend
0
"use strict" window.model = {} model.getAuthorizationHeader = () -> if typeof authenticationProxy isnt "undefined" and not $.isEmptyObject(authenticationProxy.loginObj) "Authorization" : "Basic " + authenticationProxy.loginObj.auth else {} class BaseProxy constructor: -> # progress @prev = "" @progress = 0 @total @total_results = 0 @pendingRequests = [] expandCQP : (cqp) -> try return CQP.expandOperators cqp catch e c.warn "CQP expansion failed", cqp, e return cqp # Add the possibly combined and unexpanded CQP query cqp (or # data.cqp) to data, splitting prequeries into separate # parameters, expanding all CQP queries and adding the ignorable # token expressions between tokens. (Jyrki Niemi 2016-02-02) addExpandedCQP : (data, cqp = null) -> # c.log "addExpandedCQP", data, data.cqp, cqp if cqp is null and "cqp" of data cqp = data.cqp util.addCQPs(data, cqp, (cqp) => settings.corpusListing.addIgnoreBetweenTokensCQP @expandCQP cqp) # c.log "addExpandedCQP result", data, data.cqp makeRequest: -> @abort() @prev = "" @progress = 0 @total_results = 0 @total = null abort: -> _.invoke @pendingRequests, "abort" if @pendingRequests.length # @pendingRequests = [] hasPending : () -> _.any _.map @pendingRequests, (req) -> req.readyState != 4 and req.readyState != 0 parseJSON: (data) -> try # var prefix = data[0] == "{" ? "" : "{"; # var suffix = data.slice(-1) == "}" ? "" : "}"; # var json = prefix + data.slice(0,-2) + suffix; json = data # json = "{" + json.slice(0, -1) + "}" if json.slice(-1) is "," if json[0] != "{" then json = "{" + json if json.match(/,\s*$/) json = json.replace(/,\s*$/, "") + "}" # c.log('json after', json) out = JSON.parse(json) # c.log "json parsing success!", json return out catch e # c.log("trying data", data); return JSON.parse(data) addAuthorizationHeader: (req) -> pairs = _.pairs model.getAuthorizationHeader() if pairs.length req.setRequestHeader pairs[0]... calcProgress: (e) -> newText = e.target.responseText.slice(@prev.length) # c.log "newText", newText struct = {} try struct = @parseJSON(newText) # c.log("json parse failed in ", newText); $.each struct, (key, val) => if key isnt "progress_corpora" and key.split("_")[0] is "progress" currentCorpus = val.corpus or val sum = _(currentCorpus.split("|")).map((corpus) -> Number settings.corpora[corpus.toLowerCase()].info.Size ).reduce((a, b) -> a + b , 0) @progress += sum @total_results += parseInt(val.hits) stats = (@progress / @total) * 100 if not @total? and struct.progress_corpora?.length @total = $.reduce($.map(struct["progress_corpora"], (corpus) -> return if not corpus.length _(corpus.split("|")).map((corpus) -> parseInt settings.corpora[corpus.toLowerCase()].info.Size ).reduce((a, b) -> a + b , 0) ), (val1, val2) -> val1 + val2 , 0) @prev = e.target.responseText struct: struct stats: stats total_results: @total_results # Add to the backend query parameters in data the parameter # "loginfo", to be written to the backend log. The value is based # on its existing value, the values returned by # util.makeLogInfoItems and the values in argument loginfo (either # a single string or an array of strings). This is done only if # settings.addBackendLogInfo is true. (Jyrki Niemi 2017-12-14) addLogInfo: (data, loginfo) -> if settings.addBackendLogInfo new_loginfo = [data.loginfo].concat util.makeLogInfoItems() if _.isArray loginfo new_loginfo = new_loginfo.concat loginfo else new_loginfo.push loginfo new_loginfo = _.compact(new_loginfo).join(" ") if new_loginfo data.loginfo = new_loginfo return data class model.KWICProxy extends BaseProxy constructor: -> super() @prevRequest = null @queryData = null @prevAjaxParams = null @foundKwic = false popXhr: (xhr) -> i = $.inArray(@pendingRequests, xhr) @pendingRequests.pop i unless i is -1 makeRequest: (options, page, progressCallback, kwicCallback, loginfo) -> c.log "kwicproxy.makeRequest", options, page, kwicResults.getPageInterval(Number(page)) self = this @foundKwic = false super() kwicCallback = kwicCallback or $.proxy(kwicResults.renderResult, kwicResults) self.progress = 0 o = $.extend( queryData: null progress: (data, e) -> progressObj = self.calcProgress(e) return unless progressObj? progressCallback progressObj if progressObj["struct"].kwic c.log "found kwic!" @foundKwic = true kwicCallback progressObj["struct"] , options) unless options.ajaxParams.within _.extend options.ajaxParams, settings.corpusListing.getWithinParameters() data = command: "query" defaultcontext: settings.defaultOverviewContext show: [] show_struct: [] cache : true $.extend data, kwicResults.getPageInterval(page), o.ajaxParams for corpus in settings.corpusListing.selected for key, val of corpus.within data.show.push _.last key.split(" ") for key, val of corpus.attributes data.show.push key if corpus.struct_attributes? $.each corpus.struct_attributes, (key, val) -> data.show_struct.push key if $.inArray(key, data.show_struct) is -1 if data.cqp # data.cqp = @expandCQP(data.cqp) @addExpandedCQP data, data.cqp util.addPrequeryWithin data # @prevCQP = data.cqp @prevCQP = util.combineCQPs data data.show = util.encodeListParamUniq ["sentence"].concat(data.show) c.log "data.show", data.show data.show_struct = util.encodeListParamUniq data.show_struct settings.corpusListing.minimizeWithinQueryString data settings.corpusListing.minimizeContextQueryString data data.corpus = util.encodeListParam data.corpus @addLogInfo data, loginfo @prevRequest = data @prevMisc = {"hitsPerPage" : $("#num_hits").val()} @prevParams = data def = $.ajax( url: settings.cgi_script data: util.compressQueryParams data beforeSend: (req, settings) -> self.prevRequest = settings self.addAuthorizationHeader req self.prevUrl = this.url success: (data, status, jqxhr) -> c.log "jqxhr", this self.queryData = data.querydata kwicCallback data if data.incremental is false or not @foundKwic # error: o.error progress: o.progress ) @pendingRequests.push def return def class model.LemgramProxy extends BaseProxy constructor: -> super() # @pendingRequest = abort: $.noop makeRequest: (word, type, callback, loginfo) -> super() self = this params = command: "relations" word: word corpus: settings.corpusListing.stringifySelectedEncode() incremental: $.support.ajaxProgress type: type cache : true max : 1000 # max : settings.wordPictureMaxWords or 15 @addLogInfo params, loginfo @prevParams = params def = $.ajax url: settings.cgi_script data: util.compressQueryParams params # beforeSend: (jqXHR, settings) -> # c.log "before relations send", settings # # self.prevRequest = settings # error: (data, status) -> # c.log "relationsearch abort", arguments # if status == "abort" # else # lemgramResults.resultError() success: (data) -> c.log "relations success", data self.prevRequest = params # lemgramResults.renderResult data, word progress: (data, e) -> progressObj = self.calcProgress(e) return unless progressObj? callback progressObj beforeSend: (req, settings) -> self.prevRequest = settings self.addAuthorizationHeader req self.prevUrl = this.url @pendingRequests.push def return def karpSearch: (word, sw_forms) -> deferred = $.Deferred((dfd) => @pendingRequests.push $.ajax( # url: "http://spraakbanken.gu.se/ws/karp-sok" url: settings.lemgrams_cgi_script data: wf: word corpus: settings.corpusListing.stringifySelected() resource: settings.corpusListing.getMorphology() format: "json" "sms-forms": false "sw-forms": sw_forms success: (data, textStatus, xhr) -> if Number(data.count) is 0 dfd.reject() return c.log "karp success", data, sw_forms div = (if $.isPlainObject(data.div) then [data.div] else data.div) output = $.map(div.slice(0, Number(data.count)), (item) -> # item = util.convertLMFFeatsToObjects(item) # item.LexicalEntry.Lemma.FormRepresentation.feat_lemgram item.LexicalEntry.lem ) dfd.resolve output, textStatus, xhr error: (jqXHR, textStatus, errorThrown) -> c.log "karp error", jqXHR, textStatus, errorThrown dfd.reject() ) ).promise() deferred saldoSearch: (word, sw_forms) -> dfd = $.Deferred() @karpSearch(word, sw_forms).done (lemgramArray) -> $.ajax( url: "http://spraakbanken.gu.se/ws/karp-sok" data: lemgram: lemgramArray.join("|") resource: "saldo" format: "json" ).done((data, textStatus, xhr) -> if data.count is 0 dfd.reject() c.log "saldo search 0 results" return div = (if $.isPlainObject(data.div) then [data.div] else data.div) output = $.map(div.slice(0, Number(data.count)), (item) -> sense = item.LexicalEntry.Sense sense = [sense] unless $.isArray(sense) _.map sense, (item) -> item.id ) c.log "saldoSearch results", output dfd.resolve output, textStatus, xhr ).fail -> c.log "saldo search failed" dfd.reject() dfd lemgramCount: (lemgrams, findPrefix, findSuffix) -> self = this count = $.grep(["lemgram", (if findPrefix then "prefix" else ""), (if findSuffix then "suffix" else "")], Boolean) $.ajax url: settings.cgi_script data: command: "lemgram_count" lemgram: lemgrams count: count.join(",") corpus: settings.corpusListing.stringifySelected() beforeSend: (req) -> self.addAuthorizationHeader req method: "POST" lemgramSearch: (lemgram, searchPrefix, searchSuffix) -> return $.format("[(lex contains \"%s\")%s%s]", [lemgram, @buildAffixQuery(searchPrefix, "prefix", lemgram), @buildAffixQuery(searchSuffix, "suffix", lemgram)]) buildAffixQuery: (isValid, key, value) -> return "" unless isValid $.format "| (%s contains \"%s\")", [key, value] class model.StatsProxy extends BaseProxy constructor: -> super() @prevRequest = null @prevParams = null @currentPage = 0 @page_incr = 25 processData: (def, data, reduceVals, reduceValLabels, ignoreCase) -> minWidth = 100 columns = [] for [reduceVal, reduceValLabel] in _.zip reduceVals, reduceValLabels columns.push id: reduceVal name: reduceValLabel field: "hit_value" sortable: true formatter: statisticsFormatting.reduceStatistics reduceVals, ignoreCase, _.keys(data.corpora) minWidth: minWidth cssClass: "parameter-column" headerCssClass: "localized-header" columns.push id: "pieChart" name: "" field: "hit_value" sortable: false formatter: statisticsFormatting.reduceStatisticsPieChart maxWidth: 25 minWidth: 25 columns.push id: "total" name: "stats_total" field: "total_value" sortable: true formatter: @valueFormatter minWidth : minWidth headerCssClass: "localized-header" $.each _.keys(data.corpora).sort(), (i, corpus) => columns.push id: corpus name: settings.corpora[corpus.toLowerCase()].title field: corpus + "_value" sortable: true formatter: @valueFormatter minWidth : minWidth groups = _.groupBy _.keys(data.total.absolute), (item) -> statisticsFormatting.makeGroupingValue(item) wordArray = _.keys groups sizeOfDataset = wordArray.length dataset = new Array(sizeOfDataset + 1) statsWorker = new Worker "scripts/statistics_worker.js" statsWorker.onmessage = (e) -> c.log "Called back by the worker!\n" c.log e searchParams = reduceVals: reduceVals ignoreCase: ignoreCase corpora: _.keys data.corpora def.resolve [data, wordArray, columns, e.data.dataset, e.data.summarizedData, searchParams] statsWorker.postMessage { "total" : data.total "dataset" : dataset "allrows" : (wordArray) "corpora" : data.corpora "groups" : groups loc : settings.locales[$("body").scope().lang] "attrs" : reduceVals } makeParameters: (reduceVals, cqp) -> parameters = command: "count" groupby: reduceVals.join ',' # cqp: @expandCQP cqp corpus: settings.corpusListing.stringifySelectedEncode(true) incremental: $.support.ajaxProgress @addExpandedCQP parameters, cqp _.extend parameters, settings.corpusListing.getWithinParameters() util.addPrequeryWithin parameters return parameters makeRequest: (cqp, callback, loginfo) -> self = this super() reduceval = search().stats_reduce or "word" reduceVals = reduceval.split "," insensitive = search().stats_reduce_insensitive if insensitive ignoreCase = true else ignoreCase = false reduceValLabels = _.map reduceVals, (reduceVal) -> return "word" if reduceVal == "word" maybeReduceAttr = settings.corpusListing.getCurrentAttributes(settings.corpusListing.getReduceLang())[reduceVal] if maybeReduceAttr return maybeReduceAttr.label else return settings.corpusListing.getStructAttrs(settings.corpusListing.getReduceLang())[reduceVal].label # TODO: Make sure this works with util.addCQPs # Seems it didn't but with addExpandedCQP it would seem to # work. (Jyrki Niemi 2016-02-02) data = @makeParameters(reduceVals, cqp) data.split = _.filter(reduceVals, (reduceVal) -> settings.corpusListing.getCurrentAttributes(settings.corpusListing.getReduceLang())[reduceVal]?.type == "set").join(',') rankedReduceVals = _.filter reduceVals, (reduceVal) -> settings.corpusListing.getCurrentAttributes(settings.corpusListing.getReduceLang())[reduceVal]?.ranked data.top = _.map(rankedReduceVals, (reduceVal) -> return reduceVal + ":1").join(',') if ignoreCase $.extend data, ignore_case: "word" settings.corpusListing.minimizeWithinQueryString data @prevNonExpandedCQP = cqp @addLogInfo data, loginfo @prevParams = data def = $.Deferred() @pendingRequests.push $.ajax url: settings.cgi_script data: util.compressQueryParams data beforeSend: (req, settings) -> self.prevRequest = settings self.addAuthorizationHeader req self.prevUrl = this.url error: (jqXHR, textStatus, errorThrown) -> c.log "gettings stats error, status: " + textStatus def.reject(textStatus, errorThrown) progress: (data, e) -> progressObj = self.calcProgress(e) return unless progressObj? callback? progressObj success: (data) => if data.ERROR? c.log "gettings stats failed with error", data.ERROR def.reject(data) return @processData(def, data, reduceVals, reduceValLabels, ignoreCase) return def.promise() valueFormatter: (row, cell, value, columnDef, dataContext) -> return dataContext[columnDef.id + "_display"] class model.NameProxy extends model.StatsProxy constructor: -> super() makeParameters: (reduceVal, cqp) -> # ignore reduceVal, map only works for word parameters = super([settings.placenameAttr], cqp) parameters.cqp2 = "[" + settings.placenameConstraint + "]" return parameters processData: (def, data, reduceval) -> def.resolve data class model.AuthenticationProxy constructor: -> @loginObj = {} makeRequest: (usr, pass, saveLogin) -> self = this if window.btoa auth = window.btoa(usr + ":" + pass) else throw "window.btoa is undefined" dfd = $.Deferred() $.ajax( url: settings.cgi_script type: "GET" data: command: "authenticate" beforeSend: (req) -> req.setRequestHeader "Authorization", "Basic " + auth ).done((data, status, xhr) -> unless data.corpora dfd.reject() return self.loginObj = name: # This is the only change for Shibboleth authentication in model.coffee: I use the username returned from the authentication proxy (auth.cgi) -- matthies 28.11.13, janiemi 2014-01-13 if settings.authenticationType == "shibboleth" data.username else usr credentials: data.corpora auth: auth if saveLogin $.jStorage.set "creds", self.loginObj dfd.resolve data ).fail (xhr, status, error) -> c.log "auth fail", arguments dfd.reject() dfd hasCred : (corpusId) -> unless @loginObj.credentials then return false corpusId.toUpperCase() in @loginObj.credentials class model.TimeProxy extends BaseProxy constructor: -> makeRequest: () -> dfd = $.Deferred() xhr = $.ajax url: settings.cgi_script type: "POST" data: command: "timespan" granularity: "y" corpus: settings.corpusListing.stringifyAll() xhr.done (data, status, xhr) => c.log "timespan done", data if data.ERROR c.error "timespan error", data.ERROR dfd.reject(data.ERROR ) return rest = data.combined[""] delete data.combined[""] @expandTimeStruct data.combined combined = @compilePlotArray(data.combined) # dfd.resolve output, rest if _.keys(data).length < 2 or data.ERROR dfd.reject() return # @corpusdata = data dfd.resolve [data.corpora, combined, rest] xhr.fail -> c.log "timeProxy.makeRequest failed", arguments dfd.reject() dfd compilePlotArray: (dataStruct) -> output = [] $.each dataStruct, (key, val) -> return if not key or not val output.push [parseInt(key), val] output = output.sort((a, b) -> a[0] - b[0] ) output expandTimeStruct: (struct) -> # c.log "struct", struct years = _.map(_.pairs(_.omit(struct, "")), (item) -> Number item[0] ) unless years.length then return minYear = _.min years maxYear = _.max years if _.isNaN(maxYear) or _.isNaN(minYear) c.log "expandTimestruct broken, years:", years return # while y < maxYear # c.log "years", minYear, maxYear for y in [minYear..maxYear] thisVal = struct[y] if typeof thisVal is "undefined" struct[y] = prevVal else prevVal = thisVal # c.log "after", struct class model.GraphProxy extends BaseProxy constructor: -> super() @prevParams = null expandSubCqps : (subArray) -> padding = _.map [0...subArray.length.toString().length], -> "0" array = for cqp, i in subArray p = padding[i.toString().length..].join("") ["subcqp#{p}#{i}", cqp] return _.object array makeRequest: (cqp, subcqps, corpora, from, to, loginfo) -> super() self = this params = command : "count_time" # cqp : @expandCQP cqp corpus : util.encodeListParam corpora granularity : @granularity incremental: $.support.ajaxProgress if from params.from = from if to params.to = to # util.addCQPs params, cqp @addExpandedCQP params, cqp #TODO: fix this for struct attrs _.extend params, @expandSubCqps subcqps @addLogInfo params, loginfo @prevParams = params def = $.Deferred() $.ajax url: settings.cgi_script # url : "data.json" dataType : "json" data : util.compressQueryParams params beforeSend: (req, settings) => @prevRequest = settings @addAuthorizationHeader req self.prevUrl = this.url progress: (data, e) => progressObj = @calcProgress(e) return unless progressObj? # callback progressObj def.notify progressObj error: (jqXHR, textStatus, errorThrown) -> def.reject(textStatus) success : (data) -> def.resolve data # [first, last] = settings.corpusListing.getTimeInterval() # data return def.promise() class model.NameClassificationProxy extends BaseProxy # Copied and modified from model.LemgramProxy (Jyrki Niemi 2015-05-29) constructor: -> super() makeRequest: (cqp, within, callback, loginfo) -> super() self = this groups = if settings.name_groups (group.regex for group in settings.name_groups).join(",") else null params = command: "names" # cqp: cqp corpus: settings.corpusListing.stringifySelectedEncode() defaultwithin: "sentence" default_nameswithin: "text_id" max: settings.name_group_max_names or 30 groups: groups incremental: $.support.ajaxProgress cache: true @addExpandedCQP params, cqp @addLogInfo params, loginfo @prevParams = params def = $.ajax url: settings.cgi_script data: util.compressQueryParams params # beforeSend: (jqXHR, settings) -> # c.log "before relations send", settings # # self.prevRequest = settings # error: (data, status) -> # c.log "relationsearch abort", arguments # if status == "abort" # else # lemgramResults.resultError() success: (data) -> c.log "names success", data self.prevRequest = params # lemgramResults.renderResult data, word progress: (data, e) -> progressObj = self.calcProgress(e) return unless progressObj? callback progressObj beforeSend: (req, settings) -> self.prevRequest = settings self.addAuthorizationHeader req self.prevUrl = this.url @pendingRequests.push def return def
117347
"use strict" window.model = {} model.getAuthorizationHeader = () -> if typeof authenticationProxy isnt "undefined" and not $.isEmptyObject(authenticationProxy.loginObj) "Authorization" : "Basic " + authenticationProxy.loginObj.auth else {} class BaseProxy constructor: -> # progress @prev = "" @progress = 0 @total @total_results = 0 @pendingRequests = [] expandCQP : (cqp) -> try return CQP.expandOperators cqp catch e c.warn "CQP expansion failed", cqp, e return cqp # Add the possibly combined and unexpanded CQP query cqp (or # data.cqp) to data, splitting prequeries into separate # parameters, expanding all CQP queries and adding the ignorable # token expressions between tokens. (<NAME> 2016-02-02) addExpandedCQP : (data, cqp = null) -> # c.log "addExpandedCQP", data, data.cqp, cqp if cqp is null and "cqp" of data cqp = data.cqp util.addCQPs(data, cqp, (cqp) => settings.corpusListing.addIgnoreBetweenTokensCQP @expandCQP cqp) # c.log "addExpandedCQP result", data, data.cqp makeRequest: -> @abort() @prev = "" @progress = 0 @total_results = 0 @total = null abort: -> _.invoke @pendingRequests, "abort" if @pendingRequests.length # @pendingRequests = [] hasPending : () -> _.any _.map @pendingRequests, (req) -> req.readyState != 4 and req.readyState != 0 parseJSON: (data) -> try # var prefix = data[0] == "{" ? "" : "{"; # var suffix = data.slice(-1) == "}" ? "" : "}"; # var json = prefix + data.slice(0,-2) + suffix; json = data # json = "{" + json.slice(0, -1) + "}" if json.slice(-1) is "," if json[0] != "{" then json = "{" + json if json.match(/,\s*$/) json = json.replace(/,\s*$/, "") + "}" # c.log('json after', json) out = JSON.parse(json) # c.log "json parsing success!", json return out catch e # c.log("trying data", data); return JSON.parse(data) addAuthorizationHeader: (req) -> pairs = _.pairs model.getAuthorizationHeader() if pairs.length req.setRequestHeader pairs[0]... calcProgress: (e) -> newText = e.target.responseText.slice(@prev.length) # c.log "newText", newText struct = {} try struct = @parseJSON(newText) # c.log("json parse failed in ", newText); $.each struct, (key, val) => if key isnt "progress_corpora" and key.split("_")[0] is "progress" currentCorpus = val.corpus or val sum = _(currentCorpus.split("|")).map((corpus) -> Number settings.corpora[corpus.toLowerCase()].info.Size ).reduce((a, b) -> a + b , 0) @progress += sum @total_results += parseInt(val.hits) stats = (@progress / @total) * 100 if not @total? and struct.progress_corpora?.length @total = $.reduce($.map(struct["progress_corpora"], (corpus) -> return if not corpus.length _(corpus.split("|")).map((corpus) -> parseInt settings.corpora[corpus.toLowerCase()].info.Size ).reduce((a, b) -> a + b , 0) ), (val1, val2) -> val1 + val2 , 0) @prev = e.target.responseText struct: struct stats: stats total_results: @total_results # Add to the backend query parameters in data the parameter # "loginfo", to be written to the backend log. The value is based # on its existing value, the values returned by # util.makeLogInfoItems and the values in argument loginfo (either # a single string or an array of strings). This is done only if # settings.addBackendLogInfo is true. (<NAME> 2017-12-14) addLogInfo: (data, loginfo) -> if settings.addBackendLogInfo new_loginfo = [data.loginfo].concat util.makeLogInfoItems() if _.isArray loginfo new_loginfo = new_loginfo.concat loginfo else new_loginfo.push loginfo new_loginfo = _.compact(new_loginfo).join(" ") if new_loginfo data.loginfo = new_loginfo return data class model.KWICProxy extends BaseProxy constructor: -> super() @prevRequest = null @queryData = null @prevAjaxParams = null @foundKwic = false popXhr: (xhr) -> i = $.inArray(@pendingRequests, xhr) @pendingRequests.pop i unless i is -1 makeRequest: (options, page, progressCallback, kwicCallback, loginfo) -> c.log "kwicproxy.makeRequest", options, page, kwicResults.getPageInterval(Number(page)) self = this @foundKwic = false super() kwicCallback = kwicCallback or $.proxy(kwicResults.renderResult, kwicResults) self.progress = 0 o = $.extend( queryData: null progress: (data, e) -> progressObj = self.calcProgress(e) return unless progressObj? progressCallback progressObj if progressObj["struct"].kwic c.log "found kwic!" @foundKwic = true kwicCallback progressObj["struct"] , options) unless options.ajaxParams.within _.extend options.ajaxParams, settings.corpusListing.getWithinParameters() data = command: "query" defaultcontext: settings.defaultOverviewContext show: [] show_struct: [] cache : true $.extend data, kwicResults.getPageInterval(page), o.ajaxParams for corpus in settings.corpusListing.selected for key, val of corpus.within data.show.push _.last key.split(" ") for key, val of corpus.attributes data.show.push key if corpus.struct_attributes? $.each corpus.struct_attributes, (key, val) -> data.show_struct.push key if $.inArray(key, data.show_struct) is -1 if data.cqp # data.cqp = @expandCQP(data.cqp) @addExpandedCQP data, data.cqp util.addPrequeryWithin data # @prevCQP = data.cqp @prevCQP = util.combineCQPs data data.show = util.encodeListParamUniq ["sentence"].concat(data.show) c.log "data.show", data.show data.show_struct = util.encodeListParamUniq data.show_struct settings.corpusListing.minimizeWithinQueryString data settings.corpusListing.minimizeContextQueryString data data.corpus = util.encodeListParam data.corpus @addLogInfo data, loginfo @prevRequest = data @prevMisc = {"hitsPerPage" : $("#num_hits").val()} @prevParams = data def = $.ajax( url: settings.cgi_script data: util.compressQueryParams data beforeSend: (req, settings) -> self.prevRequest = settings self.addAuthorizationHeader req self.prevUrl = this.url success: (data, status, jqxhr) -> c.log "jqxhr", this self.queryData = data.querydata kwicCallback data if data.incremental is false or not @foundKwic # error: o.error progress: o.progress ) @pendingRequests.push def return def class model.LemgramProxy extends BaseProxy constructor: -> super() # @pendingRequest = abort: $.noop makeRequest: (word, type, callback, loginfo) -> super() self = this params = command: "relations" word: word corpus: settings.corpusListing.stringifySelectedEncode() incremental: $.support.ajaxProgress type: type cache : true max : 1000 # max : settings.wordPictureMaxWords or 15 @addLogInfo params, loginfo @prevParams = params def = $.ajax url: settings.cgi_script data: util.compressQueryParams params # beforeSend: (jqXHR, settings) -> # c.log "before relations send", settings # # self.prevRequest = settings # error: (data, status) -> # c.log "relationsearch abort", arguments # if status == "abort" # else # lemgramResults.resultError() success: (data) -> c.log "relations success", data self.prevRequest = params # lemgramResults.renderResult data, word progress: (data, e) -> progressObj = self.calcProgress(e) return unless progressObj? callback progressObj beforeSend: (req, settings) -> self.prevRequest = settings self.addAuthorizationHeader req self.prevUrl = this.url @pendingRequests.push def return def karpSearch: (word, sw_forms) -> deferred = $.Deferred((dfd) => @pendingRequests.push $.ajax( # url: "http://spraakbanken.gu.se/ws/karp-sok" url: settings.lemgrams_cgi_script data: wf: word corpus: settings.corpusListing.stringifySelected() resource: settings.corpusListing.getMorphology() format: "json" "sms-forms": false "sw-forms": sw_forms success: (data, textStatus, xhr) -> if Number(data.count) is 0 dfd.reject() return c.log "karp success", data, sw_forms div = (if $.isPlainObject(data.div) then [data.div] else data.div) output = $.map(div.slice(0, Number(data.count)), (item) -> # item = util.convertLMFFeatsToObjects(item) # item.LexicalEntry.Lemma.FormRepresentation.feat_lemgram item.LexicalEntry.lem ) dfd.resolve output, textStatus, xhr error: (jqXHR, textStatus, errorThrown) -> c.log "karp error", jqXHR, textStatus, errorThrown dfd.reject() ) ).promise() deferred saldoSearch: (word, sw_forms) -> dfd = $.Deferred() @karpSearch(word, sw_forms).done (lemgramArray) -> $.ajax( url: "http://spraakbanken.gu.se/ws/karp-sok" data: lemgram: lemgramArray.join("|") resource: "saldo" format: "json" ).done((data, textStatus, xhr) -> if data.count is 0 dfd.reject() c.log "saldo search 0 results" return div = (if $.isPlainObject(data.div) then [data.div] else data.div) output = $.map(div.slice(0, Number(data.count)), (item) -> sense = item.LexicalEntry.Sense sense = [sense] unless $.isArray(sense) _.map sense, (item) -> item.id ) c.log "saldoSearch results", output dfd.resolve output, textStatus, xhr ).fail -> c.log "saldo search failed" dfd.reject() dfd lemgramCount: (lemgrams, findPrefix, findSuffix) -> self = this count = $.grep(["lemgram", (if findPrefix then "prefix" else ""), (if findSuffix then "suffix" else "")], Boolean) $.ajax url: settings.cgi_script data: command: "lemgram_count" lemgram: lemgrams count: count.join(",") corpus: settings.corpusListing.stringifySelected() beforeSend: (req) -> self.addAuthorizationHeader req method: "POST" lemgramSearch: (lemgram, searchPrefix, searchSuffix) -> return $.format("[(lex contains \"%s\")%s%s]", [lemgram, @buildAffixQuery(searchPrefix, "prefix", lemgram), @buildAffixQuery(searchSuffix, "suffix", lemgram)]) buildAffixQuery: (isValid, key, value) -> return "" unless isValid $.format "| (%s contains \"%s\")", [key, value] class model.StatsProxy extends BaseProxy constructor: -> super() @prevRequest = null @prevParams = null @currentPage = 0 @page_incr = 25 processData: (def, data, reduceVals, reduceValLabels, ignoreCase) -> minWidth = 100 columns = [] for [reduceVal, reduceValLabel] in _.zip reduceVals, reduceValLabels columns.push id: reduceVal name: reduceValLabel field: "hit_value" sortable: true formatter: statisticsFormatting.reduceStatistics reduceVals, ignoreCase, _.keys(data.corpora) minWidth: minWidth cssClass: "parameter-column" headerCssClass: "localized-header" columns.push id: "pieChart" name: "" field: "hit_value" sortable: false formatter: statisticsFormatting.reduceStatisticsPieChart maxWidth: 25 minWidth: 25 columns.push id: "total" name: "stats_total" field: "total_value" sortable: true formatter: @valueFormatter minWidth : minWidth headerCssClass: "localized-header" $.each _.keys(data.corpora).sort(), (i, corpus) => columns.push id: corpus name: settings.corpora[corpus.toLowerCase()].title field: corpus + "_value" sortable: true formatter: @valueFormatter minWidth : minWidth groups = _.groupBy _.keys(data.total.absolute), (item) -> statisticsFormatting.makeGroupingValue(item) wordArray = _.keys groups sizeOfDataset = wordArray.length dataset = new Array(sizeOfDataset + 1) statsWorker = new Worker "scripts/statistics_worker.js" statsWorker.onmessage = (e) -> c.log "Called back by the worker!\n" c.log e searchParams = reduceVals: reduceVals ignoreCase: ignoreCase corpora: _.keys data.corpora def.resolve [data, wordArray, columns, e.data.dataset, e.data.summarizedData, searchParams] statsWorker.postMessage { "total" : data.total "dataset" : dataset "allrows" : (wordArray) "corpora" : data.corpora "groups" : groups loc : settings.locales[$("body").scope().lang] "attrs" : reduceVals } makeParameters: (reduceVals, cqp) -> parameters = command: "count" groupby: reduceVals.join ',' # cqp: @expandCQP cqp corpus: settings.corpusListing.stringifySelectedEncode(true) incremental: $.support.ajaxProgress @addExpandedCQP parameters, cqp _.extend parameters, settings.corpusListing.getWithinParameters() util.addPrequeryWithin parameters return parameters makeRequest: (cqp, callback, loginfo) -> self = this super() reduceval = search().stats_reduce or "word" reduceVals = reduceval.split "," insensitive = search().stats_reduce_insensitive if insensitive ignoreCase = true else ignoreCase = false reduceValLabels = _.map reduceVals, (reduceVal) -> return "word" if reduceVal == "word" maybeReduceAttr = settings.corpusListing.getCurrentAttributes(settings.corpusListing.getReduceLang())[reduceVal] if maybeReduceAttr return maybeReduceAttr.label else return settings.corpusListing.getStructAttrs(settings.corpusListing.getReduceLang())[reduceVal].label # TODO: Make sure this works with util.addCQPs # Seems it didn't but with addExpandedCQP it would seem to # work. (<NAME> 2016-02-02) data = @makeParameters(reduceVals, cqp) data.split = _.filter(reduceVals, (reduceVal) -> settings.corpusListing.getCurrentAttributes(settings.corpusListing.getReduceLang())[reduceVal]?.type == "set").join(',') rankedReduceVals = _.filter reduceVals, (reduceVal) -> settings.corpusListing.getCurrentAttributes(settings.corpusListing.getReduceLang())[reduceVal]?.ranked data.top = _.map(rankedReduceVals, (reduceVal) -> return reduceVal + ":1").join(',') if ignoreCase $.extend data, ignore_case: "word" settings.corpusListing.minimizeWithinQueryString data @prevNonExpandedCQP = cqp @addLogInfo data, loginfo @prevParams = data def = $.Deferred() @pendingRequests.push $.ajax url: settings.cgi_script data: util.compressQueryParams data beforeSend: (req, settings) -> self.prevRequest = settings self.addAuthorizationHeader req self.prevUrl = this.url error: (jqXHR, textStatus, errorThrown) -> c.log "gettings stats error, status: " + textStatus def.reject(textStatus, errorThrown) progress: (data, e) -> progressObj = self.calcProgress(e) return unless progressObj? callback? progressObj success: (data) => if data.ERROR? c.log "gettings stats failed with error", data.ERROR def.reject(data) return @processData(def, data, reduceVals, reduceValLabels, ignoreCase) return def.promise() valueFormatter: (row, cell, value, columnDef, dataContext) -> return dataContext[columnDef.id + "_display"] class model.NameProxy extends model.StatsProxy constructor: -> super() makeParameters: (reduceVal, cqp) -> # ignore reduceVal, map only works for word parameters = super([settings.placenameAttr], cqp) parameters.cqp2 = "[" + settings.placenameConstraint + "]" return parameters processData: (def, data, reduceval) -> def.resolve data class model.AuthenticationProxy constructor: -> @loginObj = {} makeRequest: (usr, pass, saveLogin) -> self = this if window.btoa auth = window.btoa(usr + ":" + pass) else throw "window.btoa is undefined" dfd = $.Deferred() $.ajax( url: settings.cgi_script type: "GET" data: command: "authenticate" beforeSend: (req) -> req.setRequestHeader "Authorization", "Basic " + auth ).done((data, status, xhr) -> unless data.corpora dfd.reject() return self.loginObj = name: # This is the only change for Shibboleth authentication in model.coffee: I use the username returned from the authentication proxy (auth.cgi) -- matthies 28.11.13, <NAME> 2014-01-13 if settings.authenticationType == "shibboleth" data.username else usr credentials: data.corpora auth: auth if saveLogin $.jStorage.set "creds", self.loginObj dfd.resolve data ).fail (xhr, status, error) -> c.log "auth fail", arguments dfd.reject() dfd hasCred : (corpusId) -> unless @loginObj.credentials then return false corpusId.toUpperCase() in @loginObj.credentials class model.TimeProxy extends BaseProxy constructor: -> makeRequest: () -> dfd = $.Deferred() xhr = $.ajax url: settings.cgi_script type: "POST" data: command: "timespan" granularity: "y" corpus: settings.corpusListing.stringifyAll() xhr.done (data, status, xhr) => c.log "timespan done", data if data.ERROR c.error "timespan error", data.ERROR dfd.reject(data.ERROR ) return rest = data.combined[""] delete data.combined[""] @expandTimeStruct data.combined combined = @compilePlotArray(data.combined) # dfd.resolve output, rest if _.keys(data).length < 2 or data.ERROR dfd.reject() return # @corpusdata = data dfd.resolve [data.corpora, combined, rest] xhr.fail -> c.log "timeProxy.makeRequest failed", arguments dfd.reject() dfd compilePlotArray: (dataStruct) -> output = [] $.each dataStruct, (key, val) -> return if not key or not val output.push [parseInt(key), val] output = output.sort((a, b) -> a[0] - b[0] ) output expandTimeStruct: (struct) -> # c.log "struct", struct years = _.map(_.pairs(_.omit(struct, "")), (item) -> Number item[0] ) unless years.length then return minYear = _.min years maxYear = _.max years if _.isNaN(maxYear) or _.isNaN(minYear) c.log "expandTimestruct broken, years:", years return # while y < maxYear # c.log "years", minYear, maxYear for y in [minYear..maxYear] thisVal = struct[y] if typeof thisVal is "undefined" struct[y] = prevVal else prevVal = thisVal # c.log "after", struct class model.GraphProxy extends BaseProxy constructor: -> super() @prevParams = null expandSubCqps : (subArray) -> padding = _.map [0...subArray.length.toString().length], -> "0" array = for cqp, i in subArray p = padding[i.toString().length..].join("") ["subcqp#{p}#{i}", cqp] return _.object array makeRequest: (cqp, subcqps, corpora, from, to, loginfo) -> super() self = this params = command : "count_time" # cqp : @expandCQP cqp corpus : util.encodeListParam corpora granularity : @granularity incremental: $.support.ajaxProgress if from params.from = from if to params.to = to # util.addCQPs params, cqp @addExpandedCQP params, cqp #TODO: fix this for struct attrs _.extend params, @expandSubCqps subcqps @addLogInfo params, loginfo @prevParams = params def = $.Deferred() $.ajax url: settings.cgi_script # url : "data.json" dataType : "json" data : util.compressQueryParams params beforeSend: (req, settings) => @prevRequest = settings @addAuthorizationHeader req self.prevUrl = this.url progress: (data, e) => progressObj = @calcProgress(e) return unless progressObj? # callback progressObj def.notify progressObj error: (jqXHR, textStatus, errorThrown) -> def.reject(textStatus) success : (data) -> def.resolve data # [first, last] = settings.corpusListing.getTimeInterval() # data return def.promise() class model.NameClassificationProxy extends BaseProxy # Copied and modified from model.LemgramProxy (<NAME> 2015-05-29) constructor: -> super() makeRequest: (cqp, within, callback, loginfo) -> super() self = this groups = if settings.name_groups (group.regex for group in settings.name_groups).join(",") else null params = command: "names" # cqp: cqp corpus: settings.corpusListing.stringifySelectedEncode() defaultwithin: "sentence" default_nameswithin: "text_id" max: settings.name_group_max_names or 30 groups: groups incremental: $.support.ajaxProgress cache: true @addExpandedCQP params, cqp @addLogInfo params, loginfo @prevParams = params def = $.ajax url: settings.cgi_script data: util.compressQueryParams params # beforeSend: (jqXHR, settings) -> # c.log "before relations send", settings # # self.prevRequest = settings # error: (data, status) -> # c.log "relationsearch abort", arguments # if status == "abort" # else # lemgramResults.resultError() success: (data) -> c.log "names success", data self.prevRequest = params # lemgramResults.renderResult data, word progress: (data, e) -> progressObj = self.calcProgress(e) return unless progressObj? callback progressObj beforeSend: (req, settings) -> self.prevRequest = settings self.addAuthorizationHeader req self.prevUrl = this.url @pendingRequests.push def return def
true
"use strict" window.model = {} model.getAuthorizationHeader = () -> if typeof authenticationProxy isnt "undefined" and not $.isEmptyObject(authenticationProxy.loginObj) "Authorization" : "Basic " + authenticationProxy.loginObj.auth else {} class BaseProxy constructor: -> # progress @prev = "" @progress = 0 @total @total_results = 0 @pendingRequests = [] expandCQP : (cqp) -> try return CQP.expandOperators cqp catch e c.warn "CQP expansion failed", cqp, e return cqp # Add the possibly combined and unexpanded CQP query cqp (or # data.cqp) to data, splitting prequeries into separate # parameters, expanding all CQP queries and adding the ignorable # token expressions between tokens. (PI:NAME:<NAME>END_PI 2016-02-02) addExpandedCQP : (data, cqp = null) -> # c.log "addExpandedCQP", data, data.cqp, cqp if cqp is null and "cqp" of data cqp = data.cqp util.addCQPs(data, cqp, (cqp) => settings.corpusListing.addIgnoreBetweenTokensCQP @expandCQP cqp) # c.log "addExpandedCQP result", data, data.cqp makeRequest: -> @abort() @prev = "" @progress = 0 @total_results = 0 @total = null abort: -> _.invoke @pendingRequests, "abort" if @pendingRequests.length # @pendingRequests = [] hasPending : () -> _.any _.map @pendingRequests, (req) -> req.readyState != 4 and req.readyState != 0 parseJSON: (data) -> try # var prefix = data[0] == "{" ? "" : "{"; # var suffix = data.slice(-1) == "}" ? "" : "}"; # var json = prefix + data.slice(0,-2) + suffix; json = data # json = "{" + json.slice(0, -1) + "}" if json.slice(-1) is "," if json[0] != "{" then json = "{" + json if json.match(/,\s*$/) json = json.replace(/,\s*$/, "") + "}" # c.log('json after', json) out = JSON.parse(json) # c.log "json parsing success!", json return out catch e # c.log("trying data", data); return JSON.parse(data) addAuthorizationHeader: (req) -> pairs = _.pairs model.getAuthorizationHeader() if pairs.length req.setRequestHeader pairs[0]... calcProgress: (e) -> newText = e.target.responseText.slice(@prev.length) # c.log "newText", newText struct = {} try struct = @parseJSON(newText) # c.log("json parse failed in ", newText); $.each struct, (key, val) => if key isnt "progress_corpora" and key.split("_")[0] is "progress" currentCorpus = val.corpus or val sum = _(currentCorpus.split("|")).map((corpus) -> Number settings.corpora[corpus.toLowerCase()].info.Size ).reduce((a, b) -> a + b , 0) @progress += sum @total_results += parseInt(val.hits) stats = (@progress / @total) * 100 if not @total? and struct.progress_corpora?.length @total = $.reduce($.map(struct["progress_corpora"], (corpus) -> return if not corpus.length _(corpus.split("|")).map((corpus) -> parseInt settings.corpora[corpus.toLowerCase()].info.Size ).reduce((a, b) -> a + b , 0) ), (val1, val2) -> val1 + val2 , 0) @prev = e.target.responseText struct: struct stats: stats total_results: @total_results # Add to the backend query parameters in data the parameter # "loginfo", to be written to the backend log. The value is based # on its existing value, the values returned by # util.makeLogInfoItems and the values in argument loginfo (either # a single string or an array of strings). This is done only if # settings.addBackendLogInfo is true. (PI:NAME:<NAME>END_PI 2017-12-14) addLogInfo: (data, loginfo) -> if settings.addBackendLogInfo new_loginfo = [data.loginfo].concat util.makeLogInfoItems() if _.isArray loginfo new_loginfo = new_loginfo.concat loginfo else new_loginfo.push loginfo new_loginfo = _.compact(new_loginfo).join(" ") if new_loginfo data.loginfo = new_loginfo return data class model.KWICProxy extends BaseProxy constructor: -> super() @prevRequest = null @queryData = null @prevAjaxParams = null @foundKwic = false popXhr: (xhr) -> i = $.inArray(@pendingRequests, xhr) @pendingRequests.pop i unless i is -1 makeRequest: (options, page, progressCallback, kwicCallback, loginfo) -> c.log "kwicproxy.makeRequest", options, page, kwicResults.getPageInterval(Number(page)) self = this @foundKwic = false super() kwicCallback = kwicCallback or $.proxy(kwicResults.renderResult, kwicResults) self.progress = 0 o = $.extend( queryData: null progress: (data, e) -> progressObj = self.calcProgress(e) return unless progressObj? progressCallback progressObj if progressObj["struct"].kwic c.log "found kwic!" @foundKwic = true kwicCallback progressObj["struct"] , options) unless options.ajaxParams.within _.extend options.ajaxParams, settings.corpusListing.getWithinParameters() data = command: "query" defaultcontext: settings.defaultOverviewContext show: [] show_struct: [] cache : true $.extend data, kwicResults.getPageInterval(page), o.ajaxParams for corpus in settings.corpusListing.selected for key, val of corpus.within data.show.push _.last key.split(" ") for key, val of corpus.attributes data.show.push key if corpus.struct_attributes? $.each corpus.struct_attributes, (key, val) -> data.show_struct.push key if $.inArray(key, data.show_struct) is -1 if data.cqp # data.cqp = @expandCQP(data.cqp) @addExpandedCQP data, data.cqp util.addPrequeryWithin data # @prevCQP = data.cqp @prevCQP = util.combineCQPs data data.show = util.encodeListParamUniq ["sentence"].concat(data.show) c.log "data.show", data.show data.show_struct = util.encodeListParamUniq data.show_struct settings.corpusListing.minimizeWithinQueryString data settings.corpusListing.minimizeContextQueryString data data.corpus = util.encodeListParam data.corpus @addLogInfo data, loginfo @prevRequest = data @prevMisc = {"hitsPerPage" : $("#num_hits").val()} @prevParams = data def = $.ajax( url: settings.cgi_script data: util.compressQueryParams data beforeSend: (req, settings) -> self.prevRequest = settings self.addAuthorizationHeader req self.prevUrl = this.url success: (data, status, jqxhr) -> c.log "jqxhr", this self.queryData = data.querydata kwicCallback data if data.incremental is false or not @foundKwic # error: o.error progress: o.progress ) @pendingRequests.push def return def class model.LemgramProxy extends BaseProxy constructor: -> super() # @pendingRequest = abort: $.noop makeRequest: (word, type, callback, loginfo) -> super() self = this params = command: "relations" word: word corpus: settings.corpusListing.stringifySelectedEncode() incremental: $.support.ajaxProgress type: type cache : true max : 1000 # max : settings.wordPictureMaxWords or 15 @addLogInfo params, loginfo @prevParams = params def = $.ajax url: settings.cgi_script data: util.compressQueryParams params # beforeSend: (jqXHR, settings) -> # c.log "before relations send", settings # # self.prevRequest = settings # error: (data, status) -> # c.log "relationsearch abort", arguments # if status == "abort" # else # lemgramResults.resultError() success: (data) -> c.log "relations success", data self.prevRequest = params # lemgramResults.renderResult data, word progress: (data, e) -> progressObj = self.calcProgress(e) return unless progressObj? callback progressObj beforeSend: (req, settings) -> self.prevRequest = settings self.addAuthorizationHeader req self.prevUrl = this.url @pendingRequests.push def return def karpSearch: (word, sw_forms) -> deferred = $.Deferred((dfd) => @pendingRequests.push $.ajax( # url: "http://spraakbanken.gu.se/ws/karp-sok" url: settings.lemgrams_cgi_script data: wf: word corpus: settings.corpusListing.stringifySelected() resource: settings.corpusListing.getMorphology() format: "json" "sms-forms": false "sw-forms": sw_forms success: (data, textStatus, xhr) -> if Number(data.count) is 0 dfd.reject() return c.log "karp success", data, sw_forms div = (if $.isPlainObject(data.div) then [data.div] else data.div) output = $.map(div.slice(0, Number(data.count)), (item) -> # item = util.convertLMFFeatsToObjects(item) # item.LexicalEntry.Lemma.FormRepresentation.feat_lemgram item.LexicalEntry.lem ) dfd.resolve output, textStatus, xhr error: (jqXHR, textStatus, errorThrown) -> c.log "karp error", jqXHR, textStatus, errorThrown dfd.reject() ) ).promise() deferred saldoSearch: (word, sw_forms) -> dfd = $.Deferred() @karpSearch(word, sw_forms).done (lemgramArray) -> $.ajax( url: "http://spraakbanken.gu.se/ws/karp-sok" data: lemgram: lemgramArray.join("|") resource: "saldo" format: "json" ).done((data, textStatus, xhr) -> if data.count is 0 dfd.reject() c.log "saldo search 0 results" return div = (if $.isPlainObject(data.div) then [data.div] else data.div) output = $.map(div.slice(0, Number(data.count)), (item) -> sense = item.LexicalEntry.Sense sense = [sense] unless $.isArray(sense) _.map sense, (item) -> item.id ) c.log "saldoSearch results", output dfd.resolve output, textStatus, xhr ).fail -> c.log "saldo search failed" dfd.reject() dfd lemgramCount: (lemgrams, findPrefix, findSuffix) -> self = this count = $.grep(["lemgram", (if findPrefix then "prefix" else ""), (if findSuffix then "suffix" else "")], Boolean) $.ajax url: settings.cgi_script data: command: "lemgram_count" lemgram: lemgrams count: count.join(",") corpus: settings.corpusListing.stringifySelected() beforeSend: (req) -> self.addAuthorizationHeader req method: "POST" lemgramSearch: (lemgram, searchPrefix, searchSuffix) -> return $.format("[(lex contains \"%s\")%s%s]", [lemgram, @buildAffixQuery(searchPrefix, "prefix", lemgram), @buildAffixQuery(searchSuffix, "suffix", lemgram)]) buildAffixQuery: (isValid, key, value) -> return "" unless isValid $.format "| (%s contains \"%s\")", [key, value] class model.StatsProxy extends BaseProxy constructor: -> super() @prevRequest = null @prevParams = null @currentPage = 0 @page_incr = 25 processData: (def, data, reduceVals, reduceValLabels, ignoreCase) -> minWidth = 100 columns = [] for [reduceVal, reduceValLabel] in _.zip reduceVals, reduceValLabels columns.push id: reduceVal name: reduceValLabel field: "hit_value" sortable: true formatter: statisticsFormatting.reduceStatistics reduceVals, ignoreCase, _.keys(data.corpora) minWidth: minWidth cssClass: "parameter-column" headerCssClass: "localized-header" columns.push id: "pieChart" name: "" field: "hit_value" sortable: false formatter: statisticsFormatting.reduceStatisticsPieChart maxWidth: 25 minWidth: 25 columns.push id: "total" name: "stats_total" field: "total_value" sortable: true formatter: @valueFormatter minWidth : minWidth headerCssClass: "localized-header" $.each _.keys(data.corpora).sort(), (i, corpus) => columns.push id: corpus name: settings.corpora[corpus.toLowerCase()].title field: corpus + "_value" sortable: true formatter: @valueFormatter minWidth : minWidth groups = _.groupBy _.keys(data.total.absolute), (item) -> statisticsFormatting.makeGroupingValue(item) wordArray = _.keys groups sizeOfDataset = wordArray.length dataset = new Array(sizeOfDataset + 1) statsWorker = new Worker "scripts/statistics_worker.js" statsWorker.onmessage = (e) -> c.log "Called back by the worker!\n" c.log e searchParams = reduceVals: reduceVals ignoreCase: ignoreCase corpora: _.keys data.corpora def.resolve [data, wordArray, columns, e.data.dataset, e.data.summarizedData, searchParams] statsWorker.postMessage { "total" : data.total "dataset" : dataset "allrows" : (wordArray) "corpora" : data.corpora "groups" : groups loc : settings.locales[$("body").scope().lang] "attrs" : reduceVals } makeParameters: (reduceVals, cqp) -> parameters = command: "count" groupby: reduceVals.join ',' # cqp: @expandCQP cqp corpus: settings.corpusListing.stringifySelectedEncode(true) incremental: $.support.ajaxProgress @addExpandedCQP parameters, cqp _.extend parameters, settings.corpusListing.getWithinParameters() util.addPrequeryWithin parameters return parameters makeRequest: (cqp, callback, loginfo) -> self = this super() reduceval = search().stats_reduce or "word" reduceVals = reduceval.split "," insensitive = search().stats_reduce_insensitive if insensitive ignoreCase = true else ignoreCase = false reduceValLabels = _.map reduceVals, (reduceVal) -> return "word" if reduceVal == "word" maybeReduceAttr = settings.corpusListing.getCurrentAttributes(settings.corpusListing.getReduceLang())[reduceVal] if maybeReduceAttr return maybeReduceAttr.label else return settings.corpusListing.getStructAttrs(settings.corpusListing.getReduceLang())[reduceVal].label # TODO: Make sure this works with util.addCQPs # Seems it didn't but with addExpandedCQP it would seem to # work. (PI:NAME:<NAME>END_PI 2016-02-02) data = @makeParameters(reduceVals, cqp) data.split = _.filter(reduceVals, (reduceVal) -> settings.corpusListing.getCurrentAttributes(settings.corpusListing.getReduceLang())[reduceVal]?.type == "set").join(',') rankedReduceVals = _.filter reduceVals, (reduceVal) -> settings.corpusListing.getCurrentAttributes(settings.corpusListing.getReduceLang())[reduceVal]?.ranked data.top = _.map(rankedReduceVals, (reduceVal) -> return reduceVal + ":1").join(',') if ignoreCase $.extend data, ignore_case: "word" settings.corpusListing.minimizeWithinQueryString data @prevNonExpandedCQP = cqp @addLogInfo data, loginfo @prevParams = data def = $.Deferred() @pendingRequests.push $.ajax url: settings.cgi_script data: util.compressQueryParams data beforeSend: (req, settings) -> self.prevRequest = settings self.addAuthorizationHeader req self.prevUrl = this.url error: (jqXHR, textStatus, errorThrown) -> c.log "gettings stats error, status: " + textStatus def.reject(textStatus, errorThrown) progress: (data, e) -> progressObj = self.calcProgress(e) return unless progressObj? callback? progressObj success: (data) => if data.ERROR? c.log "gettings stats failed with error", data.ERROR def.reject(data) return @processData(def, data, reduceVals, reduceValLabels, ignoreCase) return def.promise() valueFormatter: (row, cell, value, columnDef, dataContext) -> return dataContext[columnDef.id + "_display"] class model.NameProxy extends model.StatsProxy constructor: -> super() makeParameters: (reduceVal, cqp) -> # ignore reduceVal, map only works for word parameters = super([settings.placenameAttr], cqp) parameters.cqp2 = "[" + settings.placenameConstraint + "]" return parameters processData: (def, data, reduceval) -> def.resolve data class model.AuthenticationProxy constructor: -> @loginObj = {} makeRequest: (usr, pass, saveLogin) -> self = this if window.btoa auth = window.btoa(usr + ":" + pass) else throw "window.btoa is undefined" dfd = $.Deferred() $.ajax( url: settings.cgi_script type: "GET" data: command: "authenticate" beforeSend: (req) -> req.setRequestHeader "Authorization", "Basic " + auth ).done((data, status, xhr) -> unless data.corpora dfd.reject() return self.loginObj = name: # This is the only change for Shibboleth authentication in model.coffee: I use the username returned from the authentication proxy (auth.cgi) -- matthies 28.11.13, PI:NAME:<NAME>END_PI 2014-01-13 if settings.authenticationType == "shibboleth" data.username else usr credentials: data.corpora auth: auth if saveLogin $.jStorage.set "creds", self.loginObj dfd.resolve data ).fail (xhr, status, error) -> c.log "auth fail", arguments dfd.reject() dfd hasCred : (corpusId) -> unless @loginObj.credentials then return false corpusId.toUpperCase() in @loginObj.credentials class model.TimeProxy extends BaseProxy constructor: -> makeRequest: () -> dfd = $.Deferred() xhr = $.ajax url: settings.cgi_script type: "POST" data: command: "timespan" granularity: "y" corpus: settings.corpusListing.stringifyAll() xhr.done (data, status, xhr) => c.log "timespan done", data if data.ERROR c.error "timespan error", data.ERROR dfd.reject(data.ERROR ) return rest = data.combined[""] delete data.combined[""] @expandTimeStruct data.combined combined = @compilePlotArray(data.combined) # dfd.resolve output, rest if _.keys(data).length < 2 or data.ERROR dfd.reject() return # @corpusdata = data dfd.resolve [data.corpora, combined, rest] xhr.fail -> c.log "timeProxy.makeRequest failed", arguments dfd.reject() dfd compilePlotArray: (dataStruct) -> output = [] $.each dataStruct, (key, val) -> return if not key or not val output.push [parseInt(key), val] output = output.sort((a, b) -> a[0] - b[0] ) output expandTimeStruct: (struct) -> # c.log "struct", struct years = _.map(_.pairs(_.omit(struct, "")), (item) -> Number item[0] ) unless years.length then return minYear = _.min years maxYear = _.max years if _.isNaN(maxYear) or _.isNaN(minYear) c.log "expandTimestruct broken, years:", years return # while y < maxYear # c.log "years", minYear, maxYear for y in [minYear..maxYear] thisVal = struct[y] if typeof thisVal is "undefined" struct[y] = prevVal else prevVal = thisVal # c.log "after", struct class model.GraphProxy extends BaseProxy constructor: -> super() @prevParams = null expandSubCqps : (subArray) -> padding = _.map [0...subArray.length.toString().length], -> "0" array = for cqp, i in subArray p = padding[i.toString().length..].join("") ["subcqp#{p}#{i}", cqp] return _.object array makeRequest: (cqp, subcqps, corpora, from, to, loginfo) -> super() self = this params = command : "count_time" # cqp : @expandCQP cqp corpus : util.encodeListParam corpora granularity : @granularity incremental: $.support.ajaxProgress if from params.from = from if to params.to = to # util.addCQPs params, cqp @addExpandedCQP params, cqp #TODO: fix this for struct attrs _.extend params, @expandSubCqps subcqps @addLogInfo params, loginfo @prevParams = params def = $.Deferred() $.ajax url: settings.cgi_script # url : "data.json" dataType : "json" data : util.compressQueryParams params beforeSend: (req, settings) => @prevRequest = settings @addAuthorizationHeader req self.prevUrl = this.url progress: (data, e) => progressObj = @calcProgress(e) return unless progressObj? # callback progressObj def.notify progressObj error: (jqXHR, textStatus, errorThrown) -> def.reject(textStatus) success : (data) -> def.resolve data # [first, last] = settings.corpusListing.getTimeInterval() # data return def.promise() class model.NameClassificationProxy extends BaseProxy # Copied and modified from model.LemgramProxy (PI:NAME:<NAME>END_PI 2015-05-29) constructor: -> super() makeRequest: (cqp, within, callback, loginfo) -> super() self = this groups = if settings.name_groups (group.regex for group in settings.name_groups).join(",") else null params = command: "names" # cqp: cqp corpus: settings.corpusListing.stringifySelectedEncode() defaultwithin: "sentence" default_nameswithin: "text_id" max: settings.name_group_max_names or 30 groups: groups incremental: $.support.ajaxProgress cache: true @addExpandedCQP params, cqp @addLogInfo params, loginfo @prevParams = params def = $.ajax url: settings.cgi_script data: util.compressQueryParams params # beforeSend: (jqXHR, settings) -> # c.log "before relations send", settings # # self.prevRequest = settings # error: (data, status) -> # c.log "relationsearch abort", arguments # if status == "abort" # else # lemgramResults.resultError() success: (data) -> c.log "names success", data self.prevRequest = params # lemgramResults.renderResult data, word progress: (data, e) -> progressObj = self.calcProgress(e) return unless progressObj? callback progressObj beforeSend: (req, settings) -> self.prevRequest = settings self.addAuthorizationHeader req self.prevUrl = this.url @pendingRequests.push def return def
[ { "context": "et et sw=2 ts=2 sts=2 ff=unix fenc=utf8:\n# Author: Binux<i@binux.me>\n# http://binux.me\n# Created o", "end": 64, "score": 0.9876154661178589, "start": 59, "tag": "USERNAME", "value": "Binux" }, { "context": "w=2 ts=2 sts=2 ff=unix fenc=utf8:\n# Author: Binux<i...
web/static/coffee/har/analysis.coffee
dhbowen1/qiandao
0
# vim: set et sw=2 ts=2 sts=2 ff=unix fenc=utf8: # Author: Binux<i@binux.me> # http://binux.me # Created on 2014-08-02 10:07:33 window.jinja_globals = ['md5','quote_chinese','utf8','unicode','timestamp','random','date_time','is_num','add','sub','multiply','divide'] jinja_globals = window.jinja_globals Array.prototype.some ?= (f) -> (return true if f x) for x in @ return false Array.prototype.every ?= (f) -> (return false if not f x) for x in @ return true define (require, exports, module) -> utils = require('/static/utils') xhr = (har) -> for entry in har.log.entries if (h for h in entry.request.headers when h.name == 'X-Requested-With' and h.value == 'XMLHttpRequest').length > 0 entry.filter_xhr = true return har mime_type = (har) -> for entry in har.log.entries mt = entry.response?.content?.mimeType entry.filter_mimeType = switch when not mt then 'other' when mt.indexOf('audio') == 0 then 'media' when mt.indexOf('image') == 0 then 'image' when mt.indexOf('javascript') != -1 then 'javascript' when mt in ['text/html', ] then 'document' when mt in ['text/css', 'application/x-pointplus', ] then 'style' when mt.indexOf('application') == 0 then 'media' else 'other' return har analyze_cookies = (har) -> # analyze where cookie from cookie_jar = new utils.CookieJar() for entry in har.log.entries cookies = {} for cookie in cookie_jar.getCookiesSync(entry.request.url, {now: new Date(entry.startedDateTime)}) cookies[cookie.key] = cookie.value for cookie in entry.request.cookies cookie.checked = false if cookie.name of cookies if cookie.value == cookies[cookie.name] cookie.from_session = true entry.filter_from_session = true else cookie.cookie_changed = true entry.filter_cookie_changed = true #cookie_jar.setCookieSync(utils.Cookie.fromJSON(angular.toJson({ #key: cookie.name #value: cookie.value #path: '/' #})), entry.request.url) else cookie.cookie_added = true entry.filter_cookie_added = true #cookie_jar.setCookieSync(utils.Cookie.fromJSON(angular.toJson({ #key: cookie.name #value: cookie.value #path: '/' #})), entry.request.url) # update cookie from response for header in (h for h in entry.response?.headers when h.name.toLowerCase() == 'set-cookie') entry.filter_set_cookie = true try cookie_jar.setCookieSync(header.value, entry.request.url, {now: new Date(entry.startedDateTime)}) catch error console.error(error) return har sort = (har) -> har.log.entries = har.log.entries.sort((a, b) -> if a.pageref > b.pageref 1 else if a.pageref < b.pageref -1 else if a.startedDateTime > b.startedDateTime 1 else if a.startedDateTime < b.startedDateTime -1 else 0 ) return har headers = (har) -> to_remove_headers = ['x-devtools-emulate-network-conditions-client-id', 'cookie', 'host', 'content-length', ] for entry in har.log.entries for header, i in entry.request.headers if header.name.toLowerCase() not in to_remove_headers header.checked = true else header.checked = false return har post_data = (har) -> for entry in har.log.entries if not entry.request.postData?.text continue if not (entry.request.postData?.mimeType?.toLowerCase().indexOf("application/x-www-form-urlencoded") == 0) entry.request.postData.params = undefined continue result = [] try for key, value of utils.querystring_parse(entry.request.postData.text) result.push({name: key, value: value}) entry.request.postData.params = result catch error console.error(error) entry.request.postData.params = undefined continue return har replace_variables = (har, variables) -> variables_vk = {} for k, v of variables if k?.length and v?.length variables_vk[v] = k #console.log variables_vk, variables # url for entry in har.log.entries try url = utils.url_parse(entry.request.url, true) catch error continue changed = false for key, value of url.query if value of variables_vk url.query[key] = "{{ #{variables_vk[value]} }}" changed = true if changed query = utils.querystring_unparse_with_variables(url.query) url.search = "?#{query}" if query entry.request.url = utils.url_unparse(url) entry.request.queryString = utils.dict2list(url.query) # post data for entry in har.log.entries if not entry.request.postData?.params? continue changed = false for each in entry.request.postData.params if each.value of variables_vk each.value = "{{ #{variables_vk[each.value]} }}" changed = true if changed obj = utils.list2dict(entry.request.postData.params) entry.request.postData.text = utils.querystring_unparse_with_variables(obj) return har rm_content = (har) -> for entry in har.log.entries if entry.response?.content?.text? entry.response?.content.text = undefined return har exports = analyze: (har, variables={}) -> if har.log replace_variables((xhr mime_type analyze_cookies headers sort post_data rm_content har), variables) else har recommend_default: (har) -> domain = null for entry in har.log.entries if not domain domain = utils.get_domain(entry.request.url) if exports.variables_in_entry(entry).length > 0 entry.recommend = true else if domain != utils.get_domain(entry.request.url) entry.recommend = false else if entry.response?.status in [304, 0] entry.recommend = false else if entry.response?.status // 100 == 3 entry.recommend = true else if entry.response?.cookies?.length > 0 entry.recommend = true else if entry.request.method == 'POST' entry.recommend = true else entry.recommend = false return har recommend: (har) -> for entry in har.log.entries entry.recommend = if entry.checked then true else false checked = (e for e in har.log.entries when e.checked) if checked.length == 0 return exports.recommend_default(har) related_cookies = [] for entry in checked for cookie in entry.request.cookies related_cookies.push(cookie.name) started = false for entry in har.log.entries by -1 started = entry.checked if not started if not started continue if not entry.response?.cookies continue start_time = new Date(entry.startedDateTime) set_cookie = (cookie.name for cookie in entry.response?.cookies when not cookie.expires or (new Date(cookie.expires)) > start_time) _related_cookies = (c for c in related_cookies when c not in set_cookie) if related_cookies.length > _related_cookies.length entry.recommend = true related_cookies = _related_cookies # add pre request cookie for cookie in entry.request.cookies related_cookies.push(cookie.name) return har variables: (string) -> re = /{{\s*([\w]+)[^}]*?\s*}}/g while m = re.exec(string) if jQuery.inArray(m[1], jinja_globals) < 0 m[1] variables_in_entry: (entry) -> result = [] [ [entry.request.url, ] (h.name for h in entry.request.headers when h.checked) (h.value for h in entry.request.headers when h.checked) (c.name for c in entry.request.cookies when c.checked) (c.value for c in entry.request.cookies when c.checked) [entry.request.postData?.text,] ].map((list) -> for string in list for each in exports.variables(string) if each not in result result.push(each) ) if result.length > 0 entry.filter_variables = true else entry.filter_variables = false return result find_variables: (har) -> result = [] for entry in har.log.entries for each in @.variables_in_entry entry result.push each return result return exports
97156
# vim: set et sw=2 ts=2 sts=2 ff=unix fenc=utf8: # Author: Binux<<EMAIL>> # http://binux.me # Created on 2014-08-02 10:07:33 window.jinja_globals = ['md5','quote_chinese','utf8','unicode','timestamp','random','date_time','is_num','add','sub','multiply','divide'] jinja_globals = window.jinja_globals Array.prototype.some ?= (f) -> (return true if f x) for x in @ return false Array.prototype.every ?= (f) -> (return false if not f x) for x in @ return true define (require, exports, module) -> utils = require('/static/utils') xhr = (har) -> for entry in har.log.entries if (h for h in entry.request.headers when h.name == 'X-Requested-With' and h.value == 'XMLHttpRequest').length > 0 entry.filter_xhr = true return har mime_type = (har) -> for entry in har.log.entries mt = entry.response?.content?.mimeType entry.filter_mimeType = switch when not mt then 'other' when mt.indexOf('audio') == 0 then 'media' when mt.indexOf('image') == 0 then 'image' when mt.indexOf('javascript') != -1 then 'javascript' when mt in ['text/html', ] then 'document' when mt in ['text/css', 'application/x-pointplus', ] then 'style' when mt.indexOf('application') == 0 then 'media' else 'other' return har analyze_cookies = (har) -> # analyze where cookie from cookie_jar = new utils.CookieJar() for entry in har.log.entries cookies = {} for cookie in cookie_jar.getCookiesSync(entry.request.url, {now: new Date(entry.startedDateTime)}) cookies[cookie.key] = cookie.value for cookie in entry.request.cookies cookie.checked = false if cookie.name of cookies if cookie.value == cookies[cookie.name] cookie.from_session = true entry.filter_from_session = true else cookie.cookie_changed = true entry.filter_cookie_changed = true #cookie_jar.setCookieSync(utils.Cookie.fromJSON(angular.toJson({ #key: cookie.name #value: cookie.value #path: '/' #})), entry.request.url) else cookie.cookie_added = true entry.filter_cookie_added = true #cookie_jar.setCookieSync(utils.Cookie.fromJSON(angular.toJson({ #key: cookie.name #value: cookie.value #path: '/' #})), entry.request.url) # update cookie from response for header in (h for h in entry.response?.headers when h.name.toLowerCase() == 'set-cookie') entry.filter_set_cookie = true try cookie_jar.setCookieSync(header.value, entry.request.url, {now: new Date(entry.startedDateTime)}) catch error console.error(error) return har sort = (har) -> har.log.entries = har.log.entries.sort((a, b) -> if a.pageref > b.pageref 1 else if a.pageref < b.pageref -1 else if a.startedDateTime > b.startedDateTime 1 else if a.startedDateTime < b.startedDateTime -1 else 0 ) return har headers = (har) -> to_remove_headers = ['x-devtools-emulate-network-conditions-client-id', 'cookie', 'host', 'content-length', ] for entry in har.log.entries for header, i in entry.request.headers if header.name.toLowerCase() not in to_remove_headers header.checked = true else header.checked = false return har post_data = (har) -> for entry in har.log.entries if not entry.request.postData?.text continue if not (entry.request.postData?.mimeType?.toLowerCase().indexOf("application/x-www-form-urlencoded") == 0) entry.request.postData.params = undefined continue result = [] try for key, value of utils.querystring_parse(entry.request.postData.text) result.push({name: key, value: value}) entry.request.postData.params = result catch error console.error(error) entry.request.postData.params = undefined continue return har replace_variables = (har, variables) -> variables_vk = {} for k, v of variables if k?.length and v?.length variables_vk[v] = k #console.log variables_vk, variables # url for entry in har.log.entries try url = utils.url_parse(entry.request.url, true) catch error continue changed = false for key, value of url.query if value of variables_vk url.query[key] = "{{ #{variables_vk[value]} }}" changed = true if changed query = utils.querystring_unparse_with_variables(url.query) url.search = "?#{query}" if query entry.request.url = utils.url_unparse(url) entry.request.queryString = utils.dict2list(url.query) # post data for entry in har.log.entries if not entry.request.postData?.params? continue changed = false for each in entry.request.postData.params if each.value of variables_vk each.value = "{{ #{variables_vk[each.value]} }}" changed = true if changed obj = utils.list2dict(entry.request.postData.params) entry.request.postData.text = utils.querystring_unparse_with_variables(obj) return har rm_content = (har) -> for entry in har.log.entries if entry.response?.content?.text? entry.response?.content.text = undefined return har exports = analyze: (har, variables={}) -> if har.log replace_variables((xhr mime_type analyze_cookies headers sort post_data rm_content har), variables) else har recommend_default: (har) -> domain = null for entry in har.log.entries if not domain domain = utils.get_domain(entry.request.url) if exports.variables_in_entry(entry).length > 0 entry.recommend = true else if domain != utils.get_domain(entry.request.url) entry.recommend = false else if entry.response?.status in [304, 0] entry.recommend = false else if entry.response?.status // 100 == 3 entry.recommend = true else if entry.response?.cookies?.length > 0 entry.recommend = true else if entry.request.method == 'POST' entry.recommend = true else entry.recommend = false return har recommend: (har) -> for entry in har.log.entries entry.recommend = if entry.checked then true else false checked = (e for e in har.log.entries when e.checked) if checked.length == 0 return exports.recommend_default(har) related_cookies = [] for entry in checked for cookie in entry.request.cookies related_cookies.push(cookie.name) started = false for entry in har.log.entries by -1 started = entry.checked if not started if not started continue if not entry.response?.cookies continue start_time = new Date(entry.startedDateTime) set_cookie = (cookie.name for cookie in entry.response?.cookies when not cookie.expires or (new Date(cookie.expires)) > start_time) _related_cookies = (c for c in related_cookies when c not in set_cookie) if related_cookies.length > _related_cookies.length entry.recommend = true related_cookies = _related_cookies # add pre request cookie for cookie in entry.request.cookies related_cookies.push(cookie.name) return har variables: (string) -> re = /{{\s*([\w]+)[^}]*?\s*}}/g while m = re.exec(string) if jQuery.inArray(m[1], jinja_globals) < 0 m[1] variables_in_entry: (entry) -> result = [] [ [entry.request.url, ] (h.name for h in entry.request.headers when h.checked) (h.value for h in entry.request.headers when h.checked) (c.name for c in entry.request.cookies when c.checked) (c.value for c in entry.request.cookies when c.checked) [entry.request.postData?.text,] ].map((list) -> for string in list for each in exports.variables(string) if each not in result result.push(each) ) if result.length > 0 entry.filter_variables = true else entry.filter_variables = false return result find_variables: (har) -> result = [] for entry in har.log.entries for each in @.variables_in_entry entry result.push each return result return exports
true
# vim: set et sw=2 ts=2 sts=2 ff=unix fenc=utf8: # Author: Binux<PI:EMAIL:<EMAIL>END_PI> # http://binux.me # Created on 2014-08-02 10:07:33 window.jinja_globals = ['md5','quote_chinese','utf8','unicode','timestamp','random','date_time','is_num','add','sub','multiply','divide'] jinja_globals = window.jinja_globals Array.prototype.some ?= (f) -> (return true if f x) for x in @ return false Array.prototype.every ?= (f) -> (return false if not f x) for x in @ return true define (require, exports, module) -> utils = require('/static/utils') xhr = (har) -> for entry in har.log.entries if (h for h in entry.request.headers when h.name == 'X-Requested-With' and h.value == 'XMLHttpRequest').length > 0 entry.filter_xhr = true return har mime_type = (har) -> for entry in har.log.entries mt = entry.response?.content?.mimeType entry.filter_mimeType = switch when not mt then 'other' when mt.indexOf('audio') == 0 then 'media' when mt.indexOf('image') == 0 then 'image' when mt.indexOf('javascript') != -1 then 'javascript' when mt in ['text/html', ] then 'document' when mt in ['text/css', 'application/x-pointplus', ] then 'style' when mt.indexOf('application') == 0 then 'media' else 'other' return har analyze_cookies = (har) -> # analyze where cookie from cookie_jar = new utils.CookieJar() for entry in har.log.entries cookies = {} for cookie in cookie_jar.getCookiesSync(entry.request.url, {now: new Date(entry.startedDateTime)}) cookies[cookie.key] = cookie.value for cookie in entry.request.cookies cookie.checked = false if cookie.name of cookies if cookie.value == cookies[cookie.name] cookie.from_session = true entry.filter_from_session = true else cookie.cookie_changed = true entry.filter_cookie_changed = true #cookie_jar.setCookieSync(utils.Cookie.fromJSON(angular.toJson({ #key: cookie.name #value: cookie.value #path: '/' #})), entry.request.url) else cookie.cookie_added = true entry.filter_cookie_added = true #cookie_jar.setCookieSync(utils.Cookie.fromJSON(angular.toJson({ #key: cookie.name #value: cookie.value #path: '/' #})), entry.request.url) # update cookie from response for header in (h for h in entry.response?.headers when h.name.toLowerCase() == 'set-cookie') entry.filter_set_cookie = true try cookie_jar.setCookieSync(header.value, entry.request.url, {now: new Date(entry.startedDateTime)}) catch error console.error(error) return har sort = (har) -> har.log.entries = har.log.entries.sort((a, b) -> if a.pageref > b.pageref 1 else if a.pageref < b.pageref -1 else if a.startedDateTime > b.startedDateTime 1 else if a.startedDateTime < b.startedDateTime -1 else 0 ) return har headers = (har) -> to_remove_headers = ['x-devtools-emulate-network-conditions-client-id', 'cookie', 'host', 'content-length', ] for entry in har.log.entries for header, i in entry.request.headers if header.name.toLowerCase() not in to_remove_headers header.checked = true else header.checked = false return har post_data = (har) -> for entry in har.log.entries if not entry.request.postData?.text continue if not (entry.request.postData?.mimeType?.toLowerCase().indexOf("application/x-www-form-urlencoded") == 0) entry.request.postData.params = undefined continue result = [] try for key, value of utils.querystring_parse(entry.request.postData.text) result.push({name: key, value: value}) entry.request.postData.params = result catch error console.error(error) entry.request.postData.params = undefined continue return har replace_variables = (har, variables) -> variables_vk = {} for k, v of variables if k?.length and v?.length variables_vk[v] = k #console.log variables_vk, variables # url for entry in har.log.entries try url = utils.url_parse(entry.request.url, true) catch error continue changed = false for key, value of url.query if value of variables_vk url.query[key] = "{{ #{variables_vk[value]} }}" changed = true if changed query = utils.querystring_unparse_with_variables(url.query) url.search = "?#{query}" if query entry.request.url = utils.url_unparse(url) entry.request.queryString = utils.dict2list(url.query) # post data for entry in har.log.entries if not entry.request.postData?.params? continue changed = false for each in entry.request.postData.params if each.value of variables_vk each.value = "{{ #{variables_vk[each.value]} }}" changed = true if changed obj = utils.list2dict(entry.request.postData.params) entry.request.postData.text = utils.querystring_unparse_with_variables(obj) return har rm_content = (har) -> for entry in har.log.entries if entry.response?.content?.text? entry.response?.content.text = undefined return har exports = analyze: (har, variables={}) -> if har.log replace_variables((xhr mime_type analyze_cookies headers sort post_data rm_content har), variables) else har recommend_default: (har) -> domain = null for entry in har.log.entries if not domain domain = utils.get_domain(entry.request.url) if exports.variables_in_entry(entry).length > 0 entry.recommend = true else if domain != utils.get_domain(entry.request.url) entry.recommend = false else if entry.response?.status in [304, 0] entry.recommend = false else if entry.response?.status // 100 == 3 entry.recommend = true else if entry.response?.cookies?.length > 0 entry.recommend = true else if entry.request.method == 'POST' entry.recommend = true else entry.recommend = false return har recommend: (har) -> for entry in har.log.entries entry.recommend = if entry.checked then true else false checked = (e for e in har.log.entries when e.checked) if checked.length == 0 return exports.recommend_default(har) related_cookies = [] for entry in checked for cookie in entry.request.cookies related_cookies.push(cookie.name) started = false for entry in har.log.entries by -1 started = entry.checked if not started if not started continue if not entry.response?.cookies continue start_time = new Date(entry.startedDateTime) set_cookie = (cookie.name for cookie in entry.response?.cookies when not cookie.expires or (new Date(cookie.expires)) > start_time) _related_cookies = (c for c in related_cookies when c not in set_cookie) if related_cookies.length > _related_cookies.length entry.recommend = true related_cookies = _related_cookies # add pre request cookie for cookie in entry.request.cookies related_cookies.push(cookie.name) return har variables: (string) -> re = /{{\s*([\w]+)[^}]*?\s*}}/g while m = re.exec(string) if jQuery.inArray(m[1], jinja_globals) < 0 m[1] variables_in_entry: (entry) -> result = [] [ [entry.request.url, ] (h.name for h in entry.request.headers when h.checked) (h.value for h in entry.request.headers when h.checked) (c.name for c in entry.request.cookies when c.checked) (c.value for c in entry.request.cookies when c.checked) [entry.request.postData?.text,] ].map((list) -> for string in list for each in exports.variables(string) if each not in result result.push(each) ) if result.length > 0 entry.filter_variables = true else entry.filter_variables = false return result find_variables: (har) -> result = [] for entry in har.log.entries for each in @.variables_in_entry entry result.push each return result return exports
[ { "context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.", "end": 215, "score": 0.9998579025268555, "start": 198, "tag": "NAME", "value": "Benjamin Blundell" }, { "context": " PXL.js\n ...
src/util/red_black_tree.coffee
OniDaito/pxljs
1
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js Benjamin Blundell - ben@pxljs.com http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details An implementation of the Red Black Tree from the Javascript Implementation found at https://github.com/gorhill/Javascript-Voronoi/blob/master/rhill-voronoi-core.js ### ###RedBlackTree### class RedBlackTree constructor : () -> @root = null insertSuccessor : (node, successor) -> if node successor.rbPrevious = node successor.rbNext = node.rbNext if node.rbNext node.rbNext.rbPrevious = successor node.rbNext = successor if node.rbRight node = node.rbRight while node.rbLeft node = node.rbLeft node.rbLeft = successor else node.rbRight = successor parent = node else if @root node = @getFirst(@root) successor.rbPrevious = null successor.rbNext = node node.rbPrevious = successor node.rbLeft = successor parent = node else successor.rbPrevious = successor.rbNext = null @root = successor parent = null successor.rbLeft = successor.rbRight = null successor.rbParent = parent successor.rbRed = true grandpa uncle node = successor while parent and parent.rbRed grandpa = parent.rbParent if parent is grandpa.rbLeft uncle = grandpa.rbRight if uncle and uncle.rbRed parent.rbRed = uncle.rbRed = false grandpa.rbRed = true node = grandpa else if node is parent.rbRight @rotateLeft(parent) node = parent parent = node.rbParent parent.rbRed = false grandpa.rbRed = true @rotateRight(grandpa) else uncle = grandpa.rbLeft if (uncle && uncle.rbRed) parent.rbRed = uncle.rbRed = false grandpa.rbRed = true node = grandpa else if (node is parent.rbLeft) @rotateRight(parent) node = parent parent = node.rbParent parent.rbRed = false grandpa.rbRed = true @rotateLeft grandpa parent = node.rbParent @root.rbRed = false removeNode : (node) -> if node.rbNext node.rbNext.rbPrevious = node.rbPrevious if node.rbPrevious node.rbPrevious.rbNext = node.rbNext node.rbNext = node.rbPrevious = null parent = node.rbParent left = node.rbLeft right = node.rbRight next if !left next = right else if !right next = left else next = @getFirst right if parent if parent.rbLeft is node parent.rbLeft = next else parent.rbRight = next else @root = next # enforce red-black rules isRed if left and right isRed = next.rbRed next.rbRed = node.rbRed next.rbLeft = left left.rbParent = next if next isnt right parent = next.rbParent next.rbParent = node.rbParent node = next.rbRight parent.rbLeft = node next.rbRight = right right.rbParent = next else next.rbParent = parent parent = next node = next.rbRight else isRed = node.rbRed node = next if node node.rbParent = parent if isRed return if node and node.rbRed node.rbRed = false return sibling loop if node is @root break if node is parent.rbLeft sibling = parent.rbRight if sibling.rbRed sibling.rbRed = false parent.rbRed = true @rotateLeft(parent) sibling = parent.rbRight if (sibling.rbLeft and sibling.rbLeft.rbRed) or (sibling.rbRight and sibling.rbRight.rbRed) if !sibling.rbRight or !sibling.rbRight.rbRed sibling.rbLeft.rbRed = false sibling.rbRed = true @rotateRight sibling sibling = parent.rbRight sibling.rbRed = parent.rbRed parent.rbRed = sibling.rbRight.rbRed = false @rotateLeft parent node = @root break else sibling = parent.rbLeft if (sibling.rbRed) sibling.rbRed = false parent.rbRed = true @rotateRight parent sibling = parent.rbLeft if (sibling.rbLeft and sibling.rbLeft.rbRed) or (sibling.rbRight and sibling.rbRight.rbRed) if !sibling.rbLeft or !sibling.rbLeft.rbRed sibling.rbRight.rbRed = false sibling.rbRed = true @rotateLeft sibling sibling = parent.rbLeft sibling.rbRed = parent.rbRed parent.rbRed = sibling.rbLeft.rbRed = false @rotateRight parent node = @root break sibling.rbRed = true node = parent parent = parent.rbParent break if node.rbRed if node node.rbRed = false rotateLeft : (node) -> p = node q = node.rbRight parent = p.rbParent if parent if parent.rbLeft is p parent.rbLeft = q else parent.rbRight = q else @root = q q.rbParent = parent p.rbParent = q p.rbRight = q.rbLeft if p.rbRight p.rbRight.rbParent = p q.rbLeft = p rotateRight : (node) -> p = node q = node.rbLeft parent = p.rbParent; if parent if parent.rbLeft is p parent.rbLeft = q else parent.rbRight = q else @root = q q.rbParent = parent p.rbParent = q p.rbLeft = q.rbRight if p.rbLeft p.rbLeft.rbParent = p q.rbRight = p getFirst : (node) -> while node.rbLeft node = node.rbLeft node getLast : (node) -> while node.rbRight node = node.rbRight node module.exports = RedBlackTree : RedBlackTree
179529
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js <NAME> - <EMAIL> http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details An implementation of the Red Black Tree from the Javascript Implementation found at https://github.com/gorhill/Javascript-Voronoi/blob/master/rhill-voronoi-core.js ### ###RedBlackTree### class RedBlackTree constructor : () -> @root = null insertSuccessor : (node, successor) -> if node successor.rbPrevious = node successor.rbNext = node.rbNext if node.rbNext node.rbNext.rbPrevious = successor node.rbNext = successor if node.rbRight node = node.rbRight while node.rbLeft node = node.rbLeft node.rbLeft = successor else node.rbRight = successor parent = node else if @root node = @getFirst(@root) successor.rbPrevious = null successor.rbNext = node node.rbPrevious = successor node.rbLeft = successor parent = node else successor.rbPrevious = successor.rbNext = null @root = successor parent = null successor.rbLeft = successor.rbRight = null successor.rbParent = parent successor.rbRed = true grandpa uncle node = successor while parent and parent.rbRed grandpa = parent.rbParent if parent is grandpa.rbLeft uncle = grandpa.rbRight if uncle and uncle.rbRed parent.rbRed = uncle.rbRed = false grandpa.rbRed = true node = grandpa else if node is parent.rbRight @rotateLeft(parent) node = parent parent = node.rbParent parent.rbRed = false grandpa.rbRed = true @rotateRight(grandpa) else uncle = grandpa.rbLeft if (uncle && uncle.rbRed) parent.rbRed = uncle.rbRed = false grandpa.rbRed = true node = grandpa else if (node is parent.rbLeft) @rotateRight(parent) node = parent parent = node.rbParent parent.rbRed = false grandpa.rbRed = true @rotateLeft grandpa parent = node.rbParent @root.rbRed = false removeNode : (node) -> if node.rbNext node.rbNext.rbPrevious = node.rbPrevious if node.rbPrevious node.rbPrevious.rbNext = node.rbNext node.rbNext = node.rbPrevious = null parent = node.rbParent left = node.rbLeft right = node.rbRight next if !left next = right else if !right next = left else next = @getFirst right if parent if parent.rbLeft is node parent.rbLeft = next else parent.rbRight = next else @root = next # enforce red-black rules isRed if left and right isRed = next.rbRed next.rbRed = node.rbRed next.rbLeft = left left.rbParent = next if next isnt right parent = next.rbParent next.rbParent = node.rbParent node = next.rbRight parent.rbLeft = node next.rbRight = right right.rbParent = next else next.rbParent = parent parent = next node = next.rbRight else isRed = node.rbRed node = next if node node.rbParent = parent if isRed return if node and node.rbRed node.rbRed = false return sibling loop if node is @root break if node is parent.rbLeft sibling = parent.rbRight if sibling.rbRed sibling.rbRed = false parent.rbRed = true @rotateLeft(parent) sibling = parent.rbRight if (sibling.rbLeft and sibling.rbLeft.rbRed) or (sibling.rbRight and sibling.rbRight.rbRed) if !sibling.rbRight or !sibling.rbRight.rbRed sibling.rbLeft.rbRed = false sibling.rbRed = true @rotateRight sibling sibling = parent.rbRight sibling.rbRed = parent.rbRed parent.rbRed = sibling.rbRight.rbRed = false @rotateLeft parent node = @root break else sibling = parent.rbLeft if (sibling.rbRed) sibling.rbRed = false parent.rbRed = true @rotateRight parent sibling = parent.rbLeft if (sibling.rbLeft and sibling.rbLeft.rbRed) or (sibling.rbRight and sibling.rbRight.rbRed) if !sibling.rbLeft or !sibling.rbLeft.rbRed sibling.rbRight.rbRed = false sibling.rbRed = true @rotateLeft sibling sibling = parent.rbLeft sibling.rbRed = parent.rbRed parent.rbRed = sibling.rbLeft.rbRed = false @rotateRight parent node = @root break sibling.rbRed = true node = parent parent = parent.rbParent break if node.rbRed if node node.rbRed = false rotateLeft : (node) -> p = node q = node.rbRight parent = p.rbParent if parent if parent.rbLeft is p parent.rbLeft = q else parent.rbRight = q else @root = q q.rbParent = parent p.rbParent = q p.rbRight = q.rbLeft if p.rbRight p.rbRight.rbParent = p q.rbLeft = p rotateRight : (node) -> p = node q = node.rbLeft parent = p.rbParent; if parent if parent.rbLeft is p parent.rbLeft = q else parent.rbRight = q else @root = q q.rbParent = parent p.rbParent = q p.rbLeft = q.rbRight if p.rbLeft p.rbLeft.rbParent = p q.rbRight = p getFirst : (node) -> while node.rbLeft node = node.rbLeft node getLast : (node) -> while node.rbRight node = node.rbRight node module.exports = RedBlackTree : RedBlackTree
true
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details An implementation of the Red Black Tree from the Javascript Implementation found at https://github.com/gorhill/Javascript-Voronoi/blob/master/rhill-voronoi-core.js ### ###RedBlackTree### class RedBlackTree constructor : () -> @root = null insertSuccessor : (node, successor) -> if node successor.rbPrevious = node successor.rbNext = node.rbNext if node.rbNext node.rbNext.rbPrevious = successor node.rbNext = successor if node.rbRight node = node.rbRight while node.rbLeft node = node.rbLeft node.rbLeft = successor else node.rbRight = successor parent = node else if @root node = @getFirst(@root) successor.rbPrevious = null successor.rbNext = node node.rbPrevious = successor node.rbLeft = successor parent = node else successor.rbPrevious = successor.rbNext = null @root = successor parent = null successor.rbLeft = successor.rbRight = null successor.rbParent = parent successor.rbRed = true grandpa uncle node = successor while parent and parent.rbRed grandpa = parent.rbParent if parent is grandpa.rbLeft uncle = grandpa.rbRight if uncle and uncle.rbRed parent.rbRed = uncle.rbRed = false grandpa.rbRed = true node = grandpa else if node is parent.rbRight @rotateLeft(parent) node = parent parent = node.rbParent parent.rbRed = false grandpa.rbRed = true @rotateRight(grandpa) else uncle = grandpa.rbLeft if (uncle && uncle.rbRed) parent.rbRed = uncle.rbRed = false grandpa.rbRed = true node = grandpa else if (node is parent.rbLeft) @rotateRight(parent) node = parent parent = node.rbParent parent.rbRed = false grandpa.rbRed = true @rotateLeft grandpa parent = node.rbParent @root.rbRed = false removeNode : (node) -> if node.rbNext node.rbNext.rbPrevious = node.rbPrevious if node.rbPrevious node.rbPrevious.rbNext = node.rbNext node.rbNext = node.rbPrevious = null parent = node.rbParent left = node.rbLeft right = node.rbRight next if !left next = right else if !right next = left else next = @getFirst right if parent if parent.rbLeft is node parent.rbLeft = next else parent.rbRight = next else @root = next # enforce red-black rules isRed if left and right isRed = next.rbRed next.rbRed = node.rbRed next.rbLeft = left left.rbParent = next if next isnt right parent = next.rbParent next.rbParent = node.rbParent node = next.rbRight parent.rbLeft = node next.rbRight = right right.rbParent = next else next.rbParent = parent parent = next node = next.rbRight else isRed = node.rbRed node = next if node node.rbParent = parent if isRed return if node and node.rbRed node.rbRed = false return sibling loop if node is @root break if node is parent.rbLeft sibling = parent.rbRight if sibling.rbRed sibling.rbRed = false parent.rbRed = true @rotateLeft(parent) sibling = parent.rbRight if (sibling.rbLeft and sibling.rbLeft.rbRed) or (sibling.rbRight and sibling.rbRight.rbRed) if !sibling.rbRight or !sibling.rbRight.rbRed sibling.rbLeft.rbRed = false sibling.rbRed = true @rotateRight sibling sibling = parent.rbRight sibling.rbRed = parent.rbRed parent.rbRed = sibling.rbRight.rbRed = false @rotateLeft parent node = @root break else sibling = parent.rbLeft if (sibling.rbRed) sibling.rbRed = false parent.rbRed = true @rotateRight parent sibling = parent.rbLeft if (sibling.rbLeft and sibling.rbLeft.rbRed) or (sibling.rbRight and sibling.rbRight.rbRed) if !sibling.rbLeft or !sibling.rbLeft.rbRed sibling.rbRight.rbRed = false sibling.rbRed = true @rotateLeft sibling sibling = parent.rbLeft sibling.rbRed = parent.rbRed parent.rbRed = sibling.rbLeft.rbRed = false @rotateRight parent node = @root break sibling.rbRed = true node = parent parent = parent.rbParent break if node.rbRed if node node.rbRed = false rotateLeft : (node) -> p = node q = node.rbRight parent = p.rbParent if parent if parent.rbLeft is p parent.rbLeft = q else parent.rbRight = q else @root = q q.rbParent = parent p.rbParent = q p.rbRight = q.rbLeft if p.rbRight p.rbRight.rbParent = p q.rbLeft = p rotateRight : (node) -> p = node q = node.rbLeft parent = p.rbParent; if parent if parent.rbLeft is p parent.rbLeft = q else parent.rbRight = q else @root = q q.rbParent = parent p.rbParent = q p.rbLeft = q.rbRight if p.rbLeft p.rbLeft.rbParent = p q.rbRight = p getFirst : (node) -> while node.rbLeft node = node.rbLeft node getLast : (node) -> while node.rbRight node = node.rbRight node module.exports = RedBlackTree : RedBlackTree
[ { "context": "chema.properties.email\n ]\n }\n password: User.schema.properties.password\n }\n required: ['emailOrUsername', 'password']\n}", "end": 5463, "score": 0.9990559816360474, "start": 5432, "tag": "PASSWORD", "value": "User.schema.properties.password" } ]
app/views/core/AuthModal.coffee
mradziwo/codecombat
0
require('app/styles/modal/auth-modal.sass') ModalView = require 'views/core/ModalView' template = require 'templates/core/auth-modal' forms = require 'core/forms' User = require 'models/User' errors = require 'core/errors' RecoverModal = require 'views/core/RecoverModal' storage = require 'core/storage' module.exports = class AuthModal extends ModalView id: 'auth-modal' template: template events: 'click #switch-to-signup-btn': 'onSignupInstead' 'submit form': 'onSubmitForm' 'keyup #name': 'onNameChange' 'click #gplus-login-btn': 'onClickGPlusLoginButton' 'click #facebook-login-btn': 'onClickFacebookLoginButton' 'click #close-modal': 'hide' 'click [data-toggle="coco-modal"][data-target="core/RecoverModal"]': 'openRecoverModal' # Initialization initialize: (options={}) -> @previousFormInputs = options.initialValues or {} @previousFormInputs.emailOrUsername ?= @previousFormInputs.email or @previousFormInputs.username if me.useSocialSignOn() # TODO: Switch to promises and state, rather than using defer to hackily enable buttons after render application.gplusHandler.loadAPI({ success: => _.defer => @$('#gplus-login-btn').attr('disabled', false) }) application.facebookHandler.loadAPI({ success: => _.defer => @$('#facebook-login-btn').attr('disabled', false) }) @subModalContinue = options.subModalContinue afterRender: -> super() @playSound 'game-menu-open' afterInsert: -> super() _.delay (=> $('input:visible:first', @$el).focus()), 500 onSignupInstead: (e) -> CreateAccountModal = require('./CreateAccountModal') modal = new CreateAccountModal({initialValues: forms.formToObject @$el, @subModalContinue}) currentView.openModalView(modal) onSubmitForm: (e) -> @playSound 'menu-button-click' e.preventDefault() forms.clearFormAlerts(@$el) @$('#unknown-error-alert').addClass('hide') userObject = forms.formToObject @$el res = tv4.validateMultiple userObject, formSchema return forms.applyErrorsToForm(@$el, res.errors) unless res.valid new Promise(me.loginPasswordUser(userObject.emailOrUsername, userObject.password).then) .then(=> return application.tracker.identify() ) .then(=> if window.nextURL window.location.href = window.nextURL else loginNavigate(@subModalContinue) ) .catch((jqxhr) => showingError = false if jqxhr.status is 401 errorID = jqxhr.responseJSON.errorID if errorID is 'not-found' forms.setErrorToProperty(@$el, 'emailOrUsername', $.i18n.t('loading_error.user_not_found')) showingError = true if errorID is 'wrong-password' forms.setErrorToProperty(@$el, 'password', $.i18n.t('account_settings.wrong_password')) showingError = true if not showingError @$('#unknown-error-alert').removeClass('hide') ) # Google Plus onClickGPlusLoginButton: -> btn = @$('#gplus-login-btn') application.gplusHandler.connect({ context: @ success: -> btn.find('.sign-in-blurb').text($.i18n.t('login.logging_in')) btn.attr('disabled', true) application.gplusHandler.loadPerson({ context: @ success: (gplusAttrs) -> existingUser = new User() existingUser.fetchGPlusUser(gplusAttrs.gplusID, { success: => me.loginGPlusUser(gplusAttrs.gplusID, { success: => application.tracker.identify().then(=> loginNavigate(@subModalContinue) ) error: @onGPlusLoginError }) error: @onGPlusLoginError }) }) }) onGPlusLoginError: => btn = @$('#gplus-login-btn') btn.find('.sign-in-blurb').text($.i18n.t('login.sign_in_with_gplus')) btn.attr('disabled', false) errors.showNotyNetworkError(arguments...) # Facebook onClickFacebookLoginButton: -> btn = @$('#facebook-login-btn') application.facebookHandler.connect({ context: @ success: -> btn.find('.sign-in-blurb').text($.i18n.t('login.logging_in')) btn.attr('disabled', true) application.facebookHandler.loadPerson({ context: @ success: (facebookAttrs) -> existingUser = new User() existingUser.fetchFacebookUser(facebookAttrs.facebookID, { success: => me.loginFacebookUser(facebookAttrs.facebookID, { success: => application.tracker.identify().then(=> loginNavigate(@subModalContinue) ) error: @onFacebookLoginError }) error: @onFacebookLoginError }) }) }) onFacebookLoginError: => btn = @$('#facebook-login-btn') btn.find('.sign-in-blurb').text($.i18n.t('login.sign_in_with_facebook')) btn.attr('disabled', false) errors.showNotyNetworkError(arguments...) openRecoverModal: (e) -> e.stopPropagation() @openModalView new RecoverModal() onHidden: -> super() @playSound 'game-menu-close' formSchema = { type: 'object' properties: { emailOrUsername: { $or: [ User.schema.properties.name User.schema.properties.email ] } password: User.schema.properties.password } required: ['emailOrUsername', 'password'] } loginNavigate = (subModalContinue) -> if not me.isAdmin() if me.isStudent() application.router.navigate('/students', { trigger: true }) else if me.isTeacher() if me.isSchoolAdmin() application.router.navigate('/school-administrator', { trigger: true }) else application.router.navigate('/teachers/classes', { trigger: true }) else if subModalContinue storage.save('sub-modal-continue', subModalContinue) window.location.reload()
10098
require('app/styles/modal/auth-modal.sass') ModalView = require 'views/core/ModalView' template = require 'templates/core/auth-modal' forms = require 'core/forms' User = require 'models/User' errors = require 'core/errors' RecoverModal = require 'views/core/RecoverModal' storage = require 'core/storage' module.exports = class AuthModal extends ModalView id: 'auth-modal' template: template events: 'click #switch-to-signup-btn': 'onSignupInstead' 'submit form': 'onSubmitForm' 'keyup #name': 'onNameChange' 'click #gplus-login-btn': 'onClickGPlusLoginButton' 'click #facebook-login-btn': 'onClickFacebookLoginButton' 'click #close-modal': 'hide' 'click [data-toggle="coco-modal"][data-target="core/RecoverModal"]': 'openRecoverModal' # Initialization initialize: (options={}) -> @previousFormInputs = options.initialValues or {} @previousFormInputs.emailOrUsername ?= @previousFormInputs.email or @previousFormInputs.username if me.useSocialSignOn() # TODO: Switch to promises and state, rather than using defer to hackily enable buttons after render application.gplusHandler.loadAPI({ success: => _.defer => @$('#gplus-login-btn').attr('disabled', false) }) application.facebookHandler.loadAPI({ success: => _.defer => @$('#facebook-login-btn').attr('disabled', false) }) @subModalContinue = options.subModalContinue afterRender: -> super() @playSound 'game-menu-open' afterInsert: -> super() _.delay (=> $('input:visible:first', @$el).focus()), 500 onSignupInstead: (e) -> CreateAccountModal = require('./CreateAccountModal') modal = new CreateAccountModal({initialValues: forms.formToObject @$el, @subModalContinue}) currentView.openModalView(modal) onSubmitForm: (e) -> @playSound 'menu-button-click' e.preventDefault() forms.clearFormAlerts(@$el) @$('#unknown-error-alert').addClass('hide') userObject = forms.formToObject @$el res = tv4.validateMultiple userObject, formSchema return forms.applyErrorsToForm(@$el, res.errors) unless res.valid new Promise(me.loginPasswordUser(userObject.emailOrUsername, userObject.password).then) .then(=> return application.tracker.identify() ) .then(=> if window.nextURL window.location.href = window.nextURL else loginNavigate(@subModalContinue) ) .catch((jqxhr) => showingError = false if jqxhr.status is 401 errorID = jqxhr.responseJSON.errorID if errorID is 'not-found' forms.setErrorToProperty(@$el, 'emailOrUsername', $.i18n.t('loading_error.user_not_found')) showingError = true if errorID is 'wrong-password' forms.setErrorToProperty(@$el, 'password', $.i18n.t('account_settings.wrong_password')) showingError = true if not showingError @$('#unknown-error-alert').removeClass('hide') ) # Google Plus onClickGPlusLoginButton: -> btn = @$('#gplus-login-btn') application.gplusHandler.connect({ context: @ success: -> btn.find('.sign-in-blurb').text($.i18n.t('login.logging_in')) btn.attr('disabled', true) application.gplusHandler.loadPerson({ context: @ success: (gplusAttrs) -> existingUser = new User() existingUser.fetchGPlusUser(gplusAttrs.gplusID, { success: => me.loginGPlusUser(gplusAttrs.gplusID, { success: => application.tracker.identify().then(=> loginNavigate(@subModalContinue) ) error: @onGPlusLoginError }) error: @onGPlusLoginError }) }) }) onGPlusLoginError: => btn = @$('#gplus-login-btn') btn.find('.sign-in-blurb').text($.i18n.t('login.sign_in_with_gplus')) btn.attr('disabled', false) errors.showNotyNetworkError(arguments...) # Facebook onClickFacebookLoginButton: -> btn = @$('#facebook-login-btn') application.facebookHandler.connect({ context: @ success: -> btn.find('.sign-in-blurb').text($.i18n.t('login.logging_in')) btn.attr('disabled', true) application.facebookHandler.loadPerson({ context: @ success: (facebookAttrs) -> existingUser = new User() existingUser.fetchFacebookUser(facebookAttrs.facebookID, { success: => me.loginFacebookUser(facebookAttrs.facebookID, { success: => application.tracker.identify().then(=> loginNavigate(@subModalContinue) ) error: @onFacebookLoginError }) error: @onFacebookLoginError }) }) }) onFacebookLoginError: => btn = @$('#facebook-login-btn') btn.find('.sign-in-blurb').text($.i18n.t('login.sign_in_with_facebook')) btn.attr('disabled', false) errors.showNotyNetworkError(arguments...) openRecoverModal: (e) -> e.stopPropagation() @openModalView new RecoverModal() onHidden: -> super() @playSound 'game-menu-close' formSchema = { type: 'object' properties: { emailOrUsername: { $or: [ User.schema.properties.name User.schema.properties.email ] } password: <PASSWORD> } required: ['emailOrUsername', 'password'] } loginNavigate = (subModalContinue) -> if not me.isAdmin() if me.isStudent() application.router.navigate('/students', { trigger: true }) else if me.isTeacher() if me.isSchoolAdmin() application.router.navigate('/school-administrator', { trigger: true }) else application.router.navigate('/teachers/classes', { trigger: true }) else if subModalContinue storage.save('sub-modal-continue', subModalContinue) window.location.reload()
true
require('app/styles/modal/auth-modal.sass') ModalView = require 'views/core/ModalView' template = require 'templates/core/auth-modal' forms = require 'core/forms' User = require 'models/User' errors = require 'core/errors' RecoverModal = require 'views/core/RecoverModal' storage = require 'core/storage' module.exports = class AuthModal extends ModalView id: 'auth-modal' template: template events: 'click #switch-to-signup-btn': 'onSignupInstead' 'submit form': 'onSubmitForm' 'keyup #name': 'onNameChange' 'click #gplus-login-btn': 'onClickGPlusLoginButton' 'click #facebook-login-btn': 'onClickFacebookLoginButton' 'click #close-modal': 'hide' 'click [data-toggle="coco-modal"][data-target="core/RecoverModal"]': 'openRecoverModal' # Initialization initialize: (options={}) -> @previousFormInputs = options.initialValues or {} @previousFormInputs.emailOrUsername ?= @previousFormInputs.email or @previousFormInputs.username if me.useSocialSignOn() # TODO: Switch to promises and state, rather than using defer to hackily enable buttons after render application.gplusHandler.loadAPI({ success: => _.defer => @$('#gplus-login-btn').attr('disabled', false) }) application.facebookHandler.loadAPI({ success: => _.defer => @$('#facebook-login-btn').attr('disabled', false) }) @subModalContinue = options.subModalContinue afterRender: -> super() @playSound 'game-menu-open' afterInsert: -> super() _.delay (=> $('input:visible:first', @$el).focus()), 500 onSignupInstead: (e) -> CreateAccountModal = require('./CreateAccountModal') modal = new CreateAccountModal({initialValues: forms.formToObject @$el, @subModalContinue}) currentView.openModalView(modal) onSubmitForm: (e) -> @playSound 'menu-button-click' e.preventDefault() forms.clearFormAlerts(@$el) @$('#unknown-error-alert').addClass('hide') userObject = forms.formToObject @$el res = tv4.validateMultiple userObject, formSchema return forms.applyErrorsToForm(@$el, res.errors) unless res.valid new Promise(me.loginPasswordUser(userObject.emailOrUsername, userObject.password).then) .then(=> return application.tracker.identify() ) .then(=> if window.nextURL window.location.href = window.nextURL else loginNavigate(@subModalContinue) ) .catch((jqxhr) => showingError = false if jqxhr.status is 401 errorID = jqxhr.responseJSON.errorID if errorID is 'not-found' forms.setErrorToProperty(@$el, 'emailOrUsername', $.i18n.t('loading_error.user_not_found')) showingError = true if errorID is 'wrong-password' forms.setErrorToProperty(@$el, 'password', $.i18n.t('account_settings.wrong_password')) showingError = true if not showingError @$('#unknown-error-alert').removeClass('hide') ) # Google Plus onClickGPlusLoginButton: -> btn = @$('#gplus-login-btn') application.gplusHandler.connect({ context: @ success: -> btn.find('.sign-in-blurb').text($.i18n.t('login.logging_in')) btn.attr('disabled', true) application.gplusHandler.loadPerson({ context: @ success: (gplusAttrs) -> existingUser = new User() existingUser.fetchGPlusUser(gplusAttrs.gplusID, { success: => me.loginGPlusUser(gplusAttrs.gplusID, { success: => application.tracker.identify().then(=> loginNavigate(@subModalContinue) ) error: @onGPlusLoginError }) error: @onGPlusLoginError }) }) }) onGPlusLoginError: => btn = @$('#gplus-login-btn') btn.find('.sign-in-blurb').text($.i18n.t('login.sign_in_with_gplus')) btn.attr('disabled', false) errors.showNotyNetworkError(arguments...) # Facebook onClickFacebookLoginButton: -> btn = @$('#facebook-login-btn') application.facebookHandler.connect({ context: @ success: -> btn.find('.sign-in-blurb').text($.i18n.t('login.logging_in')) btn.attr('disabled', true) application.facebookHandler.loadPerson({ context: @ success: (facebookAttrs) -> existingUser = new User() existingUser.fetchFacebookUser(facebookAttrs.facebookID, { success: => me.loginFacebookUser(facebookAttrs.facebookID, { success: => application.tracker.identify().then(=> loginNavigate(@subModalContinue) ) error: @onFacebookLoginError }) error: @onFacebookLoginError }) }) }) onFacebookLoginError: => btn = @$('#facebook-login-btn') btn.find('.sign-in-blurb').text($.i18n.t('login.sign_in_with_facebook')) btn.attr('disabled', false) errors.showNotyNetworkError(arguments...) openRecoverModal: (e) -> e.stopPropagation() @openModalView new RecoverModal() onHidden: -> super() @playSound 'game-menu-close' formSchema = { type: 'object' properties: { emailOrUsername: { $or: [ User.schema.properties.name User.schema.properties.email ] } password: PI:PASSWORD:<PASSWORD>END_PI } required: ['emailOrUsername', 'password'] } loginNavigate = (subModalContinue) -> if not me.isAdmin() if me.isStudent() application.router.navigate('/students', { trigger: true }) else if me.isTeacher() if me.isSchoolAdmin() application.router.navigate('/school-administrator', { trigger: true }) else application.router.navigate('/teachers/classes', { trigger: true }) else if subModalContinue storage.save('sub-modal-continue', subModalContinue) window.location.reload()
[ { "context": "forces spaces inside of object literals.\n# @author Jamund Ferguson\n###\n'use strict'\n\nastUtils = require '../eslint-a", "end": 102, "score": 0.9998694062232971, "start": 87, "tag": "NAME", "value": "Jamund Ferguson" } ]
src/rules/object-curly-spacing.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Disallows or enforces spaces inside of object literals. # @author Jamund Ferguson ### 'use strict' astUtils = require '../eslint-ast-utils' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce consistent spacing inside braces' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/object-curly-spacing' fixable: 'whitespace' schema: [ enum: ['always', 'never'] , type: 'object' properties: arraysInObjects: type: 'boolean' objectsInObjects: type: 'boolean' additionalProperties: no ] create: (context) -> spaced = context.options[0] is 'always' sourceCode = context.getSourceCode() ###* # Determines whether an option is set, relative to the spacing option. # If spaced is "always", then check whether option is set to false. # If spaced is "never", then check whether option is set to true. # @param {Object} option - The option to exclude. # @returns {boolean} Whether or not the property is excluded. ### isOptionSet = (option) -> if context.options[1] context.options[1][option] is not spaced else no options = { spaced arraysInObjectsException: isOptionSet 'arraysInObjects' objectsInObjectsException: isOptionSet 'objectsInObjects' } #-------------------------------------------------------------------------- # Helpers #-------------------------------------------------------------------------- ###* # Reports that there shouldn't be a space after the first token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportNoBeginningSpace = (node, token) -> context.report { node loc: token.loc.start message: "There should be no space after '{{token}}'." data: token: token.value fix: (fixer) -> nextToken = context.getSourceCode().getTokenAfter token fixer.removeRange [token.range[1], nextToken.range[0]] } ###* # Reports that there shouldn't be a space before the last token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportNoEndingSpace = (node, token) -> context.report { node loc: token.loc.start message: "There should be no space before '{{token}}'." data: token: token.value fix: (fixer) -> previousToken = context.getSourceCode().getTokenBefore token fixer.removeRange [previousToken.range[1], token.range[0]] } ###* # Reports that there should be a space after the first token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportRequiredBeginningSpace = (node, token) -> context.report { node loc: token.loc.start message: "A space is required after '{{token}}'." data: token: token.value fix: (fixer) -> fixer.insertTextAfter token, ' ' } ###* # Reports that there should be a space before the last token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportRequiredEndingSpace = (node, token) -> context.report { node loc: token.loc.start message: "A space is required before '{{token}}'." data: token: token.value fix: (fixer) -> fixer.insertTextBefore token, ' ' } ###* # Determines if spacing in curly braces is valid. # @param {ASTNode} node The AST node to check. # @param {Token} first The first token to check (should be the opening brace) # @param {Token} second The second token to check (should be first after the opening brace) # @param {Token} penultimate The penultimate token to check (should be last before closing brace) # @param {Token} last The last token to check (should be closing brace) # @returns {void} ### validateBraceSpacing = (node, first, second, penultimate, last) -> if astUtils.isTokenOnSameLine first, second firstSpaced = sourceCode.isSpaceBetweenTokens first, second if options.spaced and not firstSpaced reportRequiredBeginningSpace node, first if not options.spaced and firstSpaced reportNoBeginningSpace node, first if astUtils.isTokenOnSameLine penultimate, last shouldCheckPenultimate = (options.arraysInObjectsException and astUtils.isClosingBracketToken(penultimate)) or (options.objectsInObjectsException and astUtils.isClosingBraceToken penultimate) penultimateType = shouldCheckPenultimate and sourceCode.getNodeByRangeIndex(penultimate.range[0]).type closingCurlyBraceMustBeSpaced = if ( (options.arraysInObjectsException and penultimateType is 'ArrayExpression') or (options.objectsInObjectsException and penultimateType in ['ObjectExpression', 'ObjectPattern']) ) not options.spaced else options.spaced lastSpaced = sourceCode.isSpaceBetweenTokens penultimate, last if closingCurlyBraceMustBeSpaced and not lastSpaced reportRequiredEndingSpace node, last if not closingCurlyBraceMustBeSpaced and lastSpaced reportNoEndingSpace node, last ###* # Gets '}' token of an object node. # # Because the last token of object patterns might be a type annotation, # this traverses tokens preceded by the last property, then returns the # first '}' token. # # @param {ASTNode} node - The node to get. This node is an # ObjectExpression or an ObjectPattern. And this node has one or # more properties. # @returns {Token} '}' token. ### getClosingBraceOfObject = (node) -> lastProperty = node.properties[node.properties.length - 1] sourceCode.getTokenAfter lastProperty, astUtils.isClosingBraceToken ###* # Reports a given object node if spacing in curly braces is invalid. # @param {ASTNode} node - An ObjectExpression or ObjectPattern node to check. # @returns {void} ### checkForObject = (node) -> return if node.implicit return if node.properties.length is 0 first = sourceCode.getFirstToken node last = getClosingBraceOfObject node second = sourceCode.getTokenAfter first penultimate = sourceCode.getTokenBefore last validateBraceSpacing node, first, second, penultimate, last ###* # Reports a given import node if spacing in curly braces is invalid. # @param {ASTNode} node - An ImportDeclaration node to check. # @returns {void} ### checkForImport = (node) -> return if node.specifiers.length is 0 firstSpecifier = node.specifiers[0] lastSpecifier = node.specifiers[node.specifiers.length - 1] return unless lastSpecifier.type is 'ImportSpecifier' unless firstSpecifier.type is 'ImportSpecifier' firstSpecifier = node.specifiers[1] first = sourceCode.getTokenBefore firstSpecifier last = sourceCode.getTokenAfter lastSpecifier, astUtils.isNotCommaToken second = sourceCode.getTokenAfter first penultimate = sourceCode.getTokenBefore last validateBraceSpacing node, first, second, penultimate, last ###* # Reports a given export node if spacing in curly braces is invalid. # @param {ASTNode} node - An ExportNamedDeclaration node to check. # @returns {void} ### checkForExport = (node) -> return if node.specifiers.length is 0 firstSpecifier = node.specifiers[0] lastSpecifier = node.specifiers[node.specifiers.length - 1] first = sourceCode.getTokenBefore firstSpecifier last = sourceCode.getTokenAfter lastSpecifier, astUtils.isNotCommaToken second = sourceCode.getTokenAfter first penultimate = sourceCode.getTokenBefore last validateBraceSpacing node, first, second, penultimate, last #-------------------------------------------------------------------------- # Public #-------------------------------------------------------------------------- # var {x} = y; ObjectPattern: checkForObject # var y = {x: 'y'} ObjectExpression: checkForObject # import {y} from 'x'; ImportDeclaration: checkForImport # export {name} from 'yo'; ExportNamedDeclaration: checkForExport
3726
###* # @fileoverview Disallows or enforces spaces inside of object literals. # @author <NAME> ### 'use strict' astUtils = require '../eslint-ast-utils' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce consistent spacing inside braces' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/object-curly-spacing' fixable: 'whitespace' schema: [ enum: ['always', 'never'] , type: 'object' properties: arraysInObjects: type: 'boolean' objectsInObjects: type: 'boolean' additionalProperties: no ] create: (context) -> spaced = context.options[0] is 'always' sourceCode = context.getSourceCode() ###* # Determines whether an option is set, relative to the spacing option. # If spaced is "always", then check whether option is set to false. # If spaced is "never", then check whether option is set to true. # @param {Object} option - The option to exclude. # @returns {boolean} Whether or not the property is excluded. ### isOptionSet = (option) -> if context.options[1] context.options[1][option] is not spaced else no options = { spaced arraysInObjectsException: isOptionSet 'arraysInObjects' objectsInObjectsException: isOptionSet 'objectsInObjects' } #-------------------------------------------------------------------------- # Helpers #-------------------------------------------------------------------------- ###* # Reports that there shouldn't be a space after the first token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportNoBeginningSpace = (node, token) -> context.report { node loc: token.loc.start message: "There should be no space after '{{token}}'." data: token: token.value fix: (fixer) -> nextToken = context.getSourceCode().getTokenAfter token fixer.removeRange [token.range[1], nextToken.range[0]] } ###* # Reports that there shouldn't be a space before the last token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportNoEndingSpace = (node, token) -> context.report { node loc: token.loc.start message: "There should be no space before '{{token}}'." data: token: token.value fix: (fixer) -> previousToken = context.getSourceCode().getTokenBefore token fixer.removeRange [previousToken.range[1], token.range[0]] } ###* # Reports that there should be a space after the first token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportRequiredBeginningSpace = (node, token) -> context.report { node loc: token.loc.start message: "A space is required after '{{token}}'." data: token: token.value fix: (fixer) -> fixer.insertTextAfter token, ' ' } ###* # Reports that there should be a space before the last token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportRequiredEndingSpace = (node, token) -> context.report { node loc: token.loc.start message: "A space is required before '{{token}}'." data: token: token.value fix: (fixer) -> fixer.insertTextBefore token, ' ' } ###* # Determines if spacing in curly braces is valid. # @param {ASTNode} node The AST node to check. # @param {Token} first The first token to check (should be the opening brace) # @param {Token} second The second token to check (should be first after the opening brace) # @param {Token} penultimate The penultimate token to check (should be last before closing brace) # @param {Token} last The last token to check (should be closing brace) # @returns {void} ### validateBraceSpacing = (node, first, second, penultimate, last) -> if astUtils.isTokenOnSameLine first, second firstSpaced = sourceCode.isSpaceBetweenTokens first, second if options.spaced and not firstSpaced reportRequiredBeginningSpace node, first if not options.spaced and firstSpaced reportNoBeginningSpace node, first if astUtils.isTokenOnSameLine penultimate, last shouldCheckPenultimate = (options.arraysInObjectsException and astUtils.isClosingBracketToken(penultimate)) or (options.objectsInObjectsException and astUtils.isClosingBraceToken penultimate) penultimateType = shouldCheckPenultimate and sourceCode.getNodeByRangeIndex(penultimate.range[0]).type closingCurlyBraceMustBeSpaced = if ( (options.arraysInObjectsException and penultimateType is 'ArrayExpression') or (options.objectsInObjectsException and penultimateType in ['ObjectExpression', 'ObjectPattern']) ) not options.spaced else options.spaced lastSpaced = sourceCode.isSpaceBetweenTokens penultimate, last if closingCurlyBraceMustBeSpaced and not lastSpaced reportRequiredEndingSpace node, last if not closingCurlyBraceMustBeSpaced and lastSpaced reportNoEndingSpace node, last ###* # Gets '}' token of an object node. # # Because the last token of object patterns might be a type annotation, # this traverses tokens preceded by the last property, then returns the # first '}' token. # # @param {ASTNode} node - The node to get. This node is an # ObjectExpression or an ObjectPattern. And this node has one or # more properties. # @returns {Token} '}' token. ### getClosingBraceOfObject = (node) -> lastProperty = node.properties[node.properties.length - 1] sourceCode.getTokenAfter lastProperty, astUtils.isClosingBraceToken ###* # Reports a given object node if spacing in curly braces is invalid. # @param {ASTNode} node - An ObjectExpression or ObjectPattern node to check. # @returns {void} ### checkForObject = (node) -> return if node.implicit return if node.properties.length is 0 first = sourceCode.getFirstToken node last = getClosingBraceOfObject node second = sourceCode.getTokenAfter first penultimate = sourceCode.getTokenBefore last validateBraceSpacing node, first, second, penultimate, last ###* # Reports a given import node if spacing in curly braces is invalid. # @param {ASTNode} node - An ImportDeclaration node to check. # @returns {void} ### checkForImport = (node) -> return if node.specifiers.length is 0 firstSpecifier = node.specifiers[0] lastSpecifier = node.specifiers[node.specifiers.length - 1] return unless lastSpecifier.type is 'ImportSpecifier' unless firstSpecifier.type is 'ImportSpecifier' firstSpecifier = node.specifiers[1] first = sourceCode.getTokenBefore firstSpecifier last = sourceCode.getTokenAfter lastSpecifier, astUtils.isNotCommaToken second = sourceCode.getTokenAfter first penultimate = sourceCode.getTokenBefore last validateBraceSpacing node, first, second, penultimate, last ###* # Reports a given export node if spacing in curly braces is invalid. # @param {ASTNode} node - An ExportNamedDeclaration node to check. # @returns {void} ### checkForExport = (node) -> return if node.specifiers.length is 0 firstSpecifier = node.specifiers[0] lastSpecifier = node.specifiers[node.specifiers.length - 1] first = sourceCode.getTokenBefore firstSpecifier last = sourceCode.getTokenAfter lastSpecifier, astUtils.isNotCommaToken second = sourceCode.getTokenAfter first penultimate = sourceCode.getTokenBefore last validateBraceSpacing node, first, second, penultimate, last #-------------------------------------------------------------------------- # Public #-------------------------------------------------------------------------- # var {x} = y; ObjectPattern: checkForObject # var y = {x: 'y'} ObjectExpression: checkForObject # import {y} from 'x'; ImportDeclaration: checkForImport # export {name} from 'yo'; ExportNamedDeclaration: checkForExport
true
###* # @fileoverview Disallows or enforces spaces inside of object literals. # @author PI:NAME:<NAME>END_PI ### 'use strict' astUtils = require '../eslint-ast-utils' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce consistent spacing inside braces' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/object-curly-spacing' fixable: 'whitespace' schema: [ enum: ['always', 'never'] , type: 'object' properties: arraysInObjects: type: 'boolean' objectsInObjects: type: 'boolean' additionalProperties: no ] create: (context) -> spaced = context.options[0] is 'always' sourceCode = context.getSourceCode() ###* # Determines whether an option is set, relative to the spacing option. # If spaced is "always", then check whether option is set to false. # If spaced is "never", then check whether option is set to true. # @param {Object} option - The option to exclude. # @returns {boolean} Whether or not the property is excluded. ### isOptionSet = (option) -> if context.options[1] context.options[1][option] is not spaced else no options = { spaced arraysInObjectsException: isOptionSet 'arraysInObjects' objectsInObjectsException: isOptionSet 'objectsInObjects' } #-------------------------------------------------------------------------- # Helpers #-------------------------------------------------------------------------- ###* # Reports that there shouldn't be a space after the first token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportNoBeginningSpace = (node, token) -> context.report { node loc: token.loc.start message: "There should be no space after '{{token}}'." data: token: token.value fix: (fixer) -> nextToken = context.getSourceCode().getTokenAfter token fixer.removeRange [token.range[1], nextToken.range[0]] } ###* # Reports that there shouldn't be a space before the last token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportNoEndingSpace = (node, token) -> context.report { node loc: token.loc.start message: "There should be no space before '{{token}}'." data: token: token.value fix: (fixer) -> previousToken = context.getSourceCode().getTokenBefore token fixer.removeRange [previousToken.range[1], token.range[0]] } ###* # Reports that there should be a space after the first token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportRequiredBeginningSpace = (node, token) -> context.report { node loc: token.loc.start message: "A space is required after '{{token}}'." data: token: token.value fix: (fixer) -> fixer.insertTextAfter token, ' ' } ###* # Reports that there should be a space before the last token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportRequiredEndingSpace = (node, token) -> context.report { node loc: token.loc.start message: "A space is required before '{{token}}'." data: token: token.value fix: (fixer) -> fixer.insertTextBefore token, ' ' } ###* # Determines if spacing in curly braces is valid. # @param {ASTNode} node The AST node to check. # @param {Token} first The first token to check (should be the opening brace) # @param {Token} second The second token to check (should be first after the opening brace) # @param {Token} penultimate The penultimate token to check (should be last before closing brace) # @param {Token} last The last token to check (should be closing brace) # @returns {void} ### validateBraceSpacing = (node, first, second, penultimate, last) -> if astUtils.isTokenOnSameLine first, second firstSpaced = sourceCode.isSpaceBetweenTokens first, second if options.spaced and not firstSpaced reportRequiredBeginningSpace node, first if not options.spaced and firstSpaced reportNoBeginningSpace node, first if astUtils.isTokenOnSameLine penultimate, last shouldCheckPenultimate = (options.arraysInObjectsException and astUtils.isClosingBracketToken(penultimate)) or (options.objectsInObjectsException and astUtils.isClosingBraceToken penultimate) penultimateType = shouldCheckPenultimate and sourceCode.getNodeByRangeIndex(penultimate.range[0]).type closingCurlyBraceMustBeSpaced = if ( (options.arraysInObjectsException and penultimateType is 'ArrayExpression') or (options.objectsInObjectsException and penultimateType in ['ObjectExpression', 'ObjectPattern']) ) not options.spaced else options.spaced lastSpaced = sourceCode.isSpaceBetweenTokens penultimate, last if closingCurlyBraceMustBeSpaced and not lastSpaced reportRequiredEndingSpace node, last if not closingCurlyBraceMustBeSpaced and lastSpaced reportNoEndingSpace node, last ###* # Gets '}' token of an object node. # # Because the last token of object patterns might be a type annotation, # this traverses tokens preceded by the last property, then returns the # first '}' token. # # @param {ASTNode} node - The node to get. This node is an # ObjectExpression or an ObjectPattern. And this node has one or # more properties. # @returns {Token} '}' token. ### getClosingBraceOfObject = (node) -> lastProperty = node.properties[node.properties.length - 1] sourceCode.getTokenAfter lastProperty, astUtils.isClosingBraceToken ###* # Reports a given object node if spacing in curly braces is invalid. # @param {ASTNode} node - An ObjectExpression or ObjectPattern node to check. # @returns {void} ### checkForObject = (node) -> return if node.implicit return if node.properties.length is 0 first = sourceCode.getFirstToken node last = getClosingBraceOfObject node second = sourceCode.getTokenAfter first penultimate = sourceCode.getTokenBefore last validateBraceSpacing node, first, second, penultimate, last ###* # Reports a given import node if spacing in curly braces is invalid. # @param {ASTNode} node - An ImportDeclaration node to check. # @returns {void} ### checkForImport = (node) -> return if node.specifiers.length is 0 firstSpecifier = node.specifiers[0] lastSpecifier = node.specifiers[node.specifiers.length - 1] return unless lastSpecifier.type is 'ImportSpecifier' unless firstSpecifier.type is 'ImportSpecifier' firstSpecifier = node.specifiers[1] first = sourceCode.getTokenBefore firstSpecifier last = sourceCode.getTokenAfter lastSpecifier, astUtils.isNotCommaToken second = sourceCode.getTokenAfter first penultimate = sourceCode.getTokenBefore last validateBraceSpacing node, first, second, penultimate, last ###* # Reports a given export node if spacing in curly braces is invalid. # @param {ASTNode} node - An ExportNamedDeclaration node to check. # @returns {void} ### checkForExport = (node) -> return if node.specifiers.length is 0 firstSpecifier = node.specifiers[0] lastSpecifier = node.specifiers[node.specifiers.length - 1] first = sourceCode.getTokenBefore firstSpecifier last = sourceCode.getTokenAfter lastSpecifier, astUtils.isNotCommaToken second = sourceCode.getTokenAfter first penultimate = sourceCode.getTokenBefore last validateBraceSpacing node, first, second, penultimate, last #-------------------------------------------------------------------------- # Public #-------------------------------------------------------------------------- # var {x} = y; ObjectPattern: checkForObject # var y = {x: 'y'} ObjectExpression: checkForObject # import {y} from 'x'; ImportDeclaration: checkForImport # export {name} from 'yo'; ExportNamedDeclaration: checkForExport
[ { "context": "te', () ->\n create = () -> new lib.Broker 'ws://127.0.0.1:8080/ws', 'realm1'\n\n it 'should construct an ins", "end": 105, "score": 0.9406471252441406, "start": 96, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "ould be able to register', (done) ->\n ...
src/test/broker.spec.coffee
Soundscape/sublime-net
0
lib = require '../' describe 'Broker test suite', () -> create = () -> new lib.Broker 'ws://127.0.0.1:8080/ws', 'realm1' it 'should construct an instance', () -> instance = create() expect instance .not.toBeNull() it 'should be able to connect and disconnect', (done) -> instance = create() expect instance .not.toBeNull() instance.on 'connected', () -> expect instance.state() .toBe 'connected' instance.disconnect() done() instance.connect() describe 'Broker functionality test suite', () -> instance = null subscription = () -> return beforeEach () -> instance = create() afterEach () -> instance = null it 'should be able to subscribe', (done) -> instance.on 'connected', () -> instance.subscribe 'test', subscription .then () -> expect instance.channels.test .not.toBeNull() instance.disconnect() instance.on 'disconnected', () -> done() instance.connect() it 'should be able to unsubscribe', (done) -> instance.on 'connected', () -> instance.subscribe 'test', subscription .then () -> expect instance.channels.test .not.toBeNull() instance.unsubscribe 'test', subscription .then () -> expect instance.channels.test .toBeNull() instance.disconnect() instance.on 'disconnected', () -> done() instance.connect() it 'should be able to publish', (done) -> sb = (res) -> instance.disconnect() instance.on 'connected', () -> instance.subscribe 'com.example.test', sb .then () -> expect instance.channels['com.example.test'] .not.toBeNull() instance.publish 'com.example.test', { hello: 'world' }, { exclude_me: false } return instance.on 'disconnected', () -> done() instance.connect() it 'should be able to register', (done) -> key = 'com.example.register' fn = (a, b) -> a + b instance.on 'connected', () -> instance.register key, fn .then () -> expect instance.session.registrations.length .toBe 1 instance.disconnect() instance.on 'disconnected', () -> done() instance.connect() it 'should be able to unregister', (done) -> key = 'com.example.unregister' fn = (a, b) -> a + b instance.on 'connected', () -> instance.register key, fn .then () -> expect instance.session.registrations.length .toBe 1 instance.unregister key .then () -> expect instance.session.registrations.length .toBe 0 instance.disconnect() instance.on 'disconnected', () -> done() instance.connect() it 'should be able to call', (done) -> key = 'com.example.call' fn = (args) -> args[0] + args[1] instance.on 'connected', () -> instance.register key, fn .then () -> expect instance.session.registrations.length .toBe 1 instance.call key, [10, 20] .then (res) -> expect res .toBe 30 instance.unregister key .then () -> expect instance.session.registrations.length .toBe 0 instance.disconnect() instance.on 'disconnected', () -> done() instance.connect()
118334
lib = require '../' describe 'Broker test suite', () -> create = () -> new lib.Broker 'ws://127.0.0.1:8080/ws', 'realm1' it 'should construct an instance', () -> instance = create() expect instance .not.toBeNull() it 'should be able to connect and disconnect', (done) -> instance = create() expect instance .not.toBeNull() instance.on 'connected', () -> expect instance.state() .toBe 'connected' instance.disconnect() done() instance.connect() describe 'Broker functionality test suite', () -> instance = null subscription = () -> return beforeEach () -> instance = create() afterEach () -> instance = null it 'should be able to subscribe', (done) -> instance.on 'connected', () -> instance.subscribe 'test', subscription .then () -> expect instance.channels.test .not.toBeNull() instance.disconnect() instance.on 'disconnected', () -> done() instance.connect() it 'should be able to unsubscribe', (done) -> instance.on 'connected', () -> instance.subscribe 'test', subscription .then () -> expect instance.channels.test .not.toBeNull() instance.unsubscribe 'test', subscription .then () -> expect instance.channels.test .toBeNull() instance.disconnect() instance.on 'disconnected', () -> done() instance.connect() it 'should be able to publish', (done) -> sb = (res) -> instance.disconnect() instance.on 'connected', () -> instance.subscribe 'com.example.test', sb .then () -> expect instance.channels['com.example.test'] .not.toBeNull() instance.publish 'com.example.test', { hello: 'world' }, { exclude_me: false } return instance.on 'disconnected', () -> done() instance.connect() it 'should be able to register', (done) -> key = '<KEY>' fn = (a, b) -> a + b instance.on 'connected', () -> instance.register key, fn .then () -> expect instance.session.registrations.length .toBe 1 instance.disconnect() instance.on 'disconnected', () -> done() instance.connect() it 'should be able to unregister', (done) -> key = '<KEY>' fn = (a, b) -> a + b instance.on 'connected', () -> instance.register key, fn .then () -> expect instance.session.registrations.length .toBe 1 instance.unregister key .then () -> expect instance.session.registrations.length .toBe 0 instance.disconnect() instance.on 'disconnected', () -> done() instance.connect() it 'should be able to call', (done) -> key = '<KEY>' fn = (args) -> args[0] + args[1] instance.on 'connected', () -> instance.register key, fn .then () -> expect instance.session.registrations.length .toBe 1 instance.call key, [10, 20] .then (res) -> expect res .toBe 30 instance.unregister key .then () -> expect instance.session.registrations.length .toBe 0 instance.disconnect() instance.on 'disconnected', () -> done() instance.connect()
true
lib = require '../' describe 'Broker test suite', () -> create = () -> new lib.Broker 'ws://127.0.0.1:8080/ws', 'realm1' it 'should construct an instance', () -> instance = create() expect instance .not.toBeNull() it 'should be able to connect and disconnect', (done) -> instance = create() expect instance .not.toBeNull() instance.on 'connected', () -> expect instance.state() .toBe 'connected' instance.disconnect() done() instance.connect() describe 'Broker functionality test suite', () -> instance = null subscription = () -> return beforeEach () -> instance = create() afterEach () -> instance = null it 'should be able to subscribe', (done) -> instance.on 'connected', () -> instance.subscribe 'test', subscription .then () -> expect instance.channels.test .not.toBeNull() instance.disconnect() instance.on 'disconnected', () -> done() instance.connect() it 'should be able to unsubscribe', (done) -> instance.on 'connected', () -> instance.subscribe 'test', subscription .then () -> expect instance.channels.test .not.toBeNull() instance.unsubscribe 'test', subscription .then () -> expect instance.channels.test .toBeNull() instance.disconnect() instance.on 'disconnected', () -> done() instance.connect() it 'should be able to publish', (done) -> sb = (res) -> instance.disconnect() instance.on 'connected', () -> instance.subscribe 'com.example.test', sb .then () -> expect instance.channels['com.example.test'] .not.toBeNull() instance.publish 'com.example.test', { hello: 'world' }, { exclude_me: false } return instance.on 'disconnected', () -> done() instance.connect() it 'should be able to register', (done) -> key = 'PI:KEY:<KEY>END_PI' fn = (a, b) -> a + b instance.on 'connected', () -> instance.register key, fn .then () -> expect instance.session.registrations.length .toBe 1 instance.disconnect() instance.on 'disconnected', () -> done() instance.connect() it 'should be able to unregister', (done) -> key = 'PI:KEY:<KEY>END_PI' fn = (a, b) -> a + b instance.on 'connected', () -> instance.register key, fn .then () -> expect instance.session.registrations.length .toBe 1 instance.unregister key .then () -> expect instance.session.registrations.length .toBe 0 instance.disconnect() instance.on 'disconnected', () -> done() instance.connect() it 'should be able to call', (done) -> key = 'PI:KEY:<KEY>END_PI' fn = (args) -> args[0] + args[1] instance.on 'connected', () -> instance.register key, fn .then () -> expect instance.session.registrations.length .toBe 1 instance.call key, [10, 20] .then (res) -> expect res .toBe 30 instance.unregister key .then () -> expect instance.session.registrations.length .toBe 0 instance.disconnect() instance.on 'disconnected', () -> done() instance.connect()
[ { "context": "UserPassword('username:password'), {\n user: 'username',\n password: 'password',\n })\n assert.d", "end": 1026, "score": 0.9957429766654968, "start": 1018, "tag": "USERNAME", "value": "username" }, { "context": "ord'), {\n user: 'username',\n p...
test/lib/url.spec.coffee
bozonx/squidlet-lib
0
url = require('../../../../../squidlet-lib/src/url') describe 'system.lib.url', -> it 'parseSearch', -> assert.deepEqual(url.parseSearch('param1=value1&param2&param3=5&param4=true'), { param1: 'value1', param2: '', param3: 5, param4: true, }) assert.deepEqual(url.parseSearch('param1=[1, true, "str"]'), { param1: [1, true, 'str'] }) assert.deepEqual(url.parseSearch('param1={"a": "str", "b": 5, "c": true}'), { param1: {a: "str", b: 5, c: true} }) it 'parseHostPort', -> assert.deepEqual(url.parseHostPort('pre.host.com:8080'), { host: 'pre.host.com', port: 8080, }) assert.deepEqual(url.parseHostPort('pre.host.com'), { host: 'pre.host.com', }) assert.throws(() => url.parseHostPort('')) assert.throws(() => url.parseHostPort('host:port')) assert.throws(() => url.parseHostPort('host:80:90')) it 'parseUserPassword', -> assert.deepEqual(url.parseUserPassword('username:password'), { user: 'username', password: 'password', }) assert.deepEqual(url.parseUserPassword('username'), { user: 'username', }) assert.deepEqual(url.parseUserPassword(''), {}) assert.throws(() => url.parseHostPort('username:password:other')) it 'parseLeftPartOfUrl - full url', -> assert.deepEqual(url.parseLeftPartOfUrl('https://username:password@host.com:8080/path'), { scheme: 'https', host: 'host.com', port: 8080, user: 'username', password: 'password', }) it 'parseLeftPartOfUrl - username and not password', -> assert.deepEqual(url.parseLeftPartOfUrl('https://username@host.com'), { scheme: 'https', host: 'host.com', user: 'username', }) it 'parseLeftPartOfUrl - only protocol and host', -> assert.deepEqual(url.parseLeftPartOfUrl('https://host.com'), { scheme: 'https', host: 'host.com', }) it 'parseLeftPartOfUrl - ip', -> assert.deepEqual(url.parseLeftPartOfUrl('https://192.168.0.1:80'), { scheme: 'https', host: '192.168.0.1', port: 80, }) it 'parseLeftPartOfUrl - ip only', -> assert.deepEqual(url.parseLeftPartOfUrl('192.168.0.1'), { host: '192.168.0.1', }) it 'parseLeftPartOfUrl - only host', -> assert.deepEqual(url.parseLeftPartOfUrl('host.com'), { host: 'host.com', }) it 'parseLeftPartOfUrl - local host', -> assert.deepEqual(url.parseLeftPartOfUrl('localhost'), { host: 'localhost', }) it 'parseRightPartOfUrl - full', -> assert.deepEqual(url.parseRightPartOfUrl('/path/to/route/?param1=value1&param2#anc'), { path: '/path/to/route/', search: { param1: 'value1', param2: '', }, anchor: 'anc', }) it 'parseRightPartOfUrl - stripped', -> assert.deepEqual(url.parseRightPartOfUrl('path/to/route/?'), { path: 'path/to/route/', }) it 'parseRightPartOfUrl - anchor', -> assert.deepEqual(url.parseRightPartOfUrl('path#anc'), { path: 'path', anchor: 'anc', }) it 'parseRightPartOfUrl - anchor with slash', -> assert.deepEqual(url.parseRightPartOfUrl('path/#anc'), { path: 'path/', anchor: 'anc', }) it 'splitUrl - full', -> assert.deepEqual(url.splitUrl('https://u:p@host.com:80/path?p1=v1#a'), { left: 'https://u:p@host.com:80', right: '/path?p1=v1#a' }) it 'splitUrl - short', -> assert.deepEqual(url.splitUrl('host.com/path/'), { left: 'host.com', right: '/path/' }) it 'splitUrl - only left', -> assert.deepEqual(url.splitUrl('http://host.com'), { left: 'http://host.com' }) it 'splitUrl - only left - only host', -> assert.deepEqual(url.splitUrl('host.com'), { left: 'host.com' }) it 'splitUrl - only left - local host', -> assert.deepEqual(url.splitUrl('localhost'), { left: 'localhost' }) it 'splitUrl - only left - ip', -> assert.deepEqual(url.splitUrl('192.168.0.1'), { left: '192.168.0.1' }) it 'splitUrl - only right', -> assert.deepEqual(url.splitUrl('/path'), { right: '/path' }) it 'splitUrl - only right - anchor', -> assert.deepEqual(url.splitUrl('/#anc'), { right: '/#anc' }) it 'splitUrl - only right - anchor at the beginning', -> assert.deepEqual(url.splitUrl('#anc'), { right: '#anc' }) it 'parseUrl - full', -> testUrl = 'https://username:password@host.com:8080/path/to/route/?param1=value1&param2' assert.deepEqual(url.parseUrl(testUrl), { scheme: 'https', host: 'host.com', port: 8080, path: '/path/to/route/', search: { param1: 'value1', param2: '', }, user: 'username', password: 'password', }) it 'parseUrl - simplified', -> testUrl = 'http://host.com/' assert.deepEqual(url.parseUrl(testUrl), { scheme: 'http', host: 'host.com', path: '/', }) it 'parseUrl - simplified, no path', -> testUrl = 'http://host.com' assert.deepEqual(url.parseUrl(testUrl), { scheme: 'http', host: 'host.com', }) it 'parseUrl - trailing ?', -> testUrl = 'http://host.com/path?' assert.deepEqual(url.parseUrl(testUrl), { scheme: 'http', host: 'host.com', path: '/path', }) it 'parseUrl - url path', -> testUrl = '/path/to/route/?param1=value1' assert.deepEqual(url.parseUrl(testUrl), { path: '/path/to/route/', search: { param1: 'value1', }, }) it 'parseUrl - only host', -> testUrl = 'something' assert.deepEqual(url.parseUrl(testUrl), { host: 'something', }) it 'parseUrl - localhost', -> testUrl = 'localhost/to/route' assert.deepEqual(url.parseUrl(testUrl), { host: 'localhost' path: '/to/route', }) it 'parseUrl - anchor', -> testUrl = 'path#anc' assert.deepEqual(url.parseUrl(testUrl), { host: 'path', anchor: 'anc', }) it 'parseUrl - no protocol', -> testUrl = 'host.com/path' assert.deepEqual(url.parseUrl(testUrl), { host: 'host.com', path: '/path', }) it 'parseUrl - ip', -> testUrl = '192.168.0.1/path' assert.deepEqual(url.parseUrl(testUrl), { host: '192.168.0.1', path: '/path', }) it 'parseUrl - decoded values in a path', -> testUrl = '127.0.0.1:8087/api/getState/0,bedroom.light1' assert.deepEqual(url.parseUrl(testUrl), { host: '127.0.0.1', port: 8087, path: '/api/getState/0,bedroom.light1', }) it 'parseUrl - dot in file name', -> testUrl = '127.0.0.1/path/index.html?param=1' assert.deepEqual(url.parseUrl(testUrl), { host: '127.0.0.1', path: '/path/index.html', search: { param: 1 } }) it 'parseUrl - encoded by encodeURIComponent', -> testUrl = 'http://192.168.88.3:8087/api/getState/0%2C%22bedroom.light1%22' assert.deepEqual(url.parseUrl(testUrl), { host: '192.168.88.3', port: 8087, path: '/api/getState/0,"bedroom.light1"', scheme: 'http', }) #it 'parseUrl - bad url', -> # bad protocol #assert.throws(() => url.parseUrl('http:/host.com/path')) # bad search #assert.throws(() => url.parseUrl('http://host.com/path&p')) # bad host #assert.throws(() => url.parseUrl('http://:80/path&p'))
155625
url = require('../../../../../squidlet-lib/src/url') describe 'system.lib.url', -> it 'parseSearch', -> assert.deepEqual(url.parseSearch('param1=value1&param2&param3=5&param4=true'), { param1: 'value1', param2: '', param3: 5, param4: true, }) assert.deepEqual(url.parseSearch('param1=[1, true, "str"]'), { param1: [1, true, 'str'] }) assert.deepEqual(url.parseSearch('param1={"a": "str", "b": 5, "c": true}'), { param1: {a: "str", b: 5, c: true} }) it 'parseHostPort', -> assert.deepEqual(url.parseHostPort('pre.host.com:8080'), { host: 'pre.host.com', port: 8080, }) assert.deepEqual(url.parseHostPort('pre.host.com'), { host: 'pre.host.com', }) assert.throws(() => url.parseHostPort('')) assert.throws(() => url.parseHostPort('host:port')) assert.throws(() => url.parseHostPort('host:80:90')) it 'parseUserPassword', -> assert.deepEqual(url.parseUserPassword('username:password'), { user: 'username', password: '<PASSWORD>', }) assert.deepEqual(url.parseUserPassword('username'), { user: 'username', }) assert.deepEqual(url.parseUserPassword(''), {}) assert.throws(() => url.parseHostPort('username:password:other')) it 'parseLeftPartOfUrl - full url', -> assert.deepEqual(url.parseLeftPartOfUrl('https://username:password@host.com:8080/path'), { scheme: 'https', host: 'host.com', port: 8080, user: 'username', password: '<PASSWORD>', }) it 'parseLeftPartOfUrl - username and not password', -> assert.deepEqual(url.parseLeftPartOfUrl('https://<EMAIL>'), { scheme: 'https', host: 'host.com', user: 'username', }) it 'parseLeftPartOfUrl - only protocol and host', -> assert.deepEqual(url.parseLeftPartOfUrl('https://host.com'), { scheme: 'https', host: 'host.com', }) it 'parseLeftPartOfUrl - ip', -> assert.deepEqual(url.parseLeftPartOfUrl('https://192.168.0.1:80'), { scheme: 'https', host: '192.168.0.1', port: 80, }) it 'parseLeftPartOfUrl - ip only', -> assert.deepEqual(url.parseLeftPartOfUrl('192.168.0.1'), { host: '192.168.0.1', }) it 'parseLeftPartOfUrl - only host', -> assert.deepEqual(url.parseLeftPartOfUrl('host.com'), { host: 'host.com', }) it 'parseLeftPartOfUrl - local host', -> assert.deepEqual(url.parseLeftPartOfUrl('localhost'), { host: 'localhost', }) it 'parseRightPartOfUrl - full', -> assert.deepEqual(url.parseRightPartOfUrl('/path/to/route/?param1=value1&param2#anc'), { path: '/path/to/route/', search: { param1: 'value1', param2: '', }, anchor: 'anc', }) it 'parseRightPartOfUrl - stripped', -> assert.deepEqual(url.parseRightPartOfUrl('path/to/route/?'), { path: 'path/to/route/', }) it 'parseRightPartOfUrl - anchor', -> assert.deepEqual(url.parseRightPartOfUrl('path#anc'), { path: 'path', anchor: 'anc', }) it 'parseRightPartOfUrl - anchor with slash', -> assert.deepEqual(url.parseRightPartOfUrl('path/#anc'), { path: 'path/', anchor: 'anc', }) it 'splitUrl - full', -> assert.deepEqual(url.splitUrl('https://u:p@host.com:80/path?p1=v1#a'), { left: 'https://u:p@host.com:80', right: '/path?p1=v1#a' }) it 'splitUrl - short', -> assert.deepEqual(url.splitUrl('host.com/path/'), { left: 'host.com', right: '/path/' }) it 'splitUrl - only left', -> assert.deepEqual(url.splitUrl('http://host.com'), { left: 'http://host.com' }) it 'splitUrl - only left - only host', -> assert.deepEqual(url.splitUrl('host.com'), { left: 'host.com' }) it 'splitUrl - only left - local host', -> assert.deepEqual(url.splitUrl('localhost'), { left: 'localhost' }) it 'splitUrl - only left - ip', -> assert.deepEqual(url.splitUrl('192.168.0.1'), { left: '192.168.0.1' }) it 'splitUrl - only right', -> assert.deepEqual(url.splitUrl('/path'), { right: '/path' }) it 'splitUrl - only right - anchor', -> assert.deepEqual(url.splitUrl('/#anc'), { right: '/#anc' }) it 'splitUrl - only right - anchor at the beginning', -> assert.deepEqual(url.splitUrl('#anc'), { right: '#anc' }) it 'parseUrl - full', -> testUrl = 'https://username:password@host.com:8080/path/to/route/?param1=value1&param2' assert.deepEqual(url.parseUrl(testUrl), { scheme: 'https', host: 'host.com', port: 8080, path: '/path/to/route/', search: { param1: 'value1', param2: '', }, user: 'username', password: '<PASSWORD>', }) it 'parseUrl - simplified', -> testUrl = 'http://host.com/' assert.deepEqual(url.parseUrl(testUrl), { scheme: 'http', host: 'host.com', path: '/', }) it 'parseUrl - simplified, no path', -> testUrl = 'http://host.com' assert.deepEqual(url.parseUrl(testUrl), { scheme: 'http', host: 'host.com', }) it 'parseUrl - trailing ?', -> testUrl = 'http://host.com/path?' assert.deepEqual(url.parseUrl(testUrl), { scheme: 'http', host: 'host.com', path: '/path', }) it 'parseUrl - url path', -> testUrl = '/path/to/route/?param1=value1' assert.deepEqual(url.parseUrl(testUrl), { path: '/path/to/route/', search: { param1: 'value1', }, }) it 'parseUrl - only host', -> testUrl = 'something' assert.deepEqual(url.parseUrl(testUrl), { host: 'something', }) it 'parseUrl - localhost', -> testUrl = 'localhost/to/route' assert.deepEqual(url.parseUrl(testUrl), { host: 'localhost' path: '/to/route', }) it 'parseUrl - anchor', -> testUrl = 'path#anc' assert.deepEqual(url.parseUrl(testUrl), { host: 'path', anchor: 'anc', }) it 'parseUrl - no protocol', -> testUrl = 'host.com/path' assert.deepEqual(url.parseUrl(testUrl), { host: 'host.com', path: '/path', }) it 'parseUrl - ip', -> testUrl = '192.168.0.1/path' assert.deepEqual(url.parseUrl(testUrl), { host: '192.168.0.1', path: '/path', }) it 'parseUrl - decoded values in a path', -> testUrl = '127.0.0.1:8087/api/getState/0,bedroom.light1' assert.deepEqual(url.parseUrl(testUrl), { host: '127.0.0.1', port: 8087, path: '/api/getState/0,bedroom.light1', }) it 'parseUrl - dot in file name', -> testUrl = '127.0.0.1/path/index.html?param=1' assert.deepEqual(url.parseUrl(testUrl), { host: '127.0.0.1', path: '/path/index.html', search: { param: 1 } }) it 'parseUrl - encoded by encodeURIComponent', -> testUrl = 'http://192.168.88.3:8087/api/getState/0%2C%22bedroom.light1%22' assert.deepEqual(url.parseUrl(testUrl), { host: '192.168.88.3', port: 8087, path: '/api/getState/0,"bedroom.light1"', scheme: 'http', }) #it 'parseUrl - bad url', -> # bad protocol #assert.throws(() => url.parseUrl('http:/host.com/path')) # bad search #assert.throws(() => url.parseUrl('http://host.com/path&p')) # bad host #assert.throws(() => url.parseUrl('http://:80/path&p'))
true
url = require('../../../../../squidlet-lib/src/url') describe 'system.lib.url', -> it 'parseSearch', -> assert.deepEqual(url.parseSearch('param1=value1&param2&param3=5&param4=true'), { param1: 'value1', param2: '', param3: 5, param4: true, }) assert.deepEqual(url.parseSearch('param1=[1, true, "str"]'), { param1: [1, true, 'str'] }) assert.deepEqual(url.parseSearch('param1={"a": "str", "b": 5, "c": true}'), { param1: {a: "str", b: 5, c: true} }) it 'parseHostPort', -> assert.deepEqual(url.parseHostPort('pre.host.com:8080'), { host: 'pre.host.com', port: 8080, }) assert.deepEqual(url.parseHostPort('pre.host.com'), { host: 'pre.host.com', }) assert.throws(() => url.parseHostPort('')) assert.throws(() => url.parseHostPort('host:port')) assert.throws(() => url.parseHostPort('host:80:90')) it 'parseUserPassword', -> assert.deepEqual(url.parseUserPassword('username:password'), { user: 'username', password: 'PI:PASSWORD:<PASSWORD>END_PI', }) assert.deepEqual(url.parseUserPassword('username'), { user: 'username', }) assert.deepEqual(url.parseUserPassword(''), {}) assert.throws(() => url.parseHostPort('username:password:other')) it 'parseLeftPartOfUrl - full url', -> assert.deepEqual(url.parseLeftPartOfUrl('https://username:password@host.com:8080/path'), { scheme: 'https', host: 'host.com', port: 8080, user: 'username', password: 'PI:PASSWORD:<PASSWORD>END_PI', }) it 'parseLeftPartOfUrl - username and not password', -> assert.deepEqual(url.parseLeftPartOfUrl('https://PI:EMAIL:<EMAIL>END_PI'), { scheme: 'https', host: 'host.com', user: 'username', }) it 'parseLeftPartOfUrl - only protocol and host', -> assert.deepEqual(url.parseLeftPartOfUrl('https://host.com'), { scheme: 'https', host: 'host.com', }) it 'parseLeftPartOfUrl - ip', -> assert.deepEqual(url.parseLeftPartOfUrl('https://192.168.0.1:80'), { scheme: 'https', host: '192.168.0.1', port: 80, }) it 'parseLeftPartOfUrl - ip only', -> assert.deepEqual(url.parseLeftPartOfUrl('192.168.0.1'), { host: '192.168.0.1', }) it 'parseLeftPartOfUrl - only host', -> assert.deepEqual(url.parseLeftPartOfUrl('host.com'), { host: 'host.com', }) it 'parseLeftPartOfUrl - local host', -> assert.deepEqual(url.parseLeftPartOfUrl('localhost'), { host: 'localhost', }) it 'parseRightPartOfUrl - full', -> assert.deepEqual(url.parseRightPartOfUrl('/path/to/route/?param1=value1&param2#anc'), { path: '/path/to/route/', search: { param1: 'value1', param2: '', }, anchor: 'anc', }) it 'parseRightPartOfUrl - stripped', -> assert.deepEqual(url.parseRightPartOfUrl('path/to/route/?'), { path: 'path/to/route/', }) it 'parseRightPartOfUrl - anchor', -> assert.deepEqual(url.parseRightPartOfUrl('path#anc'), { path: 'path', anchor: 'anc', }) it 'parseRightPartOfUrl - anchor with slash', -> assert.deepEqual(url.parseRightPartOfUrl('path/#anc'), { path: 'path/', anchor: 'anc', }) it 'splitUrl - full', -> assert.deepEqual(url.splitUrl('https://u:p@host.com:80/path?p1=v1#a'), { left: 'https://u:p@host.com:80', right: '/path?p1=v1#a' }) it 'splitUrl - short', -> assert.deepEqual(url.splitUrl('host.com/path/'), { left: 'host.com', right: '/path/' }) it 'splitUrl - only left', -> assert.deepEqual(url.splitUrl('http://host.com'), { left: 'http://host.com' }) it 'splitUrl - only left - only host', -> assert.deepEqual(url.splitUrl('host.com'), { left: 'host.com' }) it 'splitUrl - only left - local host', -> assert.deepEqual(url.splitUrl('localhost'), { left: 'localhost' }) it 'splitUrl - only left - ip', -> assert.deepEqual(url.splitUrl('192.168.0.1'), { left: '192.168.0.1' }) it 'splitUrl - only right', -> assert.deepEqual(url.splitUrl('/path'), { right: '/path' }) it 'splitUrl - only right - anchor', -> assert.deepEqual(url.splitUrl('/#anc'), { right: '/#anc' }) it 'splitUrl - only right - anchor at the beginning', -> assert.deepEqual(url.splitUrl('#anc'), { right: '#anc' }) it 'parseUrl - full', -> testUrl = 'https://username:password@host.com:8080/path/to/route/?param1=value1&param2' assert.deepEqual(url.parseUrl(testUrl), { scheme: 'https', host: 'host.com', port: 8080, path: '/path/to/route/', search: { param1: 'value1', param2: '', }, user: 'username', password: 'PI:PASSWORD:<PASSWORD>END_PI', }) it 'parseUrl - simplified', -> testUrl = 'http://host.com/' assert.deepEqual(url.parseUrl(testUrl), { scheme: 'http', host: 'host.com', path: '/', }) it 'parseUrl - simplified, no path', -> testUrl = 'http://host.com' assert.deepEqual(url.parseUrl(testUrl), { scheme: 'http', host: 'host.com', }) it 'parseUrl - trailing ?', -> testUrl = 'http://host.com/path?' assert.deepEqual(url.parseUrl(testUrl), { scheme: 'http', host: 'host.com', path: '/path', }) it 'parseUrl - url path', -> testUrl = '/path/to/route/?param1=value1' assert.deepEqual(url.parseUrl(testUrl), { path: '/path/to/route/', search: { param1: 'value1', }, }) it 'parseUrl - only host', -> testUrl = 'something' assert.deepEqual(url.parseUrl(testUrl), { host: 'something', }) it 'parseUrl - localhost', -> testUrl = 'localhost/to/route' assert.deepEqual(url.parseUrl(testUrl), { host: 'localhost' path: '/to/route', }) it 'parseUrl - anchor', -> testUrl = 'path#anc' assert.deepEqual(url.parseUrl(testUrl), { host: 'path', anchor: 'anc', }) it 'parseUrl - no protocol', -> testUrl = 'host.com/path' assert.deepEqual(url.parseUrl(testUrl), { host: 'host.com', path: '/path', }) it 'parseUrl - ip', -> testUrl = '192.168.0.1/path' assert.deepEqual(url.parseUrl(testUrl), { host: '192.168.0.1', path: '/path', }) it 'parseUrl - decoded values in a path', -> testUrl = '127.0.0.1:8087/api/getState/0,bedroom.light1' assert.deepEqual(url.parseUrl(testUrl), { host: '127.0.0.1', port: 8087, path: '/api/getState/0,bedroom.light1', }) it 'parseUrl - dot in file name', -> testUrl = '127.0.0.1/path/index.html?param=1' assert.deepEqual(url.parseUrl(testUrl), { host: '127.0.0.1', path: '/path/index.html', search: { param: 1 } }) it 'parseUrl - encoded by encodeURIComponent', -> testUrl = 'http://192.168.88.3:8087/api/getState/0%2C%22bedroom.light1%22' assert.deepEqual(url.parseUrl(testUrl), { host: '192.168.88.3', port: 8087, path: '/api/getState/0,"bedroom.light1"', scheme: 'http', }) #it 'parseUrl - bad url', -> # bad protocol #assert.throws(() => url.parseUrl('http:/host.com/path')) # bad search #assert.throws(() => url.parseUrl('http://host.com/path&p')) # bad host #assert.throws(() => url.parseUrl('http://:80/path&p'))
[ { "context": " = createDoc()\n len = doc.push ['friends'], 'jim', ->\n expect(len).equal 1\n expect(doc.g", "end": 4031, "score": 0.6823934316635132, "start": 4028, "tag": "NAME", "value": "jim" }, { "context": ").equal 1\n expect(doc.get()).eql {friends: ['jim']}...
test/Model/docs.coffee
vmakhaev/racer
0
{expect} = require '../util' module.exports = (createDoc) -> describe 'get', -> it 'creates an undefined doc', -> doc = createDoc() expect(doc.get()).eql undefined it 'gets a defined doc', -> doc = createDoc() doc.set [], {id: 'green'}, -> expect(doc.get()).eql {id: 'green'} it 'gets a property on an undefined document', -> doc = createDoc() expect(doc.get ['id']).eql undefined it 'gets an undefined property', -> doc = createDoc() doc.set [], {}, -> expect(doc.get ['id']).eql undefined it 'gets a defined property', -> doc = createDoc() doc.set [], {id: 'green'}, -> expect(doc.get ['id']).eql 'green' it 'gets a false property', -> doc = createDoc() doc.set [], {id: 'green', shown: false}, -> expect(doc.get ['shown']).eql false it 'gets a null property', -> doc = createDoc() doc.set [], {id: 'green', shown: null}, -> expect(doc.get ['shown']).eql null it 'gets a method property', -> doc = createDoc() doc.set [], {empty: ''}, -> expect(doc.get ['empty', 'charAt']).eql ''.charAt it 'gets an array member', -> doc = createDoc() doc.set [], {rgb: [0, 255, 0]}, -> expect(doc.get ['rgb', '1']).eql 255 it 'gets an array length', -> doc = createDoc() doc.set [], {rgb: [0, 255, 0]}, -> expect(doc.get ['rgb', 'length']).eql 3 describe 'set', -> it 'sets an empty doc', -> doc = createDoc() previous = doc.set [], {}, -> expect(previous).equal undefined expect(doc.get()).eql {} it 'sets a property', -> doc = createDoc() previous = doc.set ['shown'], false, -> expect(previous).equal undefined expect(doc.get()).eql {shown: false} it 'sets a multi-nested property', -> doc = createDoc() previous = doc.set ['rgb', 'green', 'float'], 1, -> expect(previous).equal undefined expect(doc.get()).eql {rgb: {green: {float: 1}}} it 'sets on an existing document', -> doc = createDoc() previous = doc.set [], {}, -> expect(previous).equal undefined expect(doc.get()).eql {} previous = doc.set ['shown'], false, -> expect(previous).equal undefined expect(doc.get()).eql {shown: false} it 'returns the previous value on set', -> doc = createDoc() previous = doc.set ['shown'], false, -> expect(previous).equal undefined expect(doc.get()).eql {shown: false} previous = doc.set ['shown'], true, -> expect(previous).equal false expect(doc.get()).eql {shown: true} it 'creates an implied array on set', -> doc = createDoc() doc.set ['rgb', '2'], 0, -> doc.set ['rgb', '1'], 255, -> doc.set ['rgb', '0'], 127, -> expect(doc.get()).eql {rgb: [127, 255, 0]} it 'creates an implied object on an array', -> doc = createDoc() doc.set ['colors'], [], -> doc.set ['colors', '0', 'value'], 'green', -> expect(doc.get()).eql {colors: [{value: 'green'}]} describe 'del', -> it 'can del on an undefined path without effect', -> doc = createDoc() previous = doc.del ['rgb', '2'], -> expect(previous).equal undefined expect(doc.get()).eql undefined it 'can del on a document', -> doc = createDoc() doc.set [], {}, -> previous = doc.del [], -> expect(previous).eql {} expect(doc.get()).eql undefined it 'can del on a nested property', -> doc = createDoc() doc.set ['rgb'], [ {float: 0, int: 0} {float: 1, int: 255} {float: 0, int: 0} ], -> previous = doc.del ['rgb', '0', 'float'], -> expect(previous).eql 0 expect(doc.get ['rgb']).eql [ {int: 0} {float: 1, int: 255} {float: 0, int: 0} ] describe 'push', -> it 'can push on an undefined property', -> doc = createDoc() len = doc.push ['friends'], 'jim', -> expect(len).equal 1 expect(doc.get()).eql {friends: ['jim']} it 'can push on a defined array', -> doc = createDoc() len = doc.push ['friends'], 'jim', -> expect(len).equal 1 len = doc.push ['friends'], 'sue', -> expect(len).equal 2 expect(doc.get()).eql {friends: ['jim', 'sue']} it 'throws a TypeError when pushing on a non-array', (done) -> doc = createDoc() doc.set ['friends'], {}, -> doc.push ['friends'], ['x'], (err) -> expect(err).a TypeError done()
199357
{expect} = require '../util' module.exports = (createDoc) -> describe 'get', -> it 'creates an undefined doc', -> doc = createDoc() expect(doc.get()).eql undefined it 'gets a defined doc', -> doc = createDoc() doc.set [], {id: 'green'}, -> expect(doc.get()).eql {id: 'green'} it 'gets a property on an undefined document', -> doc = createDoc() expect(doc.get ['id']).eql undefined it 'gets an undefined property', -> doc = createDoc() doc.set [], {}, -> expect(doc.get ['id']).eql undefined it 'gets a defined property', -> doc = createDoc() doc.set [], {id: 'green'}, -> expect(doc.get ['id']).eql 'green' it 'gets a false property', -> doc = createDoc() doc.set [], {id: 'green', shown: false}, -> expect(doc.get ['shown']).eql false it 'gets a null property', -> doc = createDoc() doc.set [], {id: 'green', shown: null}, -> expect(doc.get ['shown']).eql null it 'gets a method property', -> doc = createDoc() doc.set [], {empty: ''}, -> expect(doc.get ['empty', 'charAt']).eql ''.charAt it 'gets an array member', -> doc = createDoc() doc.set [], {rgb: [0, 255, 0]}, -> expect(doc.get ['rgb', '1']).eql 255 it 'gets an array length', -> doc = createDoc() doc.set [], {rgb: [0, 255, 0]}, -> expect(doc.get ['rgb', 'length']).eql 3 describe 'set', -> it 'sets an empty doc', -> doc = createDoc() previous = doc.set [], {}, -> expect(previous).equal undefined expect(doc.get()).eql {} it 'sets a property', -> doc = createDoc() previous = doc.set ['shown'], false, -> expect(previous).equal undefined expect(doc.get()).eql {shown: false} it 'sets a multi-nested property', -> doc = createDoc() previous = doc.set ['rgb', 'green', 'float'], 1, -> expect(previous).equal undefined expect(doc.get()).eql {rgb: {green: {float: 1}}} it 'sets on an existing document', -> doc = createDoc() previous = doc.set [], {}, -> expect(previous).equal undefined expect(doc.get()).eql {} previous = doc.set ['shown'], false, -> expect(previous).equal undefined expect(doc.get()).eql {shown: false} it 'returns the previous value on set', -> doc = createDoc() previous = doc.set ['shown'], false, -> expect(previous).equal undefined expect(doc.get()).eql {shown: false} previous = doc.set ['shown'], true, -> expect(previous).equal false expect(doc.get()).eql {shown: true} it 'creates an implied array on set', -> doc = createDoc() doc.set ['rgb', '2'], 0, -> doc.set ['rgb', '1'], 255, -> doc.set ['rgb', '0'], 127, -> expect(doc.get()).eql {rgb: [127, 255, 0]} it 'creates an implied object on an array', -> doc = createDoc() doc.set ['colors'], [], -> doc.set ['colors', '0', 'value'], 'green', -> expect(doc.get()).eql {colors: [{value: 'green'}]} describe 'del', -> it 'can del on an undefined path without effect', -> doc = createDoc() previous = doc.del ['rgb', '2'], -> expect(previous).equal undefined expect(doc.get()).eql undefined it 'can del on a document', -> doc = createDoc() doc.set [], {}, -> previous = doc.del [], -> expect(previous).eql {} expect(doc.get()).eql undefined it 'can del on a nested property', -> doc = createDoc() doc.set ['rgb'], [ {float: 0, int: 0} {float: 1, int: 255} {float: 0, int: 0} ], -> previous = doc.del ['rgb', '0', 'float'], -> expect(previous).eql 0 expect(doc.get ['rgb']).eql [ {int: 0} {float: 1, int: 255} {float: 0, int: 0} ] describe 'push', -> it 'can push on an undefined property', -> doc = createDoc() len = doc.push ['friends'], '<NAME>', -> expect(len).equal 1 expect(doc.get()).eql {friends: ['<NAME>']} it 'can push on a defined array', -> doc = createDoc() len = doc.push ['friends'], '<NAME>', -> expect(len).equal 1 len = doc.push ['friends'], 'sue', -> expect(len).equal 2 expect(doc.get()).eql {friends: ['<NAME>', '<NAME>']} it 'throws a TypeError when pushing on a non-array', (done) -> doc = createDoc() doc.set ['friends'], {}, -> doc.push ['friends'], ['x'], (err) -> expect(err).a TypeError done()
true
{expect} = require '../util' module.exports = (createDoc) -> describe 'get', -> it 'creates an undefined doc', -> doc = createDoc() expect(doc.get()).eql undefined it 'gets a defined doc', -> doc = createDoc() doc.set [], {id: 'green'}, -> expect(doc.get()).eql {id: 'green'} it 'gets a property on an undefined document', -> doc = createDoc() expect(doc.get ['id']).eql undefined it 'gets an undefined property', -> doc = createDoc() doc.set [], {}, -> expect(doc.get ['id']).eql undefined it 'gets a defined property', -> doc = createDoc() doc.set [], {id: 'green'}, -> expect(doc.get ['id']).eql 'green' it 'gets a false property', -> doc = createDoc() doc.set [], {id: 'green', shown: false}, -> expect(doc.get ['shown']).eql false it 'gets a null property', -> doc = createDoc() doc.set [], {id: 'green', shown: null}, -> expect(doc.get ['shown']).eql null it 'gets a method property', -> doc = createDoc() doc.set [], {empty: ''}, -> expect(doc.get ['empty', 'charAt']).eql ''.charAt it 'gets an array member', -> doc = createDoc() doc.set [], {rgb: [0, 255, 0]}, -> expect(doc.get ['rgb', '1']).eql 255 it 'gets an array length', -> doc = createDoc() doc.set [], {rgb: [0, 255, 0]}, -> expect(doc.get ['rgb', 'length']).eql 3 describe 'set', -> it 'sets an empty doc', -> doc = createDoc() previous = doc.set [], {}, -> expect(previous).equal undefined expect(doc.get()).eql {} it 'sets a property', -> doc = createDoc() previous = doc.set ['shown'], false, -> expect(previous).equal undefined expect(doc.get()).eql {shown: false} it 'sets a multi-nested property', -> doc = createDoc() previous = doc.set ['rgb', 'green', 'float'], 1, -> expect(previous).equal undefined expect(doc.get()).eql {rgb: {green: {float: 1}}} it 'sets on an existing document', -> doc = createDoc() previous = doc.set [], {}, -> expect(previous).equal undefined expect(doc.get()).eql {} previous = doc.set ['shown'], false, -> expect(previous).equal undefined expect(doc.get()).eql {shown: false} it 'returns the previous value on set', -> doc = createDoc() previous = doc.set ['shown'], false, -> expect(previous).equal undefined expect(doc.get()).eql {shown: false} previous = doc.set ['shown'], true, -> expect(previous).equal false expect(doc.get()).eql {shown: true} it 'creates an implied array on set', -> doc = createDoc() doc.set ['rgb', '2'], 0, -> doc.set ['rgb', '1'], 255, -> doc.set ['rgb', '0'], 127, -> expect(doc.get()).eql {rgb: [127, 255, 0]} it 'creates an implied object on an array', -> doc = createDoc() doc.set ['colors'], [], -> doc.set ['colors', '0', 'value'], 'green', -> expect(doc.get()).eql {colors: [{value: 'green'}]} describe 'del', -> it 'can del on an undefined path without effect', -> doc = createDoc() previous = doc.del ['rgb', '2'], -> expect(previous).equal undefined expect(doc.get()).eql undefined it 'can del on a document', -> doc = createDoc() doc.set [], {}, -> previous = doc.del [], -> expect(previous).eql {} expect(doc.get()).eql undefined it 'can del on a nested property', -> doc = createDoc() doc.set ['rgb'], [ {float: 0, int: 0} {float: 1, int: 255} {float: 0, int: 0} ], -> previous = doc.del ['rgb', '0', 'float'], -> expect(previous).eql 0 expect(doc.get ['rgb']).eql [ {int: 0} {float: 1, int: 255} {float: 0, int: 0} ] describe 'push', -> it 'can push on an undefined property', -> doc = createDoc() len = doc.push ['friends'], 'PI:NAME:<NAME>END_PI', -> expect(len).equal 1 expect(doc.get()).eql {friends: ['PI:NAME:<NAME>END_PI']} it 'can push on a defined array', -> doc = createDoc() len = doc.push ['friends'], 'PI:NAME:<NAME>END_PI', -> expect(len).equal 1 len = doc.push ['friends'], 'sue', -> expect(len).equal 2 expect(doc.get()).eql {friends: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']} it 'throws a TypeError when pushing on a non-array', (done) -> doc = createDoc() doc.set ['friends'], {}, -> doc.push ['friends'], ['x'], (err) -> expect(err).a TypeError done()
[ { "context": " 'K'\n name: 'kelvin'\n matchers: [ 'K', 'Kelvin', 'kelvin' ]\n reason: 'If you\\'re a quantum ", "end": 1061, "score": 0.5829622745513916, "start": 1055, "tag": "NAME", "value": "Kelvin" } ]
src/metric-bot.coffee
paulerickson/hubot-metricbot
0
module.exports = (robot) -> units = [ { symbol: 'F' name: 'Fahrenheit' matchers: [ 'F', 'Fahrenheit', 'Farenheit' ] reason: 'If you live in Liberia, Myanmar or other countries that use the imperial system' to: C: (degrees) -> Math.floor((degrees - 32) * (5 / 9)) K: (degrees) -> Math.floor((degrees + 459.67) * (5 / 9)) getEmoji: (degrees) -> switch when degrees <= 32 then ":snowflake:" when degrees < 80 then ":sun_behind_cloud:" else ":fire:" }, { symbol: 'C' name: 'Celsius' matchers: [ 'C', 'Celsius', 'Centigrade' ] reason: "If you can't read 'Murican" to: F: (degrees) -> Math.floor((9 * degrees / 5) + 32) K: (degrees) -> Math.floor(degrees + 273.15) getEmoji: (degrees) -> switch when degrees <= 0 then ":snowflake:" when degrees < 26 then ":sun_behind_cloud:" else ":fire:" }, { symbol: 'K' name: 'kelvin' matchers: [ 'K', 'Kelvin', 'kelvin' ] reason: 'If you\'re a quantum mechanic' ignoreMentions: true to: C: (degrees) -> degrees - 273.15 F: (degrees) -> degrees * (9 / 5) - 459.67 getEmoji: (degrees) -> "" }, { symbol: 'mi' name: 'miles' matchers: [ 'mile', 'miles', 'mi' ] reason: 'If you live in Liberia, Myanmar or other countries that use the imperial system' to: km: (n) -> n * 1.609344 getEmoji: (n) -> "" }, { symbol: 'km' name: 'kilometers' matchers: [ 'kilometer', 'kilometers', 'km' ] reason: "If you can't read 'Murican" to: mi: (n) -> n / 1.609344 getEmoji: (n) -> "" } ] negationTokens = 'negative |minus |-' number = "(?:#{negationTokens})?\\d+(?:\\.\\d+)?" unitTokens = units .map (unit) -> unit.matchers .reduce(((allMatchers, matchers) -> allMatchers.concat(matchers)), []) .join '|' explicitConvertMatcher = new RegExp("(?:convert)?\\s*(?:from)?\\s*(#{number})°?\\s?(#{unitTokens}) to (#{unitTokens})\\b", 'i') mentionedUnitMatcher = new RegExp("(?:^|[\\s,.;!?—–()])(#{number})°?\\s?(#{unitTokens})([\\s,.;!?—–()]|$)", 'i') negationMatcher = new RegExp(negationTokens, 'i') # parse and convert from text strings # amount and fromUnitToken are required; if toUnitToken isn't provided, defaults to the first unit that's convertible convert = (fromAmountString, fromUnitString, toUnitString) -> fromAmount = +fromAmountString.replace(negationMatcher, '-') fromUnit = units.find (unit) -> unit.matchers.find (matcher) -> matcher.toLowerCase() == fromUnitString.toLowerCase() toUnit = if toUnitString units.find (unit) -> unit.matchers.find (matcher) -> matcher.toLowerCase() == toUnitString.toLowerCase() else toUnit = units.find (unit) -> unit.to[fromUnit.symbol] toAmount = if fromUnit and toUnit and fromUnit.to[toUnit.symbol] fromUnit.to[toUnit.symbol](fromAmount) else null return { fromAmount, fromUnit, toAmount, toUnit } # Listen for any unit we know about, then see if it's an explicit command like "convert 0°C to F" or just a mention, like "I biked 20km" robot.hear new RegExp("#{unitTokens}\\b", 'i'), (res) -> explicitMatch = explicitConvertMatcher.exec(res.match.input); if (explicitMatch) { fromAmount, fromUnit, toAmount, toUnit } = convert(explicitMatch[1], explicitMatch[2], explicitMatch[3]) if toAmount == null return res.send "Sorry, I don't know how to convert #{fromUnit.name} to #{toUnit.name}" return res.send "#{fromAmount} #{fromUnit.name} is #{toAmount} #{toUnit.name}" mentionMatch = mentionedUnitMatcher.exec(res.match.input) if (mentionMatch) { fromAmount, fromUnit, toAmount, toUnit } = convert(mentionMatch[1], mentionMatch[2], null) if (fromUnit.ignoreMentions) return if fromAmount != null and fromUnit and toAmount != null and toUnit return res.send "#{toUnit.reason}, #{fromAmount} #{fromUnit.name} is #{toAmount} #{toUnit.name} #{toUnit.getEmoji(toAmount)}"
28527
module.exports = (robot) -> units = [ { symbol: 'F' name: 'Fahrenheit' matchers: [ 'F', 'Fahrenheit', 'Farenheit' ] reason: 'If you live in Liberia, Myanmar or other countries that use the imperial system' to: C: (degrees) -> Math.floor((degrees - 32) * (5 / 9)) K: (degrees) -> Math.floor((degrees + 459.67) * (5 / 9)) getEmoji: (degrees) -> switch when degrees <= 32 then ":snowflake:" when degrees < 80 then ":sun_behind_cloud:" else ":fire:" }, { symbol: 'C' name: 'Celsius' matchers: [ 'C', 'Celsius', 'Centigrade' ] reason: "If you can't read 'Murican" to: F: (degrees) -> Math.floor((9 * degrees / 5) + 32) K: (degrees) -> Math.floor(degrees + 273.15) getEmoji: (degrees) -> switch when degrees <= 0 then ":snowflake:" when degrees < 26 then ":sun_behind_cloud:" else ":fire:" }, { symbol: 'K' name: 'kelvin' matchers: [ 'K', '<NAME>', 'kelvin' ] reason: 'If you\'re a quantum mechanic' ignoreMentions: true to: C: (degrees) -> degrees - 273.15 F: (degrees) -> degrees * (9 / 5) - 459.67 getEmoji: (degrees) -> "" }, { symbol: 'mi' name: 'miles' matchers: [ 'mile', 'miles', 'mi' ] reason: 'If you live in Liberia, Myanmar or other countries that use the imperial system' to: km: (n) -> n * 1.609344 getEmoji: (n) -> "" }, { symbol: 'km' name: 'kilometers' matchers: [ 'kilometer', 'kilometers', 'km' ] reason: "If you can't read 'Murican" to: mi: (n) -> n / 1.609344 getEmoji: (n) -> "" } ] negationTokens = 'negative |minus |-' number = "(?:#{negationTokens})?\\d+(?:\\.\\d+)?" unitTokens = units .map (unit) -> unit.matchers .reduce(((allMatchers, matchers) -> allMatchers.concat(matchers)), []) .join '|' explicitConvertMatcher = new RegExp("(?:convert)?\\s*(?:from)?\\s*(#{number})°?\\s?(#{unitTokens}) to (#{unitTokens})\\b", 'i') mentionedUnitMatcher = new RegExp("(?:^|[\\s,.;!?—–()])(#{number})°?\\s?(#{unitTokens})([\\s,.;!?—–()]|$)", 'i') negationMatcher = new RegExp(negationTokens, 'i') # parse and convert from text strings # amount and fromUnitToken are required; if toUnitToken isn't provided, defaults to the first unit that's convertible convert = (fromAmountString, fromUnitString, toUnitString) -> fromAmount = +fromAmountString.replace(negationMatcher, '-') fromUnit = units.find (unit) -> unit.matchers.find (matcher) -> matcher.toLowerCase() == fromUnitString.toLowerCase() toUnit = if toUnitString units.find (unit) -> unit.matchers.find (matcher) -> matcher.toLowerCase() == toUnitString.toLowerCase() else toUnit = units.find (unit) -> unit.to[fromUnit.symbol] toAmount = if fromUnit and toUnit and fromUnit.to[toUnit.symbol] fromUnit.to[toUnit.symbol](fromAmount) else null return { fromAmount, fromUnit, toAmount, toUnit } # Listen for any unit we know about, then see if it's an explicit command like "convert 0°C to F" or just a mention, like "I biked 20km" robot.hear new RegExp("#{unitTokens}\\b", 'i'), (res) -> explicitMatch = explicitConvertMatcher.exec(res.match.input); if (explicitMatch) { fromAmount, fromUnit, toAmount, toUnit } = convert(explicitMatch[1], explicitMatch[2], explicitMatch[3]) if toAmount == null return res.send "Sorry, I don't know how to convert #{fromUnit.name} to #{toUnit.name}" return res.send "#{fromAmount} #{fromUnit.name} is #{toAmount} #{toUnit.name}" mentionMatch = mentionedUnitMatcher.exec(res.match.input) if (mentionMatch) { fromAmount, fromUnit, toAmount, toUnit } = convert(mentionMatch[1], mentionMatch[2], null) if (fromUnit.ignoreMentions) return if fromAmount != null and fromUnit and toAmount != null and toUnit return res.send "#{toUnit.reason}, #{fromAmount} #{fromUnit.name} is #{toAmount} #{toUnit.name} #{toUnit.getEmoji(toAmount)}"
true
module.exports = (robot) -> units = [ { symbol: 'F' name: 'Fahrenheit' matchers: [ 'F', 'Fahrenheit', 'Farenheit' ] reason: 'If you live in Liberia, Myanmar or other countries that use the imperial system' to: C: (degrees) -> Math.floor((degrees - 32) * (5 / 9)) K: (degrees) -> Math.floor((degrees + 459.67) * (5 / 9)) getEmoji: (degrees) -> switch when degrees <= 32 then ":snowflake:" when degrees < 80 then ":sun_behind_cloud:" else ":fire:" }, { symbol: 'C' name: 'Celsius' matchers: [ 'C', 'Celsius', 'Centigrade' ] reason: "If you can't read 'Murican" to: F: (degrees) -> Math.floor((9 * degrees / 5) + 32) K: (degrees) -> Math.floor(degrees + 273.15) getEmoji: (degrees) -> switch when degrees <= 0 then ":snowflake:" when degrees < 26 then ":sun_behind_cloud:" else ":fire:" }, { symbol: 'K' name: 'kelvin' matchers: [ 'K', 'PI:NAME:<NAME>END_PI', 'kelvin' ] reason: 'If you\'re a quantum mechanic' ignoreMentions: true to: C: (degrees) -> degrees - 273.15 F: (degrees) -> degrees * (9 / 5) - 459.67 getEmoji: (degrees) -> "" }, { symbol: 'mi' name: 'miles' matchers: [ 'mile', 'miles', 'mi' ] reason: 'If you live in Liberia, Myanmar or other countries that use the imperial system' to: km: (n) -> n * 1.609344 getEmoji: (n) -> "" }, { symbol: 'km' name: 'kilometers' matchers: [ 'kilometer', 'kilometers', 'km' ] reason: "If you can't read 'Murican" to: mi: (n) -> n / 1.609344 getEmoji: (n) -> "" } ] negationTokens = 'negative |minus |-' number = "(?:#{negationTokens})?\\d+(?:\\.\\d+)?" unitTokens = units .map (unit) -> unit.matchers .reduce(((allMatchers, matchers) -> allMatchers.concat(matchers)), []) .join '|' explicitConvertMatcher = new RegExp("(?:convert)?\\s*(?:from)?\\s*(#{number})°?\\s?(#{unitTokens}) to (#{unitTokens})\\b", 'i') mentionedUnitMatcher = new RegExp("(?:^|[\\s,.;!?—–()])(#{number})°?\\s?(#{unitTokens})([\\s,.;!?—–()]|$)", 'i') negationMatcher = new RegExp(negationTokens, 'i') # parse and convert from text strings # amount and fromUnitToken are required; if toUnitToken isn't provided, defaults to the first unit that's convertible convert = (fromAmountString, fromUnitString, toUnitString) -> fromAmount = +fromAmountString.replace(negationMatcher, '-') fromUnit = units.find (unit) -> unit.matchers.find (matcher) -> matcher.toLowerCase() == fromUnitString.toLowerCase() toUnit = if toUnitString units.find (unit) -> unit.matchers.find (matcher) -> matcher.toLowerCase() == toUnitString.toLowerCase() else toUnit = units.find (unit) -> unit.to[fromUnit.symbol] toAmount = if fromUnit and toUnit and fromUnit.to[toUnit.symbol] fromUnit.to[toUnit.symbol](fromAmount) else null return { fromAmount, fromUnit, toAmount, toUnit } # Listen for any unit we know about, then see if it's an explicit command like "convert 0°C to F" or just a mention, like "I biked 20km" robot.hear new RegExp("#{unitTokens}\\b", 'i'), (res) -> explicitMatch = explicitConvertMatcher.exec(res.match.input); if (explicitMatch) { fromAmount, fromUnit, toAmount, toUnit } = convert(explicitMatch[1], explicitMatch[2], explicitMatch[3]) if toAmount == null return res.send "Sorry, I don't know how to convert #{fromUnit.name} to #{toUnit.name}" return res.send "#{fromAmount} #{fromUnit.name} is #{toAmount} #{toUnit.name}" mentionMatch = mentionedUnitMatcher.exec(res.match.input) if (mentionMatch) { fromAmount, fromUnit, toAmount, toUnit } = convert(mentionMatch[1], mentionMatch[2], null) if (fromUnit.ignoreMentions) return if fromAmount != null and fromUnit and toAmount != null and toUnit return res.send "#{toUnit.reason}, #{fromAmount} #{fromUnit.name} is #{toAmount} #{toUnit.name} #{toUnit.getEmoji(toAmount)}"
[ { "context": "USERNAME = \"mjmuir\"\nPASSWORD = \"your-personal-access-token\"\n\nGitHubA", "end": 18, "score": 0.9996545314788818, "start": 12, "tag": "USERNAME", "value": "mjmuir" }, { "context": "USERNAME = \"mjmuir\"\nPASSWORD = \"your-personal-access-token\"\n\nGitHubApi = requi...
index.coffee
macaullyjames/g8ify
0
USERNAME = "mjmuir" PASSWORD = "your-personal-access-token" GitHubApi = require "github" github = new GitHubApi protocol: "https" host: "gits-15.sys.kth.se" pathPrefix: "/api/v3" Promise: require "bluebird" github.authenticate type: "basic" username: USERNAME password: PASSWORD repos = ["week-1"] labels = "style": "AB4523" "documentation": "EF1212" for r in repos for n, c of labels do -> [repo, name, color] = [r, n, c] github.issues.createLabel( user: "inda-16" repo: repo name: name color: color ) .then -> console.log "#{name} label was added to #{repo}" .catch -> console.log "#{name} label was already present in #{repo}"
14134
USERNAME = "mjmuir" PASSWORD = "<PASSWORD>" GitHubApi = require "github" github = new GitHubApi protocol: "https" host: "gits-15.sys.kth.se" pathPrefix: "/api/v3" Promise: require "bluebird" github.authenticate type: "basic" username: USERNAME password: <PASSWORD> repos = ["week-1"] labels = "style": "AB4523" "documentation": "EF1212" for r in repos for n, c of labels do -> [repo, name, color] = [r, n, c] github.issues.createLabel( user: "inda-16" repo: repo name: name color: color ) .then -> console.log "#{name} label was added to #{repo}" .catch -> console.log "#{name} label was already present in #{repo}"
true
USERNAME = "mjmuir" PASSWORD = "PI:PASSWORD:<PASSWORD>END_PI" GitHubApi = require "github" github = new GitHubApi protocol: "https" host: "gits-15.sys.kth.se" pathPrefix: "/api/v3" Promise: require "bluebird" github.authenticate type: "basic" username: USERNAME password: PI:PASSWORD:<PASSWORD>END_PI repos = ["week-1"] labels = "style": "AB4523" "documentation": "EF1212" for r in repos for n, c of labels do -> [repo, name, color] = [r, n, c] github.issues.createLabel( user: "inda-16" repo: repo name: name color: color ) .then -> console.log "#{name} label was added to #{repo}" .catch -> console.log "#{name} label was already present in #{repo}"
[ { "context": "====================\n\nmodule.exports =\n name: \"Moonlight Sonata\"\n composer: \"Beethoven\"\n", "end": 144, "score": 0.9992812871932983, "start": 128, "tag": "NAME", "value": "Moonlight Sonata" }, { "context": "rts =\n name: \"Moonlight Sonata\"\n compos...
GoF/idiomatic/Behavioral/Interpreter/CoffeeScript/API/context.coffee
irynaO/JavaScript-Design-Patterns
293
'use strict' # ============================== # CONTEXT (SONATA) # ============================== module.exports = name: "Moonlight Sonata" composer: "Beethoven"
209028
'use strict' # ============================== # CONTEXT (SONATA) # ============================== module.exports = name: "<NAME>" composer: "<NAME>"
true
'use strict' # ============================== # CONTEXT (SONATA) # ============================== module.exports = name: "PI:NAME:<NAME>END_PI" composer: "PI:NAME:<NAME>END_PI"
[ { "context": "# Author: 易晓峰\n# E-mail: wvv8oo@gmail.com\n# Date: 6/1/15 9", "end": 16, "score": 0.9995092153549194, "start": 13, "tag": "NAME", "value": "易晓峰" }, { "context": "# Author: 易晓峰\n# E-mail: wvv8oo@gmail.com\n# Date: 6/1/15 9:53 AM\n# Description: 设备与用户...
src/entity/member_device.coffee
kiteam/kiteam
0
# Author: 易晓峰 # E-mail: wvv8oo@gmail.com # Date: 6/1/15 9:53 AM # Description: 设备与用户的关系 _BaseEntity = require('bijou').BaseEntity _async = require 'async' _common = require '../common' class MemberDevice extends _BaseEntity constructor: ()-> super require('../schema/member_device').schema module.exports = new MemberDevice
1635
# Author: <NAME> # E-mail: <EMAIL> # Date: 6/1/15 9:53 AM # Description: 设备与用户的关系 _BaseEntity = require('bijou').BaseEntity _async = require 'async' _common = require '../common' class MemberDevice extends _BaseEntity constructor: ()-> super require('../schema/member_device').schema module.exports = new MemberDevice
true
# Author: PI:NAME:<NAME>END_PI # E-mail: PI:EMAIL:<EMAIL>END_PI # Date: 6/1/15 9:53 AM # Description: 设备与用户的关系 _BaseEntity = require('bijou').BaseEntity _async = require 'async' _common = require '../common' class MemberDevice extends _BaseEntity constructor: ()-> super require('../schema/member_device').schema module.exports = new MemberDevice
[ { "context": "dule.exports = \n version: '0.0.1'\n author: 'Contra'\n", "end": 112, "score": 0.567599356174469, "start": 109, "tag": "USERNAME", "value": "Con" }, { "context": "e.exports = \n version: '0.0.1'\n author: 'Contra'\n", "end": 115, "score": 0.758977293...
src/nova.coffee
contra/nova
2
require.register 'nova', (module, exports, require) -> module.exports = version: '0.0.1' author: 'Contra'
112886
require.register 'nova', (module, exports, require) -> module.exports = version: '0.0.1' author: 'Con<NAME>'
true
require.register 'nova', (module, exports, require) -> module.exports = version: '0.0.1' author: 'ConPI:NAME:<NAME>END_PI'
[ { "context": "hank-you-for-considering'\n hashedToken: 'ZOGZOX7K4XywpyNFjVS+6SfbXFux8FNW7VT6NWmsz6E='\n metadata: {\n createdAt: new ", "end": 795, "score": 0.6263196468353271, "start": 752, "tag": "PASSWORD", "value": "ZOGZOX7K4XywpyNFjVS+6SfbXFux8FNW7VT6NWmsz6E...
test/check-token-spec.coffee
octoblu/meshblu-core-task-check-token
0
Datastore = require 'meshblu-core-datastore' CheckToken = require '../src/check-token' mongojs = require 'mongojs' describe 'CheckToken', -> beforeEach (done) -> @uuidAliasResolver = resolve: (uuid, callback) => callback null, uuid database = mongojs 'meshblu-core-task-check-token', ['tokens'] @datastore = new Datastore database: database collection: 'tokens' database.tokens.remove done beforeEach -> @sut = new CheckToken datastore: @datastore pepper: 'totally-a-secret' uuidAliasResolver: @uuidAliasResolver describe '->do', -> context 'when given a valid token', -> beforeEach (done) -> record = uuid: 'thank-you-for-considering' hashedToken: 'ZOGZOX7K4XywpyNFjVS+6SfbXFux8FNW7VT6NWmsz6E=' metadata: { createdAt: new Date() } @datastore.insert record, done beforeEach (done) -> request = metadata: responseId: 'used-as-biofuel' auth: uuid: 'thank-you-for-considering' token: 'the-environment' @sut.do request, (error, @response) => done error it 'should respond with a 204', -> expectedResponse = metadata: responseId: 'used-as-biofuel' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when given a invalid token', -> beforeEach (done) -> record = uuid: 'thank-you-for-considering' hashedToken: 'this-will-not-work' @datastore.insert record, done beforeEach (done) -> request = metadata: responseId: 'axed' auth: uuid: 'hatcheted' token: 'bodysprayed' @sut.do request, (error, @response) => done error it 'should respond with a 401', -> expectedResponse = metadata: responseId: 'axed' code: 401 status: 'Unauthorized' expect(@response).to.deep.equal expectedResponse
1423
Datastore = require 'meshblu-core-datastore' CheckToken = require '../src/check-token' mongojs = require 'mongojs' describe 'CheckToken', -> beforeEach (done) -> @uuidAliasResolver = resolve: (uuid, callback) => callback null, uuid database = mongojs 'meshblu-core-task-check-token', ['tokens'] @datastore = new Datastore database: database collection: 'tokens' database.tokens.remove done beforeEach -> @sut = new CheckToken datastore: @datastore pepper: 'totally-a-secret' uuidAliasResolver: @uuidAliasResolver describe '->do', -> context 'when given a valid token', -> beforeEach (done) -> record = uuid: 'thank-you-for-considering' hashedToken: '<PASSWORD>=' metadata: { createdAt: new Date() } @datastore.insert record, done beforeEach (done) -> request = metadata: responseId: 'used-as-biofuel' auth: uuid: 'thank-you-for-considering' token: '<PASSWORD>' @sut.do request, (error, @response) => done error it 'should respond with a 204', -> expectedResponse = metadata: responseId: 'used-as-biofuel' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when given a invalid token', -> beforeEach (done) -> record = uuid: 'thank-you-for-considering' hashedToken: '<PASSWORD>' @datastore.insert record, done beforeEach (done) -> request = metadata: responseId: 'axed' auth: uuid: 'hatcheted' token: '<PASSWORD>' @sut.do request, (error, @response) => done error it 'should respond with a 401', -> expectedResponse = metadata: responseId: 'axed' code: 401 status: 'Unauthorized' expect(@response).to.deep.equal expectedResponse
true
Datastore = require 'meshblu-core-datastore' CheckToken = require '../src/check-token' mongojs = require 'mongojs' describe 'CheckToken', -> beforeEach (done) -> @uuidAliasResolver = resolve: (uuid, callback) => callback null, uuid database = mongojs 'meshblu-core-task-check-token', ['tokens'] @datastore = new Datastore database: database collection: 'tokens' database.tokens.remove done beforeEach -> @sut = new CheckToken datastore: @datastore pepper: 'totally-a-secret' uuidAliasResolver: @uuidAliasResolver describe '->do', -> context 'when given a valid token', -> beforeEach (done) -> record = uuid: 'thank-you-for-considering' hashedToken: 'PI:PASSWORD:<PASSWORD>END_PI=' metadata: { createdAt: new Date() } @datastore.insert record, done beforeEach (done) -> request = metadata: responseId: 'used-as-biofuel' auth: uuid: 'thank-you-for-considering' token: 'PI:PASSWORD:<PASSWORD>END_PI' @sut.do request, (error, @response) => done error it 'should respond with a 204', -> expectedResponse = metadata: responseId: 'used-as-biofuel' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when given a invalid token', -> beforeEach (done) -> record = uuid: 'thank-you-for-considering' hashedToken: 'PI:PASSWORD:<PASSWORD>END_PI' @datastore.insert record, done beforeEach (done) -> request = metadata: responseId: 'axed' auth: uuid: 'hatcheted' token: 'PI:PASSWORD:<PASSWORD>END_PI' @sut.do request, (error, @response) => done error it 'should respond with a 401', -> expectedResponse = metadata: responseId: 'axed' code: 401 status: 'Unauthorized' expect(@response).to.deep.equal expectedResponse
[ { "context": "* grunt-bookmarklet-thingy\n# * https://github.com/justspamjustin/grunt-bookmarklet-thingy\n# *\n# * Copyright (c) 20", "end": 68, "score": 0.9996142983436584, "start": 54, "tag": "USERNAME", "value": "justspamjustin" }, { "context": "runt-bookmarklet-thingy\n# *\n# * C...
tasks/bookmarklet-thingy.coffee
justspamjustin/grunt-bookmarklet-thingy
2
# # * grunt-bookmarklet-thingy # * https://github.com/justspamjustin/grunt-bookmarklet-thingy # * # * Copyright (c) 2013 Justin Martin # * Licensed under the MIT license. # bookmarkletify = require("bookmarkletify") fs = require("fs") bookmarkletWarnLength = 2000 module.exports = (grunt) -> # ========================================================================== # TASKS # ========================================================================== grunt.registerMultiTask "bookmarklet", "Builds a bookmarklet based on your provided source files.", -> timestamp = (if @data.timestamp then " + '?t=' + Date.now()" else '') # Use a macro for __HOST__ hostMacro = '__HOST__' host = (if @data.host && @data.amdify then "'" + hostMacro + "' + " else '') getBody = => body = '' if @data.body body+= fs.readFileSync("./#{@data.body}") return body getContent = (body) => content = '' content += """ var numDependencies = 0, loadedDependencies = 0; """ if @data.js content += """numDependencies += #{@data.js.length};\n""" if @data.css content += """numDependencies += #{@data.css.length};\n""" if @data.js content += """ var scriptUrls = #{JSON.stringify(@data.js)}; #{ if @data.jsIds if @data.jsIds.length isnt @data.js.length then throw new Error("You must provide the same number of IDs as scripts") "var scriptIds = #{JSON.stringify(@data.jsIds)};" else "" } for(var i = 0; i < scriptUrls.length; i++) { var url = scriptUrls[i]; var script = document.createElement('script'); script.src = #{host}url#{timestamp}; #{if @data.jsIds then "script.id = scriptIds[i];" else ""} script.type = 'text/javascript'; script.onload = scriptLoaded; document.body.appendChild(script); } """ if(@data.css) content += """ var styleUrls = #{JSON.stringify(@data.css)}; #{ if @data.cssIds if @data.cssIds.length isnt @data.css.length then throw new Error("You must provide the same number of IDs as css") "var styleIds = #{JSON.stringify(@data.cssIds)};" else "" } for(var i = 0; i < styleUrls.length; i++) { var url = styleUrls[i]; var link = document.createElement('link'); link.href = #{host}url#{timestamp}; #{if @data.cssIds then "link.id = styleIds[i];" else ""} link.type = 'text/css'; link.rel = 'stylesheet'; link.onload = scriptLoaded; document.head.appendChild(link); } """ content += """ function scriptLoaded() { loadedDependencies++; if(numDependencies === loadedDependencies) { afterDepsLoaded(); } } function afterDepsLoaded() { #{body} } """ if @data.js && @data.css if @data.js.length + @data.css.length == 0 content += "afterDepsLoaded();\n" else content += "afterDepsLoaded();\n" return content checkBookmarkletLength = (bookmarklet) => if bookmarklet.length > bookmarkletWarnLength grunt.log.writeln("WARNING: Your bookmarklet is longer than #{bookmarkletWarnLength} characters. It may not work in some browsers.") amdifyBookmarklet = (bookmarklet) => comment = "// Generated by grunt-bookmarklet-thingy. Refer to your grunt configuration file for configuration options." if @data.amdify hostParam = (if @data.host then 'host' else '') bookmarklet = bookmarklet.replace(new RegExp(hostMacro,'g'),"' + host + '") bookmarklet = """ define([], function () { #{if @data.jshint then "'use strict';" else ""} return { getBookmarklet: function (#{hostParam}) { return '#{bookmarklet}'; } }; }); """ bookmarklet = "#{comment}\n#{bookmarklet}" if @data.jshint bookmarklet = "/*jshint scripturl:true*/\n#{bookmarklet}" return bookmarklet outputBookmarklet = (bookmarklet) => if @data.out fs.writeFileSync("./#{@data.out}",bookmarklet) else grunt.log.writeln(bookmarklet) body = getBody() content = getContent(body) bookmarklet = bookmarkletify(content) checkBookmarkletLength(bookmarklet) bookmarklet = amdifyBookmarklet(bookmarklet) outputBookmarklet(bookmarklet)
71392
# # * grunt-bookmarklet-thingy # * https://github.com/justspamjustin/grunt-bookmarklet-thingy # * # * Copyright (c) 2013 <NAME> # * Licensed under the MIT license. # bookmarkletify = require("bookmarkletify") fs = require("fs") bookmarkletWarnLength = 2000 module.exports = (grunt) -> # ========================================================================== # TASKS # ========================================================================== grunt.registerMultiTask "bookmarklet", "Builds a bookmarklet based on your provided source files.", -> timestamp = (if @data.timestamp then " + '?t=' + Date.now()" else '') # Use a macro for __HOST__ hostMacro = '__HOST__' host = (if @data.host && @data.amdify then "'" + hostMacro + "' + " else '') getBody = => body = '' if @data.body body+= fs.readFileSync("./#{@data.body}") return body getContent = (body) => content = '' content += """ var numDependencies = 0, loadedDependencies = 0; """ if @data.js content += """numDependencies += #{@data.js.length};\n""" if @data.css content += """numDependencies += #{@data.css.length};\n""" if @data.js content += """ var scriptUrls = #{JSON.stringify(@data.js)}; #{ if @data.jsIds if @data.jsIds.length isnt @data.js.length then throw new Error("You must provide the same number of IDs as scripts") "var scriptIds = #{JSON.stringify(@data.jsIds)};" else "" } for(var i = 0; i < scriptUrls.length; i++) { var url = scriptUrls[i]; var script = document.createElement('script'); script.src = #{host}url#{timestamp}; #{if @data.jsIds then "script.id = scriptIds[i];" else ""} script.type = 'text/javascript'; script.onload = scriptLoaded; document.body.appendChild(script); } """ if(@data.css) content += """ var styleUrls = #{JSON.stringify(@data.css)}; #{ if @data.cssIds if @data.cssIds.length isnt @data.css.length then throw new Error("You must provide the same number of IDs as css") "var styleIds = #{JSON.stringify(@data.cssIds)};" else "" } for(var i = 0; i < styleUrls.length; i++) { var url = styleUrls[i]; var link = document.createElement('link'); link.href = #{host}url#{timestamp}; #{if @data.cssIds then "link.id = styleIds[i];" else ""} link.type = 'text/css'; link.rel = 'stylesheet'; link.onload = scriptLoaded; document.head.appendChild(link); } """ content += """ function scriptLoaded() { loadedDependencies++; if(numDependencies === loadedDependencies) { afterDepsLoaded(); } } function afterDepsLoaded() { #{body} } """ if @data.js && @data.css if @data.js.length + @data.css.length == 0 content += "afterDepsLoaded();\n" else content += "afterDepsLoaded();\n" return content checkBookmarkletLength = (bookmarklet) => if bookmarklet.length > bookmarkletWarnLength grunt.log.writeln("WARNING: Your bookmarklet is longer than #{bookmarkletWarnLength} characters. It may not work in some browsers.") amdifyBookmarklet = (bookmarklet) => comment = "// Generated by grunt-bookmarklet-thingy. Refer to your grunt configuration file for configuration options." if @data.amdify hostParam = (if @data.host then 'host' else '') bookmarklet = bookmarklet.replace(new RegExp(hostMacro,'g'),"' + host + '") bookmarklet = """ define([], function () { #{if @data.jshint then "'use strict';" else ""} return { getBookmarklet: function (#{hostParam}) { return '#{bookmarklet}'; } }; }); """ bookmarklet = "#{comment}\n#{bookmarklet}" if @data.jshint bookmarklet = "/*jshint scripturl:true*/\n#{bookmarklet}" return bookmarklet outputBookmarklet = (bookmarklet) => if @data.out fs.writeFileSync("./#{@data.out}",bookmarklet) else grunt.log.writeln(bookmarklet) body = getBody() content = getContent(body) bookmarklet = bookmarkletify(content) checkBookmarkletLength(bookmarklet) bookmarklet = amdifyBookmarklet(bookmarklet) outputBookmarklet(bookmarklet)
true
# # * grunt-bookmarklet-thingy # * https://github.com/justspamjustin/grunt-bookmarklet-thingy # * # * Copyright (c) 2013 PI:NAME:<NAME>END_PI # * Licensed under the MIT license. # bookmarkletify = require("bookmarkletify") fs = require("fs") bookmarkletWarnLength = 2000 module.exports = (grunt) -> # ========================================================================== # TASKS # ========================================================================== grunt.registerMultiTask "bookmarklet", "Builds a bookmarklet based on your provided source files.", -> timestamp = (if @data.timestamp then " + '?t=' + Date.now()" else '') # Use a macro for __HOST__ hostMacro = '__HOST__' host = (if @data.host && @data.amdify then "'" + hostMacro + "' + " else '') getBody = => body = '' if @data.body body+= fs.readFileSync("./#{@data.body}") return body getContent = (body) => content = '' content += """ var numDependencies = 0, loadedDependencies = 0; """ if @data.js content += """numDependencies += #{@data.js.length};\n""" if @data.css content += """numDependencies += #{@data.css.length};\n""" if @data.js content += """ var scriptUrls = #{JSON.stringify(@data.js)}; #{ if @data.jsIds if @data.jsIds.length isnt @data.js.length then throw new Error("You must provide the same number of IDs as scripts") "var scriptIds = #{JSON.stringify(@data.jsIds)};" else "" } for(var i = 0; i < scriptUrls.length; i++) { var url = scriptUrls[i]; var script = document.createElement('script'); script.src = #{host}url#{timestamp}; #{if @data.jsIds then "script.id = scriptIds[i];" else ""} script.type = 'text/javascript'; script.onload = scriptLoaded; document.body.appendChild(script); } """ if(@data.css) content += """ var styleUrls = #{JSON.stringify(@data.css)}; #{ if @data.cssIds if @data.cssIds.length isnt @data.css.length then throw new Error("You must provide the same number of IDs as css") "var styleIds = #{JSON.stringify(@data.cssIds)};" else "" } for(var i = 0; i < styleUrls.length; i++) { var url = styleUrls[i]; var link = document.createElement('link'); link.href = #{host}url#{timestamp}; #{if @data.cssIds then "link.id = styleIds[i];" else ""} link.type = 'text/css'; link.rel = 'stylesheet'; link.onload = scriptLoaded; document.head.appendChild(link); } """ content += """ function scriptLoaded() { loadedDependencies++; if(numDependencies === loadedDependencies) { afterDepsLoaded(); } } function afterDepsLoaded() { #{body} } """ if @data.js && @data.css if @data.js.length + @data.css.length == 0 content += "afterDepsLoaded();\n" else content += "afterDepsLoaded();\n" return content checkBookmarkletLength = (bookmarklet) => if bookmarklet.length > bookmarkletWarnLength grunt.log.writeln("WARNING: Your bookmarklet is longer than #{bookmarkletWarnLength} characters. It may not work in some browsers.") amdifyBookmarklet = (bookmarklet) => comment = "// Generated by grunt-bookmarklet-thingy. Refer to your grunt configuration file for configuration options." if @data.amdify hostParam = (if @data.host then 'host' else '') bookmarklet = bookmarklet.replace(new RegExp(hostMacro,'g'),"' + host + '") bookmarklet = """ define([], function () { #{if @data.jshint then "'use strict';" else ""} return { getBookmarklet: function (#{hostParam}) { return '#{bookmarklet}'; } }; }); """ bookmarklet = "#{comment}\n#{bookmarklet}" if @data.jshint bookmarklet = "/*jshint scripturl:true*/\n#{bookmarklet}" return bookmarklet outputBookmarklet = (bookmarklet) => if @data.out fs.writeFileSync("./#{@data.out}",bookmarklet) else grunt.log.writeln(bookmarklet) body = getBody() content = getContent(body) bookmarklet = bookmarkletify(content) checkBookmarkletLength(bookmarklet) bookmarklet = amdifyBookmarklet(bookmarklet) outputBookmarklet(bookmarklet)
[ { "context": "\n\nagent ={\n\t\"serialKey\": \"serial\",\n\t\"stoken\": \"stoken\",\n\t\"bolt\": {\n\t\t\"uplinks\": [\n\t\t \"stormtower.dev.in", "end": 364, "score": 0.4990513026714325, "start": 361, "tag": "PASSWORD", "value": "ken" }, { "context": "(response)->\n\t#\t\t\tassert.e...
test/agent-manager.coffee
chandrashekharh/stormtracker
1
global.config = require('../package').config AgentManager = require("../lib/http/agents").AgentManager CertificateManager = require("../lib/http/certs").CertificateManager uuid = require("uuid") fs = require("fs") certainly = require("security/certainly") HttpClient = require("../lib/http/client").HttpClient agent ={ "serialKey": "serial", "stoken": "stoken", "bolt": { "uplinks": [ "stormtower.dev.intercloud.net" ], "beaconInterval": 10, "beaconRetry": 2, "uplinkStrategy": "roundrobin" } } assert = require("assert") client = new HttpClient "localhost",8123 describe "AgentManager", -> # describe "create()", -> # it "Must create the agent object", (done)-> # headers = {} # client.post "/agents",agent,headers,(response)-> # assert.equal response.password,"password" # agent.id = response.id # done() describe "getAgent()", -> before (done)-> headers = {} client.post "/agents",agent,headers,(err,response)-> console.log JSON.stringify response assert.equal response.serialKey,"serial" agent.id = response.id done() it "Must list the objects of agent", (done)-> headers = "Authorization" : "Basic YWdlbnQwMDc6cGFzc3dvcmQ=" client.post "/agents",agent,headers,(err,response)-> assert.equal response.serialKey,"serial" client.get "/agents/"+response.id,headers,(err,response) -> assert.equal response.bolt.ca.encoding,"base64" done() describe "getAgentBySerial()", (done)-> before (done)-> headers = {} client.post "/agents",agent,headers,(err,response)-> assert.equal response.serialKey,"serial" agent.id = response.id done() it "Must get the object via serialKey", -> headers = "Authorization" : "Basic YWdlbnQwMDc6cGFzc3dvcmQ=" client.get "/agents/serialKey/#{agent.serialKey}",headers,(err,response)-> assert.equal agent.serialKey,response.serialKey describe "signCSR()", -> cm = new CertificateManager it "Must sign the csr request", (done)-> cert = cm.blankCert("agent1@clearpathnet.com","email:copy","agent007@clearpathnet.com",7600,false) headers = "Authorization" : "Basic YWdlbnQwMDc6cGFzc3dvcmQ=" certainly.genKey cert,(err,certRequest)-> done(err) if err? certainly.newCSR certRequest , (err,csrRequest) -> done(err) if err? cabundle = encoding:"base64" data:new Buffer(csrRequest.csr).toString("base64") client.post "/agents/#{agent.id}/csr",cabundle,headers,(err,response)-> assert.equal response.encoding,"base64" assert.notEqual response.data,"" done() describe "getBoltConfig()",-> before (done)-> headers = {} client.post "/agents",agent,headers,(err,response)-> assert.equal response.serialKey,"serial" agent.id = response.id done() it "Get the bolt config", (done) -> headers = "Authorization" : "Basic YWdlbnQwMDc6cGFzc3dvcmQ=" client.get "/agents/#{agent.id}/bolt",headers,(err,response) -> assert.equal response.cabundle.encoding,"base64" done()
139724
global.config = require('../package').config AgentManager = require("../lib/http/agents").AgentManager CertificateManager = require("../lib/http/certs").CertificateManager uuid = require("uuid") fs = require("fs") certainly = require("security/certainly") HttpClient = require("../lib/http/client").HttpClient agent ={ "serialKey": "serial", "stoken": "sto<PASSWORD>", "bolt": { "uplinks": [ "stormtower.dev.intercloud.net" ], "beaconInterval": 10, "beaconRetry": 2, "uplinkStrategy": "roundrobin" } } assert = require("assert") client = new HttpClient "localhost",8123 describe "AgentManager", -> # describe "create()", -> # it "Must create the agent object", (done)-> # headers = {} # client.post "/agents",agent,headers,(response)-> # assert.equal response.password,"<PASSWORD>" # agent.id = response.id # done() describe "getAgent()", -> before (done)-> headers = {} client.post "/agents",agent,headers,(err,response)-> console.log JSON.stringify response assert.equal response.serialKey,"serial" agent.id = response.id done() it "Must list the objects of agent", (done)-> headers = "Authorization" : "Basic YWdlbnQwMDc6cGFzc3dvcmQ=" client.post "/agents",agent,headers,(err,response)-> assert.equal response.serialKey,"serial" client.get "/agents/"+response.id,headers,(err,response) -> assert.equal response.bolt.ca.encoding,"base64" done() describe "getAgentBySerial()", (done)-> before (done)-> headers = {} client.post "/agents",agent,headers,(err,response)-> assert.equal response.serialKey,"serial" agent.id = response.id done() it "Must get the object via serialKey", -> headers = "Authorization" : "Basic YWdlbnQwMDc6cGFzc3dvcmQ=" client.get "/agents/serialKey/#{agent.serialKey}",headers,(err,response)-> assert.equal agent.serialKey,response.serialKey describe "signCSR()", -> cm = new CertificateManager it "Must sign the csr request", (done)-> cert = cm.blankCert("<EMAIL>","email:copy","<EMAIL>",7600,false) headers = "Authorization" : "Basic YWdlbnQwMDc6cGFzc3dvcmQ=" certainly.genKey cert,(err,certRequest)-> done(err) if err? certainly.newCSR certRequest , (err,csrRequest) -> done(err) if err? cabundle = encoding:"base64" data:new Buffer(csrRequest.csr).toString("base64") client.post "/agents/#{agent.id}/csr",cabundle,headers,(err,response)-> assert.equal response.encoding,"base64" assert.notEqual response.data,"" done() describe "getBoltConfig()",-> before (done)-> headers = {} client.post "/agents",agent,headers,(err,response)-> assert.equal response.serialKey,"serial" agent.id = response.id done() it "Get the bolt config", (done) -> headers = "Authorization" : "Basic YWdlbnQwMDc6cGFzc3dvcmQ=" client.get "/agents/#{agent.id}/bolt",headers,(err,response) -> assert.equal response.cabundle.encoding,"base64" done()
true
global.config = require('../package').config AgentManager = require("../lib/http/agents").AgentManager CertificateManager = require("../lib/http/certs").CertificateManager uuid = require("uuid") fs = require("fs") certainly = require("security/certainly") HttpClient = require("../lib/http/client").HttpClient agent ={ "serialKey": "serial", "stoken": "stoPI:PASSWORD:<PASSWORD>END_PI", "bolt": { "uplinks": [ "stormtower.dev.intercloud.net" ], "beaconInterval": 10, "beaconRetry": 2, "uplinkStrategy": "roundrobin" } } assert = require("assert") client = new HttpClient "localhost",8123 describe "AgentManager", -> # describe "create()", -> # it "Must create the agent object", (done)-> # headers = {} # client.post "/agents",agent,headers,(response)-> # assert.equal response.password,"PI:PASSWORD:<PASSWORD>END_PI" # agent.id = response.id # done() describe "getAgent()", -> before (done)-> headers = {} client.post "/agents",agent,headers,(err,response)-> console.log JSON.stringify response assert.equal response.serialKey,"serial" agent.id = response.id done() it "Must list the objects of agent", (done)-> headers = "Authorization" : "Basic YWdlbnQwMDc6cGFzc3dvcmQ=" client.post "/agents",agent,headers,(err,response)-> assert.equal response.serialKey,"serial" client.get "/agents/"+response.id,headers,(err,response) -> assert.equal response.bolt.ca.encoding,"base64" done() describe "getAgentBySerial()", (done)-> before (done)-> headers = {} client.post "/agents",agent,headers,(err,response)-> assert.equal response.serialKey,"serial" agent.id = response.id done() it "Must get the object via serialKey", -> headers = "Authorization" : "Basic YWdlbnQwMDc6cGFzc3dvcmQ=" client.get "/agents/serialKey/#{agent.serialKey}",headers,(err,response)-> assert.equal agent.serialKey,response.serialKey describe "signCSR()", -> cm = new CertificateManager it "Must sign the csr request", (done)-> cert = cm.blankCert("PI:EMAIL:<EMAIL>END_PI","email:copy","PI:EMAIL:<EMAIL>END_PI",7600,false) headers = "Authorization" : "Basic YWdlbnQwMDc6cGFzc3dvcmQ=" certainly.genKey cert,(err,certRequest)-> done(err) if err? certainly.newCSR certRequest , (err,csrRequest) -> done(err) if err? cabundle = encoding:"base64" data:new Buffer(csrRequest.csr).toString("base64") client.post "/agents/#{agent.id}/csr",cabundle,headers,(err,response)-> assert.equal response.encoding,"base64" assert.notEqual response.data,"" done() describe "getBoltConfig()",-> before (done)-> headers = {} client.post "/agents",agent,headers,(err,response)-> assert.equal response.serialKey,"serial" agent.id = response.id done() it "Get the bolt config", (done) -> headers = "Authorization" : "Basic YWdlbnQwMDc6cGFzc3dvcmQ=" client.get "/agents/#{agent.id}/bolt",headers,(err,response) -> assert.equal response.cabundle.encoding,"base64" done()
[ { "context": "# Alexander Danylchenko\n# BMC tpl\\tplre language completions snippet.\n# 2", "end": 23, "score": 0.9998291730880737, "start": 2, "tag": "NAME", "value": "Alexander Danylchenko" } ]
snippets/language-tplpre.cson
triaglesis/language-tplpre
1
# Alexander Danylchenko # BMC tpl\tplre language completions snippet. # 2017-08-14 - Latest version. ".source.tplpre": # PATTERN BLOCK COMPLETIONS:: "_Copyright BMC Copyright": prefix: "_Copyright_BMC_Copyright_" body: "// INFO: Add current year!\n// (c) Copyright 2019 BMC Software, Inc. All rights reserved.$0" description: 'Copyright info' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/The+Pattern+Language+TPL' "_tpl": prefix: "_tpl" body: "tpl \\$\\$TPLVERSION\\$\\$ module ${1:Module}.${2:Name};$0" description: 'Dev option. Header for TPLPreprocessor' "_pattern": prefix: "_pattern" description: 'Pattern block template' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Pattern+Overview' body: """ pattern ${1:PatternName} 1.0 \"\"\" Pattern trigger on ... Pattern also tries to ... Supported platforms: UNIX Windows \"\"\" metadata products := ''; urls := ''; publishers := ''; categories := ''; known_versions := '', '', ''; end metadata; overview tags TKU, TKU_YYYY_MM_DD, Name, Product; end overview; constants si_type := 'Product Name'; end constants; triggers on process := DiscoveredProcess where cmd matches unix_cmd \"CMD\" and args matches regex \"ARGS\"; end triggers; body host := model.host(process); end body; end pattern; $0 """ "from SearchFunctions": prefix: "from_SearchFunctions_" body: "// INFO: Check the latest version!\nfrom SearchFunctions import SearchFunctions ${1:1}.${2:0};$0" "from RDBMSFunctions": prefix: "from_RDBMSFunctions_" body: "// INFO: Check the latest version!\nfrom RDBMSFunctions import RDBMSFunctions ${1:1}.${2:0};$0" "from DiscoveryFunctions": prefix: "from_DiscoveryFunctions_" body: "// INFO: Check the latest version!\nfrom DiscoveryFunctions import DiscoveryFunctions ${1:1}.${2:0};$0" "from ConversionFunctions": prefix: "from_ConversionFunctions_" body: "// INFO: Check the latest version!\nfrom ConversionFunctions import ConversionFunctions ${1:1}.${2:0};$0" "import Future": prefix: "from_System_Future" body: "// INFO: Check the latest version!\nfrom System import Future ${1:1}.${2:0};$0" # METADATA: "metadata pattern": prefix: "_metadata_pattern" description: 'Metadata in pattern body block template' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Pattern+Overview' body: """ metadata products := \"\"; urls := \"\"; publishers := \"\"; categories := \"\"; known_versions := \"\", \"\", \"\", \"\", \"\"; end metadata; $0 """ "metadata module": prefix: "_metadata_module" description: 'Metadata in module block template' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Pattern+Overview' body: """ metadata origin := \"TKU\"; tkn_name := \"${1:name}\"; tree_path := '${2:category}', '${3:category}', '${4:category}'; end metadata; $0 """ # TRIGGER: "_triggers unix_cmd": prefix: "_triggers_unix_cmd_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on process := DiscoveredProcess where cmd matches unix_cmd \"${1:name}\"; end triggers; $0 """ "_triggers windows_cmd": prefix: "_triggers_windows_cmd_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on process := DiscoveredProcess where cmd matches windows_cmd \"${1:name}\"; end triggers; $0 """ "_triggers host": prefix: "_triggers_host_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on Host created, confirmed where ${1:name}; end triggers; $0 """ "_triggers hardware_detail": prefix: "_triggers_hardware_detail_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on detail := HardwareDetail created, confirmed where ${1:name}; end triggers; $0 """ "_triggers management_controller": prefix: "_triggers_management_controller_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on mc := ManagementController created, confirmed where ${1:name}; end triggers; $0 """ "_triggers network_device": prefix: "_triggers_network_device_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on device := NetworkDevice created, confirmed where ${1:vendor}; end triggers; $0 """ "_triggers software_instance": prefix: "_triggers_software_instance_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on SoftwareInstance created, confirmed where type = ${1:name}; end triggers; $0 """ "_triggers software_component": prefix: "_triggers_software_component_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on SoftwareComponent created, confirmed where instance = ${1:name}; end triggers; $0 """ # IDENTIFIERS: "_identify Simple Identifiers": prefix: "_identify_Simple_Identifiers_" description: 'Identify tables are active tables used to annotate matching nodes with particular values.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Identify' body: """ identify ${1:SOME} 1.0 tags simple_identity, ${2:tag1}; DiscoveredProcess cmd -> simple_identity; end identify; $0 """ # TABLES: "_table Two cols": prefix: "_table_Two_cols_" description: 'Tables provide simple look-up tables that can be used by functions in pattern bodies.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Static+Tables' body: """ table ${1:table_name} 1.0 \"one\" -> \"val_name1\", \"val_name2\"; \"two\" -> \"val_name3\", \"val_name4\"; default -> \"val_name5\", \"val_name6\"; end table; $0 """ "_table One col": prefix: "_table_One_col_" description: 'Tables provide simple look-up tables that can be used by functions in pattern bodies.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Static+Tables' body: """ table ${1:table_name} 1.0 \"one\" -> val_1; \"two\" -> val_2; default -> val_100; end table; $0 """ # DEFINITIONS: "_definitions Small": prefix: "_definitions_Small_" description: 'Additional functions to call in patterns are described in definitions blocks. In TPL 1.5, definitions blocks are used for User defined functions and for data integration with SQL databases.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Definitions' body: """ definitions ${1:def_name} 1.0 \'''${2:Describe definitions}\'''$0 end definitions; $0 """ "_definitions Big": prefix: "_definitions_Big_" description: 'Additional functions to call in patterns are described in definitions blocks. In TPL 1.5, definitions blocks are used for User defined functions and for data integration with SQL databases.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Definitions' body: """ definitions ${1:def_name} 1.0 \'''${2:Describe definitions} Change History: \''' $0 end definitions; $0 """ "_define Function": prefix: "_define_Function_" description: 'User defined functions are specified in definitions blocks. In order to specify a function the type parameter within the definitions block must be set to the value function or omitted.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ define ${1:function_name}(${2:argument}) -> ${3:return} \''' ${4:Describe function} \''' $0 return ${5:dummy}; end define; $0 """ # FULL VERSION: "_full_version (\\\\d*\\\\.\\\\d*)": prefix: "_full_version_(\\\\d*\\\\.\\\\d*)_" description: 'Template for product version extract when full version is obtained.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ // Assign product version if full_version then product_version := regex.extract(full_version, regex '(\\\\d*\\\\.\\\\d*)', raw '\\\\1'); if not product_version then product_version := full_version; end if; end if; $0 """ "_packages Find packages": prefix: "_packages_Find_packages_" description: 'Template for find packages and get full version.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.findPackages' body: """ packages := model.findPackages( host, [regex \"${1:PACKAGE_NAME}\"] ); for package in packages do if package.version then full_version := package.version; break; end if; end for;$0 """ # TPLPRE: # COMMON FUNCTIONS:: # // This is an old implementation, please use new (SearchFunctions.getNodeIp) "OLD functions.validate_host_address_format(rel_host_address)": prefix: "_functions.validate_host_address_format" description: 'OLD Common_functions module. If <rel_host_address> does not meet requirements(regex \'^[\da-z\:][\w\:\.\-]*$\') then functions returns empty string' body: """// WARNING: This is an old implementation, please use new (SearchFunctions.getNodeIp)\nfunctions.validate_host_address_format(${1:rel_host_address});$0""" "OLD functions.domain_lookup(host, rel_host_address_domain)": prefix: "_functions.domain_lookup" description: 'OLD Common_functions module. Function resolves domain to IP address using "nslookup" command' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.domain_lookup(${1:host}, ${2:rel_host_address_domain});$0""" "OLD functions.identify_host_perform_search(host, rel_host_address)": prefix: "_functions.identify_host_perform_search" description: 'OLD Common_functions module. Function searches for one "rel_host_address" Host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions.getHostingNodes)\nfunctions.identify_host_perform_search(${1:host}, ${2:rel_host_address});$0""" "OLD functions.identify_host_perform_search_in_scope(host, rel_host_address, hosts_scope)": prefix: "_functions.identify_host_perform_search_in_scope" description: """OLD Common_functions module. Function searches for one rel_host_address Host in some narrowed scope of hosts, but not on all available hosts like identify_host_perform_search()""" body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.identify_host_perform_search_in_scope(${1:host}, ${2:rel_host_address}, ${3:hosts_scope});$0""" "OLD functions.identify_host(host, rel_host_address, extended)": prefix: "_functions.identify_host" description: 'OLD Common_functions module. Function searches for one "rel_host_address" Host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.identify_host(${1:host}, ${2:rel_host_address}, ${3:extended});$0""" "OLD functions.identify_host_extended(host, rel_host_address, extended)": prefix: "_functions.identify_host_extended" description: 'OLD Common_functions module. Function searches for one "rel_host_address" Host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.identify_host_extended(${1:host}, ${2:rel_host_address}, ${3:extended});$0""" "OLD functions.related_sis_search(host, rel_host_address, rel_si_type)": prefix: "_functions.related_sis_search" description: 'OLD Common_functions module. Function searches for all SIs with "rel_si_type" TYPE on "rel_host_address" host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_sis_search(${1:host}, ${2:rel_host_address}, ${3:rel_si_type});$0""" "OLD functions.related_sis_search_on_multiple_hosts(host, rel_host_addresses, rel_si_type)": prefix: "_functions.related_sis_search_on_multiple_hosts" description: 'OLD Common_functions module. Function searches for all SIs with "rel_si_type" TYPE on multiple "rel_host_addresses" hosts.' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_sis_search_on_multiple_hosts(${1:host}, ${2:rel_host_addresses}, ${3:rel_si_type});$0""" "OLD functions.related_sis_search_on_multiple_hosts_extended(host, rel_host_addresses, rel_si_type)": prefix: "_functions.related_sis_search_on_multiple_hosts_extended" description: 'OLD Common_functions module. Function searches for all SIs with "rel_si_type" TYPE on multiple "rel_host_addresses" hosts.' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_sis_search_on_multiple_hosts_extended(${1:host}, ${2:rel_host_addresses}, ${3:rel_si_type});$0""" "OLD functions.related_sis_search_extended(host, rel_host_address, rel_si_type, extended)": prefix: "_functions.related_sis_search_extended" description: 'OLD Common_functions module. Function searches for all SIs with "rel_si_type" TYPE on "rel_host_address" host.' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_sis_search_extended(${1:host}, ${2:rel_host_address}, ${3:rel_si_type}, ${4:extended}),$0""" "OLD functions.related_si_types_search(host, rel_host_address, rel_si_types)": prefix: "_functions.related_si_types_search" description: 'OLD Common_functions module. Function searches for all SIs with different TYPEs in "rel_si_types" LIST on "rel_host_address" host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_si_types_search(${1:host}, ${2:rel_host_address}, ${3:rel_si_types});$0""" "OLD functions.path_normalization(host, install_root)": prefix: "_functions.path_normalization" description: 'OLD Common_functions module. Current function determines "~" in the path, normalizes it and returns back full path' body: """// WARNING: This is an old implementation, please use new (New.New)\nfunctions.path_normalization(${1:host}, ${2:install_root});$0""" "OLD functions.links_management(si_node, recently_found_sis, related_si_type)": prefix: "_functions.links_management" description: 'OLD Common_functions module. Function that manages Communication and Dependency links between the current SI and related SIs' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.links_management(${1:si_node}, ${2:recently_found_sis}, ${3:related_si_type});$0""" "OLD functions.get_cleanedup_path(path, os)": prefix: "_functions.get_cleanedup_path" description: 'OLD Common_functions module. Function which normalizes directory path by removing "\.\", "\..\", etc.' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.get_cleanedup_path(${1:path}, ${2:os});$0""" "OLD functions.get_max_version(ver1, ver2)": prefix: "_functions.get_max_version" description: 'OLD Common_functions module. Compares to version strings like "10.08.10" and "7.18" and returns the biggest one' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.get_max_version(${1:ver1}, ${2:ver2});$0""" "OLD functions.get_exe_cwd_path(process, expected_binary_name)": prefix: "_functions.get_exe_cwd_path" description: """OLD Common_functions module. Function tries to obtain: - full process command path (exe_path) and/or - current working directory (cwd_path) - directory the process was started from. """ body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.get_exe_cwd_path(${1:process}, ${2:expected_binary_name});$0""" "OLD functions.sort_list(list)": prefix: "_functions.sort_list" description: 'OLD Common_functions module. Function returns sorted list of strings ' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.sort_list(${1:list});$0""" "OLD functions.run_priv_cmd(host, command, priv_cmd := 'PRIV_RUNCMD')": prefix: "_functions.run_priv_cmd" description: """OLD Common_functions module. Run the given command, using privilege elevation on UNIX, if required. The command is first run as given. If this fails, produces no output and the platform is UNIX then the command is executed again using the given priv_cmd. """ body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.run_priv_cmd(${1:host}, ${2:command}, priv_cmd := 'PRIV_RUNCMD');$0""" "OLD functions.has_process(host, command)": prefix: "_functions.has_process" description: 'OLD Common_functions module. Returns true if the given process is running on the given host. ' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.has_process(${1:host}, ${2:command});$0""" "OLD functions.isValidSerialNumber(serial)": prefix: "_functions.isValidSerialNumber" description: 'OLD Common_functions module. Returns true if the given serial number is valid ' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.isValidSerialNumber(${1:serial});$0""" "OLD functions.convertToCharString(ascii_codes)": prefix: "_functions.convertToCharString" description: 'OLD Common_functions module. Converts list of ASCII code integers into a string of characters. ' body: """// WARNING: This is an old implementation, please use new (ConversionFunctions)\nfunctions.convertToCharString(${1:ascii_codes});$0""" "OLD functions.wmiFollowAssociations(host, namespace, initial_paths, associations)": prefix: "_functions.wmiFollowAssociations" description: """OLD Common_functions module. Starting from initial_paths, a list of WMI source instance paths, follows multiple WMI associations to reach a set of target instances. """ body: """// WARNING: This is an old implementation, please use new (ConversionFunctions)\nfunctions.wmiFollowAssociations(${1:host}, ${2:namespace}, ${3:initial_paths}, ${4:associations});$0""" "OLD functions.checkForDecimal(value, bValue)": prefix: "_functions.checkForDecimal" description: 'OLD Common_functions module. Check for decimal and convert the value into Bytes ' body: """// WARNING: This is an old implementation, please use new (ConversionFunctions)\nfunctions.checkForDecimal(${1:value}, ${2:bValue});$0""" "OLD functions.convertToBytes(value, gib)": prefix: "_functions.convertToBytes" description: 'OLD Common_functions module. Convert the value into Bytes ' body: """// WARNING: This is an old implementation, please use new (ConversionFunctions)\nfunctions.convertToBytes(${1:value}, ${2:gib});$0""" "OLD functions.identify_host_with_uuid(uuid)": prefix: "_functions.identify_host_with_uuid" description: 'OLD Common_functions module. Function returns host with searched UUID ' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.identify_host_with_uuid(${1:uuid});$0""" "OLD functions.locateCommands(host, command_list)": prefix: "_functions.locateCommands" description: """OLD Common_functions module. Attempts to locate the required commands. Returns a table of each command location. The location is none if the command could not be found. This call returns none if the location process fails.""" body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.locateCommands(${1:host}, ${2:command_list});$0""" "OLD functions.find_server(host, server_address, port, si_type, alt_types := none, all := false)": prefix: "_functions.find_server" description: 'OLD Common_functions module. Function that searches for the appropriate server node based on the provided server details. ' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)!\nfunctions.find_server(${1:host}, ${2:server_address}, ${3:port}, ${4:si_type}, alt_types := ${5:none}, all := ${6:false});$0""" "OLD functions.checkCommandList(host, command_list)": prefix: "_functions.checkCommandList" description: 'OLD Common_functions module. Checks whether the commands exist. Returns true if all the commands exist. Even one command we are looking for is not present we return false. ' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.checkCommandList(${1:host}, ${2:command_list});$0""" # CONVERSION FUNCTIONS:: "ConversionFunctions.isValidSerialNumber(serial) -> valid": prefix: "ConversionFunctions.isValidSerialNumber" description: 'SupportingFiles ConversionFunctions module -> isValidSerialNumber() - checks if the provided serial number is valid;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.isValidSerialNumber(${1:serial});$0" "isValidSerialNumber(serial) -> valid": prefix: "isValidSerialNumber" description: 'SupportingFiles ConversionFunctions module -> isValidSerialNumber() - checks if the provided serial number is valid;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.isValidSerialNumber(${1:serial});$0" "ConversionFunctions.convertToCharString(ascii_codes) -> ascii_string": prefix: "ConversionFunctions.convertToCharString" description: 'SupportingFiles ConversionFunctions module -> convertToCharString() - converts list of ASCII code integers into a string of characters;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertToCharString(${1:ascii_codes});$0" "convertToCharString(ascii_codes) -> ascii_string": prefix: "convertToCharString" description: 'SupportingFiles ConversionFunctions module -> convertToCharString() - converts list of ASCII code integers into a string of characters;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertToCharString(${1:ascii_codes});$0" "ConversionFunctions.convertToBytes(value, gib) -> result": prefix: "ConversionFunctions.convertToBytes" description: 'SupportingFiles ConversionFunctions module -> convertToBytes() - converts the value into Bytes;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertToBytes(${1:value}, gib);$0" "convertToBytes(value, gib) -> result": prefix: "convertToBytes" description: 'SupportingFiles ConversionFunctions module -> convertToBytes() - converts the value into Bytes;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertToBytes(${1:value}, gib);$0" "ConversionFunctions.convertStringToHex(string, sep := \"\") -> result": prefix: "ConversionFunctions.convertStringToHex" description: 'SupportingFiles ConversionFunctions module -> convertStringToHex() - converts String To HexaDecimal string;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertStringToHex(${1:string}, sep := \"\");$0" "convertStringToHex(string, sep := \"\") -> result": prefix: "convertStringToHex" description: 'SupportingFiles ConversionFunctions module -> convertStringToHex() - converts String To HexaDecimal string;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertStringToHex(${1:string}, sep := \"\");$0" # cluster_support_functions "cluster_support_functions.getHostingNode(host, fallback_kind := Host, instance := inst, clustered_data_path := path)": prefix: "cluster_support_functions.getHostingNode" description: """SI can be identified as clustered (running on cluster): - if SI has specific processes/commands that indicates clustered installation - if SI is managed/monitored by ClusterService. Usually SI\'s instance or paths can be found in ClusterService information. - if SI binary or data directory resides on file system managed by Cluster - if SI is listening on IP address which is managed by Cluster""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.getHostingNode(host, fallback_kind := \"${1:t_host}\", instance := \"${2:inst}\", clustered_data_path := \"${3:path}\");$0" "cluster_support_functions.add_resource_attrs(resource, resource_type, resource_properties, resource_mapping)": prefix: "cluster_support_functions.add_resource_attrs" description: 'Add resource attributes of interest to the cluster resource node along with a standardised resource type attribute.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.add_resource_attrs(${1:resource}, ${2:resource_type}, ${3:resource_properties}, ${4:resource_mapping});$0" "cluster_support_functions.get_cluster_dns_names(cluster, ipv4_addrs, ipv6_addrs, host:=none)": prefix: "cluster_support_functions.get_cluster_dns_names" description: 'Get DNS names associated with the hosts of a cluster.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.get_cluster_dns_names(${1:cluster}, ${2:ipv4_addrs}, ${3:ipv6_addrs}, host := \"${4:none}\");$0" "cluster_support_functions.get_cluster_service_vip(si)": prefix: "cluster_support_functions.get_cluster_service_vip" description: 'Obtain the virtual ip address of the provided SoftwareInstance node if it is related to a ClusterService node. Also return the port if reported.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.get_cluster_service_vip(${1:si});$0" "cluster_support_functions.get_si_host(si, ip_addr)": prefix: "cluster_support_functions.get_si_host" description: """Obtain the host related to the provided SoftwareInstance node. If the SoftwareInstance is related to multiple hosts due to the software running on a cluster, then it selects the host based on the host currently supporting the provided IP address or the host known to be actively running the clustered software.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.get_si_host(${1:si}, ${2:ip_addr});$0" # DISCOVERY BUILT IN FUNCTIONS:: "discovery.process(node)": prefix: "discovery.process" description: 'Returns the process node corresponding to the source node, which must be a ListeningPort or NetworkConnection node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.process' body: "discovery.process(${1:process});$0" "discovery.children(node)": prefix: "discovery.children" description: 'Returns a list of the child processes for the given DiscoveredProcess node. Returns an empty list if there no children or the parameter is not a DiscoveredProcess node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.children' body: "discovery.children(${1:process});$0" "discovery.descendents(node)": prefix: "discovery.descendents" description: "Returns a list consisting of the children of the given DiscoveredProcess node, and recursively all of the children's children." descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.descendents' body: "discovery.descendents(${1:process});$0" "discovery.parent(node)": prefix: "discovery.parent" description: 'Returns the parent process for the given DiscoveredProcess node. Returns none if the process has no parent.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.parent' body: "discovery.parent(${1:process});$0" "discovery.allProcesses(node)": prefix: "discovery.allProcesses" description: 'Returns a list of all processes corresponding to the directly discovered data source node. Returns an empty list if the source node is not a valid directly discovered data node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.allProcesses' body: "discovery.allProcesses(${1:process});$0" "discovery.access(node)": prefix: "discovery.access" description: 'Returns the Discovery Access node for the source DDD node, if given. If no node is given, it returns the DiscoveryAccess currently in use.Returns none if the source is not valid.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.access' body: "discovery.access(${1:process});$0" # GET AND QUERY: "discovery.fileGet(host, config_filepath)": prefix: "discovery.fileGet" description: 'Retrieves the specified file. target is a node used to identify the discovery target, either a directly discovered data node, or a Host node. Requires PRIV_CAT to be defined to retrieve files not readable by the current user.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.fileGet' body: "discovery.fileGet(host, ${1:config_filepath});$0" "discovery.fileInfo(host, \"file_path\")": prefix: "discovery.fileInfo" description: "Retrieves information about the specified file, but not the file content. This is useful if the file is a binary file or particularly large." descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.fileInfo' body: "discovery.fileInfo(host, \"${1:file_path}\");$0" "discovery.getNames(target, ip_address)": prefix: "discovery.getNames" description: 'Performs a DNS lookup on the IP address and returns a list of FQDN strings.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.getNames' body: "discovery.getNames(${1:target}, ${2:ip_address});$0" "discovery.listDirectory(host, directory)": prefix: "discovery.listDirectory" description: 'Retrieves the directory listing of the directory specified by the path on the specified target. You cannot use wildcards in the path.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.listDirectory' body: "discovery.listDirectory(host, ${1:directory});$0" "discovery.listRegistry(host, registry_root)": prefix: "discovery.listRegistry" description: 'Returns a list of the registry entries of the registry key specified by the key_path.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.listRegistry' body: "discovery.listRegistry(host, ${1:registry_root});$0" "discovery.registryKey(host, reg_key_inst_dir)": prefix: "discovery.registryKey" description: 'Retrieves a registry key from a Windows computer.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.registryKey' body: "discovery.registryKey(host, ${1:reg_key_inst_dir});$0" "discovery.wmiQuery(host, wmiQuery, wmiNS)": prefix: "discovery.wmiQuery_wmiNS" description: 'Performs a WMI query on a Windows computer. Returns a list of DiscoveredWMI nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.wmiQuery' body: "discovery.wmiQuery(host, ${1:wmiQuery}, ${2:wmiNS});$0" "discovery.wmiQuery(host, wmiQuery, raw \"path_to\")": prefix: "discovery.wmiQuery_path_to" description: 'Performs a WMI query on a Windows computer. Returns a list of DiscoveredWMI nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.wmiQuery' body: "discovery.wmiQuery(host, ${1:wmiQuery}, raw \"${2:path_to}\");$0" "discovery.wbemQuery(target, class_name, [properties], namespace)": prefix: "discovery.wbemQuery" description: 'Performs a WBEM query on the target and returns a list of DiscoveredWBEM DDD nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.wbemQuery' body: "discovery.wbemQuery(${1:target}, ${2:class_name}, [${3:properties}], ${4:namespace});$0" "discovery.wbemEnumInstances(target, class_name, properties, namespace, filter_locally)": prefix: "discovery.wbemEnumInstances" description: 'Performs a WBEM query on the target and returns a list of DiscoveredWBEMInstance DDD nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.wbemEnumInstances' body: "discovery.wbemEnumInstances(${1:target}, ${2:class_name}, ${3:properties}, ${4:namespace}, ${5:filter_locally});$0" # New implementation of runCommand: "Future.runCommand(host, \"command_to_run\", \"path_to_command\")": prefix: "Future.runCommand" description: 'FUTURE Returns a DiscoveredCommandResult node containing the result of running the specified command.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Future.runCommand' body: "Future.runCommand(host, \"${1:command}\", \"${2:path_to_command}\");$0" # Classical implementation of runCommand: "discovery.runCommand(host, \"command_to_run\")": prefix: "discovery.runCommand" description: 'Returns a DiscoveredCommandResult node containing the result of running the specified command.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.runCommand' body: "discovery.runCommand(host, \"${1:command_to_run}\");$0" "discovery.snmpGet(target, oid_table, [binary_oid_list])": prefix: "discovery.snmpGet" description: 'Performs an SNMP query on the target and returns a DiscoveredSNMP node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.snmpGet' body: "discovery.snmpGet(${1:target}, ${2:oid_table}, [${3:binary_oid_list}]);$0" "discovery.snmpGetTable(target, table_oid, column_table, [binary_oid_list])": prefix: "discovery.snmpGetTable" description: 'Performs an SNMP query that returns a table on the target.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.snmpGetTable' body: "discovery.snmpGetTable(${1:target}, ${2:table_oid}, ${3:column_table}, [${4:binary_oid_list}]);$0" # New functions for REST API: "discovery.restfulGet(target, protocol, path[, header])": prefix: "discovery.restfulGet" description: 'Performs a GET request on the target using the RESTful protocol specified and returns a node containing information on the discovered system.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.restfulGet' body: "discovery.restfulGet(${1:target}, ${2:protocol}, ${3:path}[, ${4:header}]);$0" "discovery.restfulPost(target, protocol, path, body[, header])": prefix: "discovery.restfulPost" description: 'Performs a POST request on the target using the RESTful system and returns a node containing information on the discovered system.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.restfulPost' body: "discovery.restfulPost(${1:target}, ${2:protocol}, ${3:path}, ${4:body}[, ${5:header}]);$0" # New functions for vSphere: "discovery.vSphereFindObjects": prefix: "discovery.vSphereFindObjects" description: 'Queries to search from the root folder the instances of an object type and returns the requested properties for each object found.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.vSphereFindObjects' body: "discovery.vSphereFindObjects(${1:vc_host}, \"${2:HostSystem}\", [\"name\", \"hardware.systemInfo.uuid\"]);$0" "discovery.vSphereTraverseToObjects": prefix: "discovery.vSphereTraverseToObjects" description: 'Queries to traverse from the initial object to instances of an object type and get properties on those objects.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.vSphereTraverseToObjects' body: "discovery.vSphereTraverseToObjects(${1:host}, \"${2:HostSystem}\", storage_info.storage_id, \"datastore\", \"Datastore\", [\"name\"]);$0" "discovery.vSphereGetProperties": prefix: "discovery.vSphereGetProperties" description: 'Queries to retrieve properties from a given MOR and returns the requested properties for each object found.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.vSphereGetProperties' body: "discovery.vSphereGetProperties(${1:host}, \"${2:HostSystem}\", host_id, [\"config.storageDevice.scsiLun[\"%disk_info.key%\"].deviceName\", \"config.storageDevice.scsiLun[\"%disk_info.key%\"].capabilities.updateDisplayNameSupported\"]);$0" "discovery.vSphereGetPropertyTable": prefix: "discovery.vSphereGetPropertyTable" description: 'Queries to retrieve a table of values from a given MOR and is intended to be used to retrieve nested properties from lists and arrays.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.vSphereGetPropertyTable' body: "discovery.vSphereGetPropertyTable(${1:host}, \"${2:HostSystem}\", host_id, \"config.storageDevice.scsiLun\", [\"serialNumber\", \"deviceName\"]);$0" # https://docs.bmc.com/docs/display/DISCO111/Binary+functions "binary.toHexString(value)": prefix: "binary.toHexString" description: 'Returns the given binary value as a hex string, that is, two hex digits per byte.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toHexString' body: "binary.toHexString(${1:value});$0" "binary.toIPv4(value)": prefix: "binary.toIPv4" description: 'Returns the given binary value as the text representation of an IPv4 address.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toIPv4' body: "binary.toIPv4(${1:value});$0" "binary.toIPv4z(value)": prefix: "binary.toIPv4z" description: 'Returns the given binary value as the text representation of an IPv4 address with a zone index.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toIPv4z' body: "binary.toIPv4z(${1:value});$0" "binary.toIPv6(value)": prefix: "binary.toIPv6" description: 'Returns the given binary value as the text representation of a canonical IPv6 address.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toIPv6' body: "binary.toIPv6(${1:value});$0" "binary.toIPv6z(value)": prefix: "binary.toIPv6z" description: 'Returns the given binary value as the text representation of a canonical IPv6 address with zone index.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toIPv6z' body: "binary.toIPv6z(${1:value});$0" "binary.toMACAddress(value)": prefix: "binary.toMACAddress" description: 'Returns the given binary value as the text representation of a MAC address.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toMACAddress' body: "binary.toMACAddress(${1:value});$0" "binary.toValue(data, format)": prefix: "binary.toValue" description: 'Converts the given binary value into the specified format.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toValue' body: "binary.toValue(${1:data}, ${2:format});$0" "binary.toWWN(value)": prefix: "binary.toWWN" description: 'Returns the given binary value as the text representation of a WWN value.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toWWN' body: "binary.toWWN(${1:value});$0" # MATRIX: "filepath_info Matrix": prefix: "filepath_info_Matrix" description: 'Development function. Allows us to gather all file get and command run from patterns to show it in docs.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: """ $0// *filepath_info_start $0// filepath_windows := \"${1:filepath_windows}\" $0// filepath_unix := \"${2:filepath_unix}\" $0// reason := \"${3:Obtain something}\" $0// when := \"${4:Only if installation is path obtained}\" $0// *filepath_info_end$0 """ "command_info Matrix": prefix: "command_info_Matrix" description: 'Development function. Allows us to gather all file get and command run from patterns to show it in docs.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: """ $0// *command_info_start $0// command_windows := \"${1:command_windows}\" $0// command_unix := \"${2:command_unix}\" $0// reason := \"${3:Obtain something}\" $0// when := \"${4:Only if installation path is obtained}\" $0// *command_info_end$0 """ "filepath_info Unix Matrix": prefix: "filepath_info_Unix_Matrix" description: 'Development function. Allows us to gather all file get and command run from patterns to show it in docs.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: """ $0// *filepath_info_start $0// filepath_unix := \"${2:filepath_unix}\" $0// reason := \"${3:Obtain something}\" $0// when := \"${4:Only if installation is path obtained}\" $0// *filepath_info_end$0 """ "command_info Windows Matrix": prefix: "command_info_Windows_Matrix" description: 'Development function. Allows us to gather all file get and command run from patterns to show it in docs.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: """ $0// *command_info_start $0// command_windows := \"${1:command_windows}\" $0// reason := \"${3:Obtain something}\" $0// when := \"${4:Only if installation path is obtained}\" $0// *command_info_end$0 """ # JSON: "json.encode(\"value\")": prefix: "json.encode" description: 'Converts value to a JSON encoded string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/json.encode' body: "json.encode(${1:value});$0" "json.decode(\"value\")": prefix: "json.decode" description: 'Decodes a JSON encoded string and returns a structure containing a string, table or list including nested structures.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/json.decode' body: "json.decode(${1:value});$0" # DISCOVERY FUNCTIONS: "DiscoveryFunctions.escapePath(host, install_root) -> install_root": prefix: "DiscoveryFunctions.escapePath" description: 'DiscoveryFunctions.escapePath() -> escape extra characters and resolve /../ in path.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.escapePath(${1:host}, ${2:install_root});$0" "escapePath(host, install_root) -> install_root": prefix: "escapePath" description: 'DiscoveryFunctions.escapePath() -> escape extra characters and resolve /../ in path.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.escapePath(${1:host}, ${2:install_root});$0" "DiscoveryFunctions.escapeArg(host, value, permit_env_vars := false) -> escaped": prefix: "DiscoveryFunctions.escapeArg" description: 'DiscoveryFunctions.escapeArg(host, value, permit_env_vars := false) -> escapes an argument for use in a command' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.escapeArg(${1:host}, ${2:value}, ${2:permit_env_vars} := false);$0" "escapeArg(host, value, permit_env_vars := false) -> escaped": prefix: "escapeArg" description: 'DiscoveryFunctions.escapeArg(host, value, permit_env_vars := false) -> escapes an argument for use in a command' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.escapeArg(${1:host}, ${2:value}, ${2:permit_env_vars} := false);$0" "DiscoveryFunctions.pathNormalization(host, install_root) -> install_root // deprecated": prefix: "DiscoveryFunctions.pathNormalization" description: 'deprecated synonym for expandWindowsPath' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "// deprecated synonym for expandWindowsPath\nDiscoveryFunctions.pathNormalization(${1:host}, ${2:install_root});$0 // deprecated" "pathNormalization(host, install_root) -> install_root // deprecated": prefix: "pathNormalization" description: 'deprecated synonym for expandWindowsPath' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "// deprecated synonym for expandWindowsPath\nDiscoveryFunctions.pathNormalization(${1:host}, ${2:install_root});$0 // deprecated" "DiscoveryFunctions.getCleanedupPath(path, os) -> path_normalized // deprecated": prefix: "DiscoveryFunctions.getCleanedupPath" description: 'deprecated function to normalize a path, like normalizePath, but without expanding Windows short names;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "// deprecated synonym for expandWindowsPath\nDiscoveryFunctions.getCleanedupPath(${1:path}, ${2:os});$0 // deprecated" "getCleanedupPath(path, os) -> path_normalized // deprecated": prefix: "getCleanedupPath" description: 'deprecated function to normalize a path, like normalizePath, but without expanding Windows short names;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "// deprecated synonym for expandWindowsPath\nDiscoveryFunctions.getCleanedupPath(${1:path}, ${2:os});$0 // deprecated" "DiscoveryFunctions.expandWindowsPath(host, path) -> expanded": prefix: "DiscoveryFunctions.expandWindowsPath" description: 'Convert short-form DOS 8.3 names in path into the long form.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.expandWindowsPath(${1:host}, ${2:path});$0" "expandWindowsPath(host, path) -> expanded": prefix: "expandWindowsPath" description: 'Convert short-form DOS 8.3 names in path into the long form.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.expandWindowsPath(${1:host}, ${2:path});$0" "DiscoveryFunctions.getMaxVersion(ver1, ver2) -> maxversion": prefix: "DiscoveryFunctions.getMaxVersion" description: 'DiscoveryFunctions.getMaxVersion() -> compares two versions and returns the highest one.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.getMaxVersion(${1:ver1}, ${2:ver2});$0" "getMaxVersion(ver1, ver2) -> maxversion": prefix: "getMaxVersion" description: 'DiscoveryFunctions.getMaxVersion() -> compares two versions and returns the highest one.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.getMaxVersion(${1:ver1}, ${2:ver2});$0" "DiscoveryFunctions.getExeCwdPath(process, expected_binary_name) -> exe_path, cwd_path": prefix: "DiscoveryFunctions.getExeCwdPath" description: 'DiscoveryFunctions.getExeCwdPath() -> returns full path of the binary file location and the full path from where it\'s been execute.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.getExeCwdPath(${1:process}, ${2:expected_binary_name});$0" "getExeCwdPath(process, expected_binary_name) -> exe_path, cwd_path": prefix: "getExeCwdPath" description: 'DiscoveryFunctions.getExeCwdPath() -> returns full path of the binary file location and the full path from where it\'s been execute.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.getExeCwdPath(${1:process}, ${2:expected_binary_name});$0" "DiscoveryFunctions.sortList(list) -> sorted_list": prefix: "DiscoveryFunctions.sortList" description: 'DiscoveryFunctions.sortList() -> sorts the list and returns its sorted copy.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.sortList(${1:list});$0" "sortList(list) -> sorted_list": prefix: "sortList" description: 'DiscoveryFunctions.sortList() -> sorts the list and returns its sorted copy.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.sortList(${1:list});$0" "DiscoveryFunctions.runActiveCommand(host, command_line, expected_content_regex := none, priv_cmd := none) -> result": prefix: "DiscoveryFunctions.runActiveCommand" description: 'DiscoveryFunctions.runActiveCommand() -> runs the command and then re-runs it with privileged permissions if needed.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.runActiveCommand(${1:host}, ${2:command_line}, expected_content_regex := ${3:none}, priv_cmd := ${4:none});$0" "runActiveCommand(host, command_line, expected_content_regex := none, priv_cmd := none) -> result": prefix: "runActiveCommand" description: 'DiscoveryFunctions.runActiveCommand() -> runs the command and then re-runs it with privileged permissions if needed.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.runActiveCommand(${1:host}, ${2:command_line}, expected_content_regex := ${3:none}, priv_cmd := ${4:none});$0" "DiscoveryFunctions.runFutureActiveCommand(host, command_line, expected_content_regex := none, priv_cmd := none, full_process := full_process) -> result": prefix: "DiscoveryFunctions.runFutureActiveCommand" description: 'DiscoveryFunctions.runFutureActiveCommand() -> runs the command and then re-runs it with privileged permissions if needed.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.runFutureActiveCommand(${1:host}, ${2:command_line}, expected_content_regex := ${3:none}, priv_cmd := ${4:none}, full_process := ${5:full_process});$0" "runFutureActiveCommand(host, command_line, expected_content_regex := none, priv_cmd := none, full_process := full_process) -> result": prefix: "runFutureActiveCommand" description: 'DiscoveryFunctions.runFutureActiveCommand() -> runs the command and then re-runs it with privileged permissions if needed.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.runFutureActiveCommand(${1:host}, ${2:command_line}, expected_content_regex := ${3:none}, priv_cmd := ${4:none}, full_process := ${5:full_process});$0" "DiscoveryFunctions.locateCommands(host, command_list) -> result": prefix: "DiscoveryFunctions.locateCommands" description: 'DiscoveryFunctions.locateCommands() -> searches for the location of the provided command list.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.locateCommands(${1:host}, ${2:command_list});$0" "locateCommands(host, command_list) -> result": prefix: "locateCommands" description: 'DiscoveryFunctions.locateCommands() -> searches for the location of the provided command list.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.locateCommands(${1:host}, ${2:command_list});$0" "DiscoveryFunctions.checkCommandList(host, command_list) -> result": prefix: "DiscoveryFunctions.checkCommandList" description: 'DiscoveryFunctions.checkCommandList() -> checks that the list of commands exist on the given Host.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.checkCommandList(${1:host}, ${2:command_list});$0" "checkCommandList(host, command_list) -> result": prefix: "checkCommandList" description: 'DiscoveryFunctions.checkCommandList() -> checks that the list of commands exist on the given Host.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.checkCommandList(${1:host}, ${2:command_list});$0" "DiscoveryFunctions.getErrorRegexes(arg1, arg2) -> result": prefix: "DiscoveryFunctions.getErrorRegexes" description: 'returns a list of known regexes to parse errored command outputs' body: "// This is not implemented yet. Reffer to DiscoveryFunctions 1.7 docstrings" "getErrorRegexes(arg1, arg2) -> result": prefix: "getErrorRegexes" description: 'returns a list of known regexes to parse errored command outputs' body: "// This is not implemented yet. Reffer to DiscoveryFunctions 1.7 docstrings" # RDBMS OLD:: # // This is an old implementation, please use new (RDBMSFunctions) "OLD rdbms_functions.oracle_ora_file_parser(section_name, oracle_ora_file_content) -> section": prefix: "_rdbms_functions.oracle_ora_file_parser" description: 'OLD rdbms_functions.oracle_ora_file_parser -> function tries to obtain full section from Oracle listener.ora or tnsnames.ora file. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.oracleOraFileParser)\nrdbms_functions.oracle_ora_file_parser(${1:section_name}, ${2:oracle_ora_file_content});$0""" "OLD rdbms_functions.perform_rdbms_sis_search(related_sis_raw, rel_si_type, instance, port, db_name, extended) -> related_rdbms_sis": prefix: "_rdbms_functions.perform_rdbms_sis_search" description: 'OLD rdbms_functions.perform_rdbms_sis_search -> This internal function is used by related_rdbms_sis_search() and related_rdbms_sis_search_extended() and searches for specific RDBMS SI \"rel_si_type\" TYPE on \"rel_host_address\" host, which can be uniquely identified by attribute (depends on RDBMS Type) ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.perform_rdbms_sis_search(${1:related_sis_raw}, ${2:rel_si_type}, ${3:instance}, ${4:port}, ${5:db_name}, ${6:extended});$0""" "OLD rdbms_functions.related_rdbms_sis_search(host, rel_host_address, rel_si_type, instance, port, db_name, extended) -> related_rdbms_sis": prefix: "_rdbms_functions.related_rdbms_sis_search" description: 'OLD rdbms_functions.related_rdbms_sis_search -> Function searches for specific RDBMS SI \"rel_si_type\" TYPE on \"rel_host_address\" host. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.related_rdbms_sis_search(${1:host}, ${2:rel_host_address}, ${3:rel_si_type}, ${4:instance}, ${5:port}, ${6:db_name}, ${7:extended});$0""" "OLD rdbms_functions.related_rdbms_sis_search_extended(host, rel_host_address, rel_si_type, instance, port, db_name, extended) -> related_rdbms_sis": prefix: "_rdbms_functions.related_rdbms_sis_search_extended" description: 'OLD rdbms_functions.related_rdbms_sis_search_extended -> Function searches for specific RDBMS SI \"rel_si_type\" TYPE on \"rel_host_address\" host. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.related_rdbms_sis_search_extended(${1:host}, ${2:rel_host_address}, ${3:rel_si_type}, ${4:instance}, ${5:port}, ${6:db_name}, ${7:extended});$0""" "OLD rdbms_functions.oracle_net_service_name_search(host, net_service_name, tnsnames_file_full_location) -> related_oracle_si": prefix: "_rdbms_functions.oracle_net_service_name_search" description: 'OLD rdbms_functions.oracle_net_service_name_search -> Function returns Oracle Database SI which is end point for local \<net_service_name\>. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.oracleNetServiceNameSearch)\nrdbms_functions.oracle_net_service_name_search(${1:host}, ${2:net_service_name}, ${3:tnsnames_file_full_location});$0""" "OLD rdbms_functions.dsn_rdbms_servers(host,dsn_name) -> db_srvs": prefix: "_rdbms_functions.dsn_rdbms_servers" description: 'OLD rdbms_functions.dsn_rdbms_servers -> Function returns related RDBMS SI by its DSN (Data Source Name) value. For WINDOWS ONLY! ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.dsnRdbmsServers)\nrdbms_functions.dsn_rdbms_servers(${1:host}, ${2:dsn_name});$0""" "OLD rdbms_functions.parseJDBC(url) -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name": prefix: "_rdbms_functions.parseJDBC" description: 'OLD rdbms_functions.parseJDBC -> Parse a JDBC URL and extract the details ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.parseJDBC)\nrdbms_functions.parseJDBC(${1:url});$0""" "OLD rdbms_functions.jdbc_search(host,jdbc_url) -> db_srvs": prefix: "_rdbms_functions.jdbc_search" description: 'OLD rdbms_functions.jdbc_search -> Function returns related RDBMS SI by JDBC URL value. First it parses the JDBC URL(the function from j2eeinferredmodel module was taken as a basis), then it uses related_rdbms_sis_search or oracle_net_service_name_search function to find the related RDBMS SIs. Supported RDBMS: MSSQL, Oracle, DB2, MySQL, PostgreSQL, Ingres DB, Sybase ASE, Informix. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.jdbc_search(${1:host}, ${2:jdbc_url});$0""" "OLD rdbms_functions.find_db_server(host, server_address, port, si_type, db_details) -> server_nodes": prefix: "_rdbms_functions.find_db_server" description: 'OLD rdbms_functions.find_db_server -> Function that searches for the appropriate database server node based on the provided server details. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.find_db_server(${1:host}, ${2:server_address}, ${3:port}, ${4:si_type}, ${5:db_details});$0""" # RDBMS NEW:: "RDBMSFunctions.oracleOraFileParser(section_name, oracle_ora_file_content) -> section": prefix: "RDBMSFunctions.oracleOraFileParser" description: 'obtains full section from Oracle listener.ora or tnsnames.ora files' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.oracleOraFileParser(${1:section_name}, ${2:oracle_ora_file_content}); // -> section$0" "oracleOraFileParser(section_name, oracle_ora_file_content) -> section": prefix: "oracleOraFileParser" description: 'obtains full section from Oracle listener.ora or tnsnames.ora files' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.oracleOraFileParser(${1:section_name}, ${2:oracle_ora_file_content}); // -> section$0" "RDBMSFunctions.performRdbmsSisSearch(related_sis_raw, rel_si_type, port, instance, db_name, ora_service_name, db2_copy_name) -> related_rdbms_nodes": prefix: "RDBMSFunctions.performRdbmsSisSearch" description: 'searches for the RDBMS Software by provided parameters' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ RDBMSFunctions.performRdbmsSisSearch(related_sis_raw = ${1:related_sis_raw}, rel_si_type = ${2:rel_si_type}, port = ${3:port}, instance = ${4:instance}, db_name = ${5:db_name}, ora_service_name = ${6:ora_service_name}, db2_copy_name = ${7:db2_copy_name}); // -> -> related_rdbms_nodes$0 """ "performRdbmsSisSearch(related_sis_raw, rel_si_type, port, instance, db_name, ora_service_name, db2_copy_name) -> related_rdbms_nodes": prefix: "performRdbmsSisSearch" description: 'searches for the RDBMS Software by provided parameters' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ RDBMSFunctions.performRdbmsSisSearch(related_sis_raw = ${1:related_sis_raw}, rel_si_type = ${2:rel_si_type}, port = ${3:port}, instance = ${4:instance}, db_name = ${5:db_name}, ora_service_name = ${6:ora_service_name}, db2_copy_name = ${7:db2_copy_name}); // -> -> related_rdbms_nodes$0 """ "RDBMSFunctions.oracleNetServiceNameSearch(host, net_service_name, tnsnames_file_full_location) -> ora_host, ora_sid, ora_service_name": prefix: "RDBMSFunctions.oracleNetServiceNameSearch" description: 'returns Oracle Database SI parameters by the provided Net Service Name' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ RDBMSFunctions.oracleNetServiceNameSearch(host = ${1:host}, net_service_name = ${2:net_service_name}, tnsnames_file_full_location = ${3:tnsnames_file_full_location}); // -> ora_host, ora_sid, ora_service_name$0 """ "oracleNetServiceNameSearch(host, net_service_name, tnsnames_file_full_location) -> ora_host, ora_sid, ora_service_name": prefix: "oracleNetServiceNameSearch" description: 'returns Oracle Database SI parameters by the provided Net Service Name' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ RDBMSFunctions.oracleNetServiceNameSearch(host = ${1:host}, net_service_name = ${2:net_service_name}, tnsnames_file_full_location = ${3:tnsnames_file_full_location}); // -> ora_host, ora_sid, ora_service_name$0 """ "RDBMSFunctions.dsnRdbmsServers(host,dsn_name) -> db_host, db_type, db_instance, ora_service_name, db_port, db_name": prefix: "RDBMSFunctions.dsnRdbmsServers" description: 'determines RDBMS Server details by the provided DSN' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.dsnRdbmsServers(host, ${1:dsn_name}); // -> db_host, db_type, db_instance, ora_service_name, db_port, db_name$0" "dsnRdbmsServers(host,dsn_name) -> db_host, db_type, db_instance, ora_service_name, db_port, db_name": prefix: "dsnRdbmsServers" description: 'determines RDBMS Server details by the provided DSN' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.dsnRdbmsServers(host, ${1:dsn_name}); // -> db_host, db_type, db_instance, ora_service_name, db_port, db_name$0" "RDBMSFunctions.parseJDBC(url) -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name": prefix: "RDBMSFunctions.parseJDBC" description: 'extracts RDBMS details by the provided JDBC URL' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.parseJDBC(${1:url}); // -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name$0" "parseJDBC(url) -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name": prefix: "parseJDBC" description: 'extracts RDBMS details by the provided JDBC URL' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.parseJDBC(${1:url}); // -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name$0" # SEARCH FUNCTIONS:: "SearchFunctions.getNodeIp(host, rel_host_address_domain) -> node_ip": prefix: "SearchFunctions.getNodeIp" description: 'converts alphanumeric Host address into IP address' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getNodeIp(host, ${1:rel_host_address_domain}); // -> node_ip$0" "getNodeIp(host, rel_host_address_domain) -> node_ip": prefix: "getNodeIp" description: 'converts alphanumeric Host address into IP address' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getNodeIp(host, ${1:rel_host_address_domain}); // -> node_ip$0" "SearchFunctions.getHostingNodes(host, node_address, balancer_port := none) -> hosting_nodes, nodes_type": prefix: "SearchFunctions.getHostingNodes" description: 'searches for Hosting Nodes' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getHostingNodes(host, ${1:node_address}, balancer_port := ${2:none}); // -> hosting_nodes, nodes_type$0" "getHostingNodes(host, node_address, balancer_port := none) -> hosting_nodes, nodes_type": prefix: "getHostingNodes" description: 'searches for Hosting Nodes' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getHostingNodes(host, ${1:node_address}, balancer_port := ${2:none}); // -> hosting_nodes, nodes_type$0" # GET SOFTWARE NODES: "SearchFunctions.getSoftwareNodes(evrything) -> software_nodes": prefix: "SearchFunctions.getSoftwareNodes" description: 'searches for software(SoftwareInstance, DatabaseDetail, SoftwareComponent or LoadBalancerService)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, node_address := ${1:none}, software_type := ${2:none}, balancer_port := ${3:none}, port := ${4:none}, instance := ${5:none}, listen_tcp_socket := ${6:none}, server_name := ${7:none}, installed_product := ${8:none}, db_name := ${9:none}, net_service_name := ${10:none}, ora_service_name := ${11:none}, db2_copy_name := ${12:none}, dsn_name := ${13:none}, jdbc_url := ${14:none}, tnsnames_file_location := ${15:none}, get_remote_nodes_only := ${16:none} ); // -> software_nodes $0 """ "getSoftwareNodes(evrything) -> software_nodes": prefix: "getSoftwareNodes" description: 'searches for software(SoftwareInstance, DatabaseDetail, SoftwareComponent or LoadBalancerService)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, node_address := ${1:none}, software_type := ${2:none}, balancer_port := ${3:none}, port := ${4:none}, instance := ${5:none}, listen_tcp_socket := ${6:none}, server_name := ${7:none}, installed_product := ${8:none}, db_name := ${9:none}, net_service_name := ${10:none}, ora_service_name := ${11:none}, db2_copy_name := ${12:none}, dsn_name := ${13:none}, jdbc_url := ${14:none}, tnsnames_file_location := ${15:none}, get_remote_nodes_only := ${16:none} ); // -> software_nodes $0 """ "SearchFunctions.getSI(related_node, si_types_raw) -> related_si": prefix: "SearchFunctions.getSI" description: 'returns the SI Node which is running behind LoadBalancer or hosts DatabaseDetail Node' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getSI(${1:related_node}, ${2:si_types_raw}); // -> related_si$0" "getSI(related_node, si_types_raw) -> related_si": prefix: "getSI" description: 'returns the SI Node which is running behind LoadBalancer or hosts DatabaseDetail Node' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getSI(${1:related_node}, ${2:si_types_raw}); // -> related_si$0" "SearchFunctions.relatedSisSearchOnMultipleHosts(host, rel_host_addresses, rel_si_type) -> related_sis": prefix: "SearchFunctions.relatedSisSearchOnMultipleHosts" description: 'searches for software on multiple Hosts' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.relatedSisSearchOnMultipleHosts(host, rel_host_addresses = ${1:rel_host_addresses}, rel_si_type = ${2:rel_si_type}); // -> related_sis$0" "relatedSisSearchOnMultipleHosts(host, rel_host_addresses, rel_si_type) -> related_sis": prefix: "relatedSisSearchOnMultipleHosts" description: 'searches for software on multiple Hosts' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.relatedSisSearchOnMultipleHosts(host, rel_host_addresses = ${1:rel_host_addresses}, rel_si_type = ${2:rel_si_type}); // -> related_sis$0" "SearchFunctions.identifyHostWithUuid(uuid) -> searched_host": prefix: "SearchFunctions.identifyHostWithUuid" description: 'searches for the Host with the specific UUID' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.identifyHostWithUuid(${1:uuid}); // -> searched_host$0" "identifyHostWithUuid(uuid) -> searched_host": prefix: "identifyHostWithUuid" description: 'searches for the Host with the specific UUID' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.identifyHostWithUuid(${1:uuid}); // -> searched_host$0" # Templates: # GET SOFTWARE NODES JDBC: "SearchFunctions.getSoftwareNodes(host, jdbc_url)": prefix: "_jdbc_url_SearchFunctions.getSoftwareNodes" description: 'Template of common SearchFunctions.getSoftwareNodes to find database via jdbc url.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, jdbc_url := ${2:jdbc_url}); $0 """ # GET SOFTWARE NODES CUSTOM: "SearchFunctions.getSoftwareNodes(host, node_address, software_type, db_name)": prefix: "_db_host_type_SearchFunctions.getSoftwareNodes" description: 'Template of common SearchFunctions.getSoftwareNodes to find related database.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, node_address := ${1:db_host}, software_type := ${2:db_type}, db_name := ${3:db_name} ); $0 """ "SearchFunctions.getSoftwareNodes(host, node_address, software_type, port, instance, db_name)": prefix: "_db_host_port_SearchFunctions.getSoftwareNodes" description: 'Template of common SearchFunctions.getSoftwareNodes to find related database by node_address, software_type, port, instance, db_name.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, node_address := ${1:db_host}, software_type := ${2:db_type}, port := ${3:port}, instance := ${4:instance}, db_name := ${5:db_name} ); $0 """ # REGEX USUAL USAGE:: "full ver (\\\\d+(?:\\\\.\\\\d+)*) greedy": prefix: "_regex_full_ver" description: 'Template regex expression to catch full version.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(\\\\d+(?:\\\\.\\\\d+)*)$0" "full ver ^(\\\\d+(?:\\\\.\\\\d+)?) zero or one": prefix: "_regex_full_ver_" description: 'Template regex expression to catch full version from start if string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "^(\\\\d+(?:\\\\.\\\\d+)?)$0" "product ver (\\\\d+(?:\\\\.\\\\d+)?) zero or one": prefix: "_regex_product_ver" description: 'Template regex expression to catch product version.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(\\\\d+(?:\\\\.\\\\d+)?)$0" "bjavaw (?i)\\bjavaw?(?:\\\\.exe)\\$": prefix: "_regex_bjavaw" description: 'Template regex expression to catch bjavaw cmd.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(?i)\\bjavaw?(?:\\\\.exe)\\$$0" "bjava (?i)\\bjava(?:\\\\.exe)?\\$": prefix: "_regex_bjava" description: 'Template regex expression to catch bjava cmd.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(?i)\\bjava(?:\\\\.exe)?\\$$0" "java (?i)^(\\w:.*\\)Java\\": prefix: "_regex_java" description: 'Template regex expression to catch java cmd.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(?i)^(\\w:.*\\)Java\\$0" "java (/\\\\.+/)java/": prefix: "_regex_java" description: 'Template regex expression to catch java cmd.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "^(/\\\\.+/)java/$0" "ipv4 (\\\\d+(?:\\\\.\\\\d+){3})": prefix: "_regex_ipv4" description: 'Template regex expression to catch ipv4.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(\\\\d+(?:\\\\.\\\\d+){3})$0" "ver ^(\\\\d+)": prefix: "_regex_ver" description: 'Template regex expression to catch simple decimals.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "^(\\\\d+)$0" "ver ^\\\\d+\\$": prefix: "_regex_ver" description: 'Template regex expression to catch simple decimals.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "^\\\\d+\\$$0" "Win_path catch path with spaces": prefix: "_regex_Win_path" description: 'Template regex expression to catch path with spaces in windows.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(?i)\\\"([^\"]+)PATH_TO_FILE_LIB\\\"$0" "Win_path_alt catch path with spaces in windows, alternative": prefix: "_regex_Win_path_alt" description: 'Template regex expression to catch path with spaces in windows, alternative.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "([^\"]+)PATH_TO_FILE_CONF$0" # INFERRENCE: https://docs.bmc.com/docs/display/DISCO111/Inference+functions "inference.associate(inferred_node, associate)": prefix: "inference.associate" description: 'Create associate inference relationship(s) from the specified node(s) to the inferred node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.associate' body: "inference.associate(${1:inferred_node}, ${2:associate});$0" "inference.contributor(inferred_node, contributor, contributes)": prefix: "inference.contributor" description: 'Create contributor inference relationship(s) from the specified node(s) to the inferred node, for attribute names specified in the contributes list.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.contributor' body: "inference.contributor(${1:inferred_node}, ${2:contributor}, ${3:contributes});$0" "inference.primary(inferred_node, primary)": prefix: "inference.primary" description: 'Create primary inference relationship(s) from the specified node(s) to the inferred node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.primary' body: "inference.primary(${1:inferred_node}, ${2:primary});$0" "inference.relation(inferred_relationship, source)": prefix: "inference.relation" description: 'Create relation inference relationship(s) from the specified node(s) to the inferred relationship.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.relation' body: "inference.relation(${1:inferred_relationship}, ${2:source});$0" "inference.withdrawal(inferred_node, evidence, withdrawn)": prefix: "inference.withdrawal" description: 'Create withdrawal inference relationship(s) from the specified node(s) to the inferred node, indicating the withdrawal of the withdrawn attribute name.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.withdrawal' body: "inference.withdrawal(${1:inferred_node}, ${2:evidence}, ${3:withdrawn});$0" "inference.destruction(destroyed_node, source)": prefix: "inference.destruction" description: 'When destroying a node, indicate that the source node was responsible for its destruction.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.destruction' body: "inference.destruction(${1:destroyed_node}, ${2:source});$0" # https://docs.bmc.com/docs/display/DISCO111/System+functions "system.getOption(option_name)": prefix: "system.getOption" description: 'Takes the name of a BMC Discovery system option and returns the value.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: "system.getOption(${1:option_name});$0" "system.cmdbSync(nodes)": prefix: "system.cmdbSync" description: 'Addssystem.cmdbSync the given root node or list of root nodes to the CMDB synchronization queue for all sync connections where continuous synchronization is enabled.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: "system.cmdbSync(${1:nodes});$0" # MODEL FUNCTIONS:: "model.addContainment(container, containees)": prefix: "model.addContainment" description: 'Adds the containees to the container by creating suitable relationships between the nodes. containees can be a single node, or a list of nodes, for example: [node1, node2].' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.addContainment' body: "model.addContainment(${1:si_node}, ${2:software_components});$0" "model.setContainment(container, containees)": prefix: "model.setContainment" description: """Equivalent to addContainment, except that at the end of the pattern body, any relationships to contained nodes that have not been confirmed by setContainment or addContainment calls are removed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.setContainment' body: "model.setContainment(${1:cluster_si_node}, ${2:related_sis});$0" "model.destroy(node)": prefix: "model.destroy" description: 'Destroy the specified node or relationship in the model. (Not usually used in pattern bodies, but in removal sections.)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.destroy' body: "model.destroy(${1:dummy});$0" "model.withdraw(node, attribute)": prefix: "model.withdraw" description: 'Removes the named attribute from the node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.withdraw' body: "model.withdraw(si_node, \"${1:detail}\");$0" "model.setRemovalGroup(node, [name])": prefix: "model.setRemovalGroup" description: 'Add the specified node or nodes to a named removal group. The purpose of this function is to identify a group of nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.setRemovalGroup' body: "model.setRemovalGroup(${1:cluster_si}, \"${2:Dummy_Server_Cluster}\");$0" "model.anchorRemovalGroup(node, [name])": prefix: "model.anchorRemovalGroup" description: 'Specify an anchor node for a named removal group. If a group name is not specified the default name group is used.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.anchorRemovalGroup' body: "model.anchorRemovalGroup(${1:si}, \"${2:license_dts}\");$0" "model.suppressRemovalGroup([name])": prefix: "model.suppressRemovalGroup" description: 'Suppress removal of the named removal group. If a group name is not specified the default name group is used. ' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.suppressRemovalGroup' body: "model.suppressRemovalGroup(\"%${1:detail_type}%\");$0" "model.host(node)": prefix: "model.host" description: """Returns the Host node corresponding to the given node. The given node can be any directly discovered data node, or a Software Instance or Business Application Instance. If more than one Host is related to the given node (for example a Business Application Instance spread across multiple Hosts), an arbitrary one of the Hosts is returned.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.host' body: "model.host(${1:process});$0" "model.hosts(node)": prefix: "model.hosts" description: """Returns a list of all the Host nodes corresponding to the given node. As with model.host, the given node can be any directly discovered data node or a Software Instance or Business Application Instance.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.hosts' body: "model.hosts(${1:model_sis});$0" "model.findPackages(node, regexes)": prefix: "model.findPackages" description: """Traverses from the node, which must be a Host or a directly discovered data node, and returns a set of all Package nodes that have names matching the provided list of regular expressions.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.findPackages' body: "model.findPackages(host, [regex \"${1:}\"]);$0" "model.addDisplayAttribute(node, value)": prefix: "model.addDisplayAttribute" description: 'Adds a named attribute, or a list of named attributes to the additional attributes displayed in a node view. Added attributes can be removed using model.removeDisplayAttribute.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO113/model.addDisplayAttribute' body: "model.addDisplayAttribute(${1:node}, ${2:value});$0" "model.removeDisplayAttribute(node, value)": prefix: "model.removeDisplayAttribute" description: 'Removes a named attribute, or a list of named attributes from the additional attributes displayed in a node view. Additional attributes are added using the model.addDisplayAttribute function.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO113/model.removeDisplayAttribute' body: "model.removeDisplayAttribute(${1:node}, ${2:value});$0" "model.kind(node)": prefix: "model.kind" description: 'Returns the node kind corresponding to the given node.The given node can be any node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.kind' body: "model.kind(${1:hosting_node});$0" # REL: "model.rel.Communication(Server, Client)": prefix: "rel_Communication" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Communication(Server := ${1:related_sis}, Client := ${2:si_node});$0" "model.rel.Containment(Contained, Container)": prefix: "rel_Containment" description: description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Containment(Contained := ${1:cluster_member_node}, Container := ${2:cluster});$0" "model.rel.Dependency(Dependant, DependedUpon)": prefix: "rel_Dependency" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Dependency(Dependant := ${1:si_node}, DependedUpon := ${2:dep_si});$0" "model.rel.Detail(ElementWithDetail, Detail)": prefix: "rel_Detail" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Detail(ElementWithDetail := ${1:si_node}, Detail := ${2:details});$0" "model.rel.HostContainment(HostContainer, ContainedHost)": prefix: "rel_HostContainment" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.HostContainment(HostContainer := ${1:si_node}, ContainedHost := ${2:host});$0" "model.rel.HostedFile(HostedFile, Host)": prefix: "rel_HostedFile" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.HostedFile(HostedFile := ${1:file}, Host := ${2:host});$0" "model.rel.HostedSoftware(Host, RunningSoftware)": prefix: "rel_HostedSoftware" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.HostedSoftware(Host := ${1:host}, RunningSoftware := ${2:si_node});$0" "model.rel.Management(Manager, ManagedElement)": prefix: "rel_Management" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Management(Manager := ${1:manager_si}, ManagedElement := ${2:si_node});$0" "model.rel.RelatedFile(ElementUsingFile, File)": prefix: "rel_RelatedFile" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.RelatedFile(ElementUsingFile := ${1:si_node}, File := ${2:file});$0" "model.rel.SoftwareService(ServiceProvider, Service)": prefix: "rel_SoftwareService" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.SoftwareService(ServiceProvider := ${1:si_node}, Service := ${2:cluster});$0" "model.rel.SoftwareContainment(SoftwareContainer, ContainedSoftware)": prefix: "rel_SoftwareContainment" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.SoftwareContainment(SoftwareContainer := ${1:si_node}, ContainedSoftware := ${2:sc_lst});$0" "model.rel.StorageUse(Consumer, Provider)": prefix: "rel_StorageUse" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.StorageUse(Consumer := ${1:virtual_disk}, Provider := ${2:dest_disks});$0" # UNIQUE REL: "model.uniquerel.Communication(Server, Client)": prefix: "uniquerel_Communication" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Communication(Server := ${1:related_sis}, Client := ${2:si_node});$0" "model.uniquerel.Containment(Contained, Container)": prefix: "uniquerel_Containment" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Containment(Contained := ${1:cluster_member_node}, Container := ${2:cluster});$0" "model.uniquerel.Dependency(Dependant, DependedUpon)": prefix: "uniquerel_Dependency" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Dependency(Dependant := ${1:si_node}, DependedUpon := ${2:dep_si});$0" "model.uniquerel.Detail(ElementWithDetail, Detail)": prefix: "uniquerel_Detail" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Detail(ElementWithDetail := ${1:si_node}, Detail := ${2:details});$0" "model.uniquerel.HostContainment(HostContainer, ContainedHost)": prefix: "uniquerel_HostContainment" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.HostContainment(HostContainer := ${1:si_node}, ContainedHost := ${2:host});$0" "model.uniquerel.HostedFile(HostedFile, Host)": prefix: "uniquerel_HostedFile" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.HostedFile(HostedFile := ${1:file}, Host := ${2:host});$0" "model.uniquerel.HostedSoftware(Host, RunningSoftware)": prefix: "uniquerel_HostedSoftware" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.HostedSoftware(Host := ${1:host}, RunningSoftware := ${2:si_node});$0" "model.uniquerel.HostedService(ServiceHost, RunningService)": prefix: "uniquerel_HostedService" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.HostedService(ServiceHost := ${1:cluster}, RunningService := ${2:cluster_service_node});$0" "model.uniquerel.Management(Manager, ManagedElement)": prefix: "uniquerel_Management" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Management(Manager := ${1:manager_si}, ManagedElement := ${2:si_node});$0" "model.uniquerel.RelatedFile(ElementUsingFile, File)": prefix: "uniquerel_RelatedFile" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.RelatedFile(ElementUsingFile := ${1:si_node}, File := ${2:file});$0" "model.uniquerel.SoftwareService(ServiceProvider, Service)": prefix: "uniquerel_SoftwareService" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.SoftwareService(ServiceProvider := ${1:si_node}, Service := ${2:cluster});$0" "model.uniquerel.SoftwareContainment(SoftwareContainer, ContainedSoftware)": prefix: "uniquerel_SoftwareContainment" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.SoftwareContainment(SoftwareContainer := ${1:si_node}, ContainedSoftware := ${2:sc_lst});$0" "model.uniquerel.StorageUse(Consumer, Provider)": prefix: "uniquerel_StorageUse" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.StorageUse(Consumer := ${1:virtual_disk}, Provider := ${2:dest_disks});$0" # Customization:: "SoftwareInstance Short": prefix: "SoftwareInstance_Short_" body: """ model.SoftwareInstance(key := key, $0name := name, $0short_name := short_name );$0 """ "SoftwareInstance Key": prefix: "SoftwareInstance_Key_" body: """ model.SoftwareInstance(key := \"%port%/%key_si_type%/%host.key%\", $0 name := name, $0 short_name := short_name, $0 version := full_version, $0 product_version := product_version, $0 port := port, $0 listening_ports := listening_ports, $0 type := si_type $0 ); $0 """ "SoftwareInstance Key_group": prefix: "SoftwareInstance_Key_group_" body: """ model.SoftwareInstance(key := \"%port%/%key_si_type%/%host.key%\", $0 name := name, $0 short_name := short_name, $0 version := full_version, $0 product_version := product_version, $0 port := port, $0 listening_ports := listening_ports, $0 type := si_type $0 ); $0 """ "SoftwareInstance Detailed": prefix: "SoftwareInstance_Detailed_" body: """ model.SoftwareInstance(key := \"%product_version%/%si_type%/%host.key%\", $0 name := name, $0 short_name := short_name, $0 version := full_version, $0 product_version := product_version, $0 publisher := publisher, $0 product := product, $0 type := si_type $0 ); $0 """ # Extra: "Communication type model.uniquerel.": prefix: "Communication_type_model.uniquerel._" body: "model.uniquerel.Communication(Server := ${1:related_sis}, Client := ${2:si_node}, type := \"${3:%type%}\");$0" # NUMBER FUNCTIONS:: "number.toChar(number)": prefix: "number.toChar" description: 'Converts the integer number in the ASCII range to a character.If the value is outside the ASCII range, it returns none.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/number.toChar' body: "number.toChar(${1:number});$0" "number.toText(number)": prefix: "number.toText" description: 'Converts the integer number to a text form' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/number.toText' body: "number.toText(${1:number});$0" "number.range(number)": prefix: "number.range" description: 'Generate a list containing 0 to number - 1. If number is less than 1 the list will be empty.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/number.range' body: "number.range(${1:number});$0" # TEXT FUNCTIONS:: "text.lower(string)": prefix: "text.lower" description: 'Returns the lower-cased version of the string argument.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.lower' body: "text.lower(string)$0" "text.upper(string)": prefix: "text.upper" description: 'Returns the upper-cased version of the string argument.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.upper' body: "text.upper(string)$0" "text.toNumber(string [, base ] )": prefix: "text.toNumber" description: """Converts its string argument into a number. By default, the number is treated as a base 10 value; if the optional base is provided, the number is treated as being in the specified base. Bases from 2 to 36 are supported. Bases larger than 10 use the letters a through z to represent digits.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.toNumber' body: "text.toNumber(port);$0" # REPLACE: "text.replace(string, old, new)": prefix: "text.replace" description: 'Returns a modified version of the string formed by replacing all occurrences of the string old with new.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.replace' body: "text.replace(${1:where_string}, \"${2:from_char}\", \"${3:to_char}\");$0" "text.replace() -> replace , to .": prefix: "_text.replace_col" description: 'Template to replace common characters.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.replace' body: "text.replace(${1:string}, \",\", \".\");$0" "text.replace() -> replace - to .": prefix: "_text.replace_min" description: 'Template to replace common characters.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.replace' body: "text.replace(${1:string}, \"-\", \".\");$0" "text.replace() -> replace \\\\ to \\\\\\\\": prefix: "_text.replace_sla" description: 'Template to replace common characters.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.replace' body: "text.replace(${1:string}, \"\\\\\\\", \"\\\\\\\\\\\\\\\");$0" # STRING OPTIONS: "text.join(list, \"separator\")": prefix: "text.join" description: 'Returns a string containing all items in a list of strings joined with the specified separator.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.join' body: "text.join(${1:list}, \"${2:separator}\");$0" "text.split(string, [separator])": prefix: "text.split" description: 'Returns a list consisting of portions of the string split according to the separator string, where specified.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.split' body: "text.split(${1:string}, \"${2:separator}\");$0" "text.strip(string [, characters ] )": prefix: "text.strip" description: 'Strips unwanted characters from the start and end of the given string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.strip' body: "text.strip(${1:string});$0" "text.leftStrip(string [, characters ] )": prefix: "text.leftStrip" description: 'Equivalent to text.strip, but only strips from the left side of the string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.leftStrip' body: "text.leftStrip(${1:string} [, ${2:characters} ] );$0" "text.rightStrip(string [, characters ] )": prefix: "text.rightStrip" description: 'Equivalent to text.strip, but only strips from the right side of the string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.rightStrip' body: "text.rightStrip(${1:string} [, ${2:characters} ] );$0" "text.hash(string)": prefix: "text.hash" description: 'Returns a hashed form of the string, generated with the MD5 hash algorithm.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.hash' body: "text.hash(${1:string});$0" "text.ordinal(string)": prefix: "text.ordinal" description: 'Returns the ordinal value of the string argument. The string must be one character in length.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.ordinal' body: "text.ordinal(${1:string});$0" # LIST: "append list": prefix: "append_list_" body: "list.append(${1:the_list}, ${2:string});$0" # TRAVERCE: "search(in da ::DiscoveryResult:ProcessList \#DiscoveredProcess where pid": prefix: "_trav_rel_proc_parent" description: 'search(in da traverse DiscoveryAccess:DiscoveryAccessResult:DiscoveryResult:ProcessList traverse List:List:Member:DiscoveredProcess where pid' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: """ rel_services := search(in ${1:da_node} traverse DiscoveryAccess:DiscoveryAccessResult:DiscoveryResult:ProcessList $0traverse List:List:Member:DiscoveredProcess where pid = %pproc_pid%);$0 """ "search(in si ::SoftwareContainer:SoftwareInstance": prefix: "_trav_ContainedSoftware::SoftwareInstance" description: 'search(in si traverse ContainedSoftware:SoftwareContainment:SoftwareContainer:SoftwareInstance where type and key <> %key% step in SoftwareContainer:SoftwareContainment where \#:ContainedSoftware:SoftwareInstance.key = si.key)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: """ obsolete_links := search(in ${1:related_si} traverse ContainedSoftware:SoftwareContainment:SoftwareContainer:SoftwareInstance where type = %${2:si_type}% and key <> %key% step in SoftwareContainer:SoftwareContainment where #:ContainedSoftware:SoftwareInstance.key = %${3:related_si}.key%);$0 """ "search(in si ::DiscoveredProcess)": prefix: "_trav_InferredElement::DiscoveredProcess" description: 'search(in si traverse InferredElement:Inference:Primary:DiscoveredProcess)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "procs := search(in si traverse InferredElement:Inference:Primary:DiscoveredProcess);$0" "search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where type)": prefix: "_trav_Host:HostedSoftware::SoftwareInstance" description: 'search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where type)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: """ some_si := search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where ${1:type} = \"${2:type_here}\");$0 """ "search(in si ::Communication:Server:SoftwareInstance where type": prefix: "_trav_Client::SoftwareInstance" description: 'search(in si traverse Client:Communication:Server:SoftwareInstance where type = smth)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "srv_si_list := search(in ${1:related_si} traverse Client:Communication:Server:SoftwareInstance where type = \"${2:type_here}\");$0" "search(in si ::Client:SoftwareInstance where type": prefix: "_trav_Server::SoftwareInstance" description: 'search(in si traverse Server:Communication:Client:SoftwareInstance where type = smth)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "client_si_list := search(in ${1:related_si} traverse Server:Communication:Client:SoftwareInstance where type = \"${2:type_here}\");$0" "search(in si ::SoftwareContainer:BusinessApplicationInstance where type": prefix: "_trav_ContainedSoftware::BusinessApplicationInstance" description: 'search(in si traverse ContainedSoftware:SoftwareContainment:SoftwareContainer:BusinessApplicationInstance where type = si_type)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "bai_candidates := search(in ${1:related_si} traverse ContainedSoftware:SoftwareContainment:SoftwareContainer:BusinessApplicationInstance where type = \"%${2:si_type}%\");$0" "search(in host ::SoftwareInstance where type ::Detail:DatabaseDetail": prefix: "_trav_Host::SoftwareInstance" description: "search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where type = smth traverse ElementWithDetail:Detail:Detail:DatabaseDetail where instance has subword subword)" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "db2_si := search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where type = \"${1:type_here}\" traverse ElementWithDetail:Detail:Detail:DatabaseDetail where instance has subword '%${2:subword}%');$0" "search(in si ::Detail:Detail:Detail where type": prefix: "_trav_ElementWithDetail::Detail" description: 'search(in si traverse ElementWithDetail:Detail:Detail:Detail where type = smth)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "existing_dts := search(in si traverse ElementWithDetail:Detail:Detail:Detail where ${1:type} = \"${2:type_here}\");$0" "search(in si ::DependedUpon:SoftwareInstance": prefix: "_trav_Dependant::SoftwareInstance" description: 'search(in si traverse Dependant:Dependency:DependedUpon:SoftwareInstance)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "mains_si := search(in ${1:related_si} traverse Dependant:Dependency:DependedUpon:SoftwareInstance);$0" "search(in si ::Communication:Server:SoftwareInstance": prefix: "_trav_Client::Server:SoftwareInstance" description: 'search(in si traverse Client:Communication:Server:SoftwareInstance)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "main_db_sis := search(in ${1:related_si} traverse Client:Communication:Server:SoftwareInstance);$0" # OTHER - DIFFERENT: # LOG USUAL: "log.debug(\"message\")": prefix: "log.debug" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.debug' body: "log.debug(\"${1:message}\");$0" "log.info(\"message\")": prefix: "log.info" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.info' body: "log.info(\"${1:message}\");$0" "log.warn(\"message\")": prefix: "log.warn" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.warn' body: "log.warn(\"${1:message}\");$0" "log.error(\"message\")": prefix: "log.error" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.error' body: "log.error(\"${1:message}\");$0" "log.critical(\"message\")": prefix: "log.critical" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.critical' body: "log.critical(\"${1:message}\");$0" # LOG CUSTOM: "_debug simple": prefix: "_debug_simple_" body: "log.debug(\"DEBUG_RUN: -----------> ${1:message} on line:\");$0" "_warn simple": prefix: "_warn_simple_" body: "log.warn(\"DEBUG_RUN: -----------> ${1:message} on line:\");$0" "_debug %variable%": prefix: "_debug_%variable%_" body: "log.debug(\"DEBUG_RUN: -----------> ${1:message} %${2:variable}% - ${4:message} on line:\");$0" "_warn %variable%": prefix: "_warn_%variable%_" body: "log.warn (\"DEBUG_RUN: -----------> ${1:message} %${2:variable}% - ${4:message} on line:\");$0" "_debug %node.attrs%": prefix: "_debug_%node.attrs%_" body: "log.debug(\"DEBUG_RUN: -----------> ${1:message} %${2:host}.${3:name}% - ${4:message} on line:\");$0" "_debug %node.attrs% Exec": prefix: "_debug_%node.attrs%_Exec_" body: """ delta_time_tics := time.toTicks(time.current()) - time.toTicks(start_time); log\\\\.debug(\"DEBUG_RUN: -----------> ${1:message} %${2:host}.${3:name}% - ${4:message} on line: Execution time:\" + number.toText(delta_time_tics/10000) + \"ms\");$0 """ # LOG SI: "_info log SI": prefix: "_info_log_SI_" body: "log.info(\"%host.name%: SI created for %${1:si_type}%\");$0" # EXTRACTIONS REGEX: "regex.extract(string, expression [, substitution] [, no_match])": prefix: "regex.extract" description: 'Returns the result of extracting the regular expression from the string, optionally with a substitution expression and a specified result if no match is found. Returns an empty string, or the string specified in no_match if the expression does not match. ' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extract(${1:string}, ${2:expression}, raw '\\\\1', no_match := '${3:NoMatch}');$0" "regex.extractAll(string, pattern)": prefix: "regex.extractAll" description: 'Returns a list containing all the non-overlapping matches of the pattern in the string. If the pattern contains more than one group, returns a list of lists containing the groups in order.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extractAll(${1:string}, ${2:pattern});$0" "regex.extract(variable, regex regex_raw, raw '\\\\1')": prefix: "regex.extract_Var" description: 'Tamplate for regex - extracting from: variable with some content in it.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extract(${1:variable}, regex \"${2:regex_raw}\", raw '\\\\1');$0" "regex.extract(node.attrs, regex regex_raw, raw '\\\\1')": prefix: "regex.extract_node.attrs" description: 'Tamplate for regex - extracting from: node with attribues.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extract(${1:node}.${2:attrs}, regex \"${3:regex_raw}\", raw '\\\\1');$0" "regex.extract(variable, regex regex_raw, raw '\\\\1', raw '\\\\2)": prefix: "regex.extract_raw_1,2" description: 'Tamplate for regex - extracting from: variable with two groups to check.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extract(${1:variable}, regex \"${2:regex_raw}\", raw '\\\\${3:1}', raw '\\\\${4:2}');$0" # EXTRACTIONS Xpath: "xpath.evaluate(string, expression)": prefix: "xpath.evaluate" description: 'Returns the result of evaluating the xpath expression against the XML string. Returns a list of strings containing the selected values. The result is always a list, even if the expression is guaranteed to always return just one result.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/xpath.evaluate' body: "xpath.evaluate(${1:some_file_path}, \"${2:xpath_string}\");$0" "xpath.openDocument(string)": prefix: "xpath.openDocument" description: 'Returns the DOM object resulting from parsing the XML string. The DOM object returned is suitable for passing to xpath.evaluate.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/xpath.openDocument' body: "xpath.openDocument(${1:some_file_path});$0" "xpath.closeDocument(DOM object)": prefix: "xpath.closeDocument" description: 'Closes the DOM object resulting from xpath.openDocument.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/xpath.closeDocument' body: "xpath.closeDocument(${1:some_file_path});$0" # Table functions: "table( [ parameters ] )": prefix: "table" description: 'Creates a new table.With no parameters, creates an empty table. If parameters are given, initializes the table with items where the keys are the parameter names and the values are the parameter values.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/table' body: "table();$0" "table.remove(table, key)": prefix: "table.remove" description: 'Removes the specified key from the specified table.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/table.remove' body: "table.remove(${1:table}, ${2:key});$0" # CONTAINERS: "related.detailContainer(node)": prefix: "related.detailContainer" description: 'Returns the Software Component, Software Instance, or Business Application Instance node containing the given node.The given node can be a Detail or DatabaseDetail. If no single container node can be found None is returned.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/related.detailContainer' body: "related.detailContainer(${1:node});$0" "related.hostingNode( [\"fallback_kind\"], attributes...)": prefix: "related.hostingNode" description: 'Returns a Host or Cluster node that is associated with the node that triggered the pattern.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/related.hostingNode' body: "related.hostingNode(\"${1:Cluster}\", type := \"${2:SQL Server}\", properties := ${3:required_properties});$0" "related.host(node)": prefix: "related.host" description: 'Returns the Host node corresponding to the given node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/related.host' body: "related.host(${1:node});$0" # https://docs.bmc.com/docs/display/DISCO111/Email+functions "mail.send(recipients, subject, message)": prefix: "mail.send" description: 'Sends an email. recipients is a single string containing an email address, or a list of email address strings; subject is the subject line to use in the email; message is the message contents.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/mail.send' body: "mail.send(${1:recipients}, ${2:subject}, ${3:message});$0" # https://docs.bmc.com/docs/display/DISCO111/Time+functions "time.current()": prefix: "time.current" description: 'Returns an internal datetime object representing the current UTC time.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.current' body: "time.current();$0" "time.delta(days, hours, minutes, seconds)": prefix: "time.delta" description: 'Creates a time delta that can be added to or subtracted from a time represented by an internal datetime object. ' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.delta' body: "time.delta(${1:days}, ${2:hours}, ${3:minutes}, ${4:seconds});$0" "time.parseLocal(string)": prefix: "time.parseLocal" description: 'Converts a string representing a local time into an internal UTC datetime object. If no time zone is present in the string it will use the time zone of the appliance.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.parseLocal' body: "time.parseLocal(${1:string});$0" "time.parseUTC(string)": prefix: "time.parseUTC" description: 'Take a UTC time string and converts it into an internal datetime object. It is not adjusted for timezones or daylight saving time. ' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.parseUTC' body: "time.parseUTC(${1:string});$0" "time.formatLocal(datetime [, format ])": prefix: "time.formatLocal" description: 'Formats an internal datetime object into a human-readable string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.formatLocal' body: "time.formatUTC(${1:lastRebootedDate}, raw \"%m/%d/%Y %H:%M:%S\");$0" "time.formatUTC(datetime [, format ])": prefix: "time.formatUTC" description: 'Formats an internal datetime object into a human-readable string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.formatUTC' body: "time.formatUTC(${1:datetime} [, format ]);$0" "time.toTicks(datetime)": prefix: "time.toTicks" description: 'Converts an internal datatime object (UTC) to ticks.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.toTicks' body: "time.toTicks(${1:datetime});$0" "time.fromTicks(ticks)": prefix: "time.fromTicks" description: 'Converts ticks to an internal datetime object (UTC).' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.fromTicks' body: "time.fromTicks(${1:ticks});$0" "time.deltaFromTicks(ticks)": prefix: "time.deltaFromTicks" description: 'Converts ticks into a time delta.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.deltaFromTicks' body: "time.deltaFromTicks(${1:ticks});$0" # SIMPLE IDENTIFIERS:: "_regex Simple Identifiers": prefix: "_regex_Simple_Identifiers_" body: "(?1:regex )/}\"${1:regex}\" -> \"${2:product_name}\";$0" "_windows_cmd Simple Identifiers": prefix: "_windows_cmd_Simple_Identifiers_" body: "(?1:windows_cmd )/}\"${1:windows_cmd}\" -> \"${2:product_name}\";$0" "_unix_cmd Simple Identifiers": prefix: "_unix_cmd_Simple_Identifiers_" body: "(?1:unix_cmd )/}\"${1:unix_cmd}\" -> \"${2:product_name}\";$0" # IF OS_CLASS:: "_os_class host.os_class": prefix: "_os_class_host.os_class_" body: """ if host.os_class = "Windows" then sep := '\\\\\\'; else sep := '/'; end if; $0 """
95162
# <NAME> # BMC tpl\tplre language completions snippet. # 2017-08-14 - Latest version. ".source.tplpre": # PATTERN BLOCK COMPLETIONS:: "_Copyright BMC Copyright": prefix: "_Copyright_BMC_Copyright_" body: "// INFO: Add current year!\n// (c) Copyright 2019 BMC Software, Inc. All rights reserved.$0" description: 'Copyright info' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/The+Pattern+Language+TPL' "_tpl": prefix: "_tpl" body: "tpl \\$\\$TPLVERSION\\$\\$ module ${1:Module}.${2:Name};$0" description: 'Dev option. Header for TPLPreprocessor' "_pattern": prefix: "_pattern" description: 'Pattern block template' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Pattern+Overview' body: """ pattern ${1:PatternName} 1.0 \"\"\" Pattern trigger on ... Pattern also tries to ... Supported platforms: UNIX Windows \"\"\" metadata products := ''; urls := ''; publishers := ''; categories := ''; known_versions := '', '', ''; end metadata; overview tags TKU, TKU_YYYY_MM_DD, Name, Product; end overview; constants si_type := 'Product Name'; end constants; triggers on process := DiscoveredProcess where cmd matches unix_cmd \"CMD\" and args matches regex \"ARGS\"; end triggers; body host := model.host(process); end body; end pattern; $0 """ "from SearchFunctions": prefix: "from_SearchFunctions_" body: "// INFO: Check the latest version!\nfrom SearchFunctions import SearchFunctions ${1:1}.${2:0};$0" "from RDBMSFunctions": prefix: "from_RDBMSFunctions_" body: "// INFO: Check the latest version!\nfrom RDBMSFunctions import RDBMSFunctions ${1:1}.${2:0};$0" "from DiscoveryFunctions": prefix: "from_DiscoveryFunctions_" body: "// INFO: Check the latest version!\nfrom DiscoveryFunctions import DiscoveryFunctions ${1:1}.${2:0};$0" "from ConversionFunctions": prefix: "from_ConversionFunctions_" body: "// INFO: Check the latest version!\nfrom ConversionFunctions import ConversionFunctions ${1:1}.${2:0};$0" "import Future": prefix: "from_System_Future" body: "// INFO: Check the latest version!\nfrom System import Future ${1:1}.${2:0};$0" # METADATA: "metadata pattern": prefix: "_metadata_pattern" description: 'Metadata in pattern body block template' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Pattern+Overview' body: """ metadata products := \"\"; urls := \"\"; publishers := \"\"; categories := \"\"; known_versions := \"\", \"\", \"\", \"\", \"\"; end metadata; $0 """ "metadata module": prefix: "_metadata_module" description: 'Metadata in module block template' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Pattern+Overview' body: """ metadata origin := \"TKU\"; tkn_name := \"${1:name}\"; tree_path := '${2:category}', '${3:category}', '${4:category}'; end metadata; $0 """ # TRIGGER: "_triggers unix_cmd": prefix: "_triggers_unix_cmd_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on process := DiscoveredProcess where cmd matches unix_cmd \"${1:name}\"; end triggers; $0 """ "_triggers windows_cmd": prefix: "_triggers_windows_cmd_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on process := DiscoveredProcess where cmd matches windows_cmd \"${1:name}\"; end triggers; $0 """ "_triggers host": prefix: "_triggers_host_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on Host created, confirmed where ${1:name}; end triggers; $0 """ "_triggers hardware_detail": prefix: "_triggers_hardware_detail_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on detail := HardwareDetail created, confirmed where ${1:name}; end triggers; $0 """ "_triggers management_controller": prefix: "_triggers_management_controller_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on mc := ManagementController created, confirmed where ${1:name}; end triggers; $0 """ "_triggers network_device": prefix: "_triggers_network_device_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on device := NetworkDevice created, confirmed where ${1:vendor}; end triggers; $0 """ "_triggers software_instance": prefix: "_triggers_software_instance_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on SoftwareInstance created, confirmed where type = ${1:name}; end triggers; $0 """ "_triggers software_component": prefix: "_triggers_software_component_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on SoftwareComponent created, confirmed where instance = ${1:name}; end triggers; $0 """ # IDENTIFIERS: "_identify Simple Identifiers": prefix: "_identify_Simple_Identifiers_" description: 'Identify tables are active tables used to annotate matching nodes with particular values.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Identify' body: """ identify ${1:SOME} 1.0 tags simple_identity, ${2:tag1}; DiscoveredProcess cmd -> simple_identity; end identify; $0 """ # TABLES: "_table Two cols": prefix: "_table_Two_cols_" description: 'Tables provide simple look-up tables that can be used by functions in pattern bodies.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Static+Tables' body: """ table ${1:table_name} 1.0 \"one\" -> \"val_name1\", \"val_name2\"; \"two\" -> \"val_name3\", \"val_name4\"; default -> \"val_name5\", \"val_name6\"; end table; $0 """ "_table One col": prefix: "_table_One_col_" description: 'Tables provide simple look-up tables that can be used by functions in pattern bodies.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Static+Tables' body: """ table ${1:table_name} 1.0 \"one\" -> val_1; \"two\" -> val_2; default -> val_100; end table; $0 """ # DEFINITIONS: "_definitions Small": prefix: "_definitions_Small_" description: 'Additional functions to call in patterns are described in definitions blocks. In TPL 1.5, definitions blocks are used for User defined functions and for data integration with SQL databases.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Definitions' body: """ definitions ${1:def_name} 1.0 \'''${2:Describe definitions}\'''$0 end definitions; $0 """ "_definitions Big": prefix: "_definitions_Big_" description: 'Additional functions to call in patterns are described in definitions blocks. In TPL 1.5, definitions blocks are used for User defined functions and for data integration with SQL databases.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Definitions' body: """ definitions ${1:def_name} 1.0 \'''${2:Describe definitions} Change History: \''' $0 end definitions; $0 """ "_define Function": prefix: "_define_Function_" description: 'User defined functions are specified in definitions blocks. In order to specify a function the type parameter within the definitions block must be set to the value function or omitted.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ define ${1:function_name}(${2:argument}) -> ${3:return} \''' ${4:Describe function} \''' $0 return ${5:dummy}; end define; $0 """ # FULL VERSION: "_full_version (\\\\d*\\\\.\\\\d*)": prefix: "_full_version_(\\\\d*\\\\.\\\\d*)_" description: 'Template for product version extract when full version is obtained.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ // Assign product version if full_version then product_version := regex.extract(full_version, regex '(\\\\d*\\\\.\\\\d*)', raw '\\\\1'); if not product_version then product_version := full_version; end if; end if; $0 """ "_packages Find packages": prefix: "_packages_Find_packages_" description: 'Template for find packages and get full version.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.findPackages' body: """ packages := model.findPackages( host, [regex \"${1:PACKAGE_NAME}\"] ); for package in packages do if package.version then full_version := package.version; break; end if; end for;$0 """ # TPLPRE: # COMMON FUNCTIONS:: # // This is an old implementation, please use new (SearchFunctions.getNodeIp) "OLD functions.validate_host_address_format(rel_host_address)": prefix: "_functions.validate_host_address_format" description: 'OLD Common_functions module. If <rel_host_address> does not meet requirements(regex \'^[\da-z\:][\w\:\.\-]*$\') then functions returns empty string' body: """// WARNING: This is an old implementation, please use new (SearchFunctions.getNodeIp)\nfunctions.validate_host_address_format(${1:rel_host_address});$0""" "OLD functions.domain_lookup(host, rel_host_address_domain)": prefix: "_functions.domain_lookup" description: 'OLD Common_functions module. Function resolves domain to IP address using "nslookup" command' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.domain_lookup(${1:host}, ${2:rel_host_address_domain});$0""" "OLD functions.identify_host_perform_search(host, rel_host_address)": prefix: "_functions.identify_host_perform_search" description: 'OLD Common_functions module. Function searches for one "rel_host_address" Host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions.getHostingNodes)\nfunctions.identify_host_perform_search(${1:host}, ${2:rel_host_address});$0""" "OLD functions.identify_host_perform_search_in_scope(host, rel_host_address, hosts_scope)": prefix: "_functions.identify_host_perform_search_in_scope" description: """OLD Common_functions module. Function searches for one rel_host_address Host in some narrowed scope of hosts, but not on all available hosts like identify_host_perform_search()""" body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.identify_host_perform_search_in_scope(${1:host}, ${2:rel_host_address}, ${3:hosts_scope});$0""" "OLD functions.identify_host(host, rel_host_address, extended)": prefix: "_functions.identify_host" description: 'OLD Common_functions module. Function searches for one "rel_host_address" Host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.identify_host(${1:host}, ${2:rel_host_address}, ${3:extended});$0""" "OLD functions.identify_host_extended(host, rel_host_address, extended)": prefix: "_functions.identify_host_extended" description: 'OLD Common_functions module. Function searches for one "rel_host_address" Host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.identify_host_extended(${1:host}, ${2:rel_host_address}, ${3:extended});$0""" "OLD functions.related_sis_search(host, rel_host_address, rel_si_type)": prefix: "_functions.related_sis_search" description: 'OLD Common_functions module. Function searches for all SIs with "rel_si_type" TYPE on "rel_host_address" host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_sis_search(${1:host}, ${2:rel_host_address}, ${3:rel_si_type});$0""" "OLD functions.related_sis_search_on_multiple_hosts(host, rel_host_addresses, rel_si_type)": prefix: "_functions.related_sis_search_on_multiple_hosts" description: 'OLD Common_functions module. Function searches for all SIs with "rel_si_type" TYPE on multiple "rel_host_addresses" hosts.' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_sis_search_on_multiple_hosts(${1:host}, ${2:rel_host_addresses}, ${3:rel_si_type});$0""" "OLD functions.related_sis_search_on_multiple_hosts_extended(host, rel_host_addresses, rel_si_type)": prefix: "_functions.related_sis_search_on_multiple_hosts_extended" description: 'OLD Common_functions module. Function searches for all SIs with "rel_si_type" TYPE on multiple "rel_host_addresses" hosts.' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_sis_search_on_multiple_hosts_extended(${1:host}, ${2:rel_host_addresses}, ${3:rel_si_type});$0""" "OLD functions.related_sis_search_extended(host, rel_host_address, rel_si_type, extended)": prefix: "_functions.related_sis_search_extended" description: 'OLD Common_functions module. Function searches for all SIs with "rel_si_type" TYPE on "rel_host_address" host.' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_sis_search_extended(${1:host}, ${2:rel_host_address}, ${3:rel_si_type}, ${4:extended}),$0""" "OLD functions.related_si_types_search(host, rel_host_address, rel_si_types)": prefix: "_functions.related_si_types_search" description: 'OLD Common_functions module. Function searches for all SIs with different TYPEs in "rel_si_types" LIST on "rel_host_address" host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_si_types_search(${1:host}, ${2:rel_host_address}, ${3:rel_si_types});$0""" "OLD functions.path_normalization(host, install_root)": prefix: "_functions.path_normalization" description: 'OLD Common_functions module. Current function determines "~" in the path, normalizes it and returns back full path' body: """// WARNING: This is an old implementation, please use new (New.New)\nfunctions.path_normalization(${1:host}, ${2:install_root});$0""" "OLD functions.links_management(si_node, recently_found_sis, related_si_type)": prefix: "_functions.links_management" description: 'OLD Common_functions module. Function that manages Communication and Dependency links between the current SI and related SIs' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.links_management(${1:si_node}, ${2:recently_found_sis}, ${3:related_si_type});$0""" "OLD functions.get_cleanedup_path(path, os)": prefix: "_functions.get_cleanedup_path" description: 'OLD Common_functions module. Function which normalizes directory path by removing "\.\", "\..\", etc.' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.get_cleanedup_path(${1:path}, ${2:os});$0""" "OLD functions.get_max_version(ver1, ver2)": prefix: "_functions.get_max_version" description: 'OLD Common_functions module. Compares to version strings like "10.08.10" and "7.18" and returns the biggest one' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.get_max_version(${1:ver1}, ${2:ver2});$0""" "OLD functions.get_exe_cwd_path(process, expected_binary_name)": prefix: "_functions.get_exe_cwd_path" description: """OLD Common_functions module. Function tries to obtain: - full process command path (exe_path) and/or - current working directory (cwd_path) - directory the process was started from. """ body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.get_exe_cwd_path(${1:process}, ${2:expected_binary_name});$0""" "OLD functions.sort_list(list)": prefix: "_functions.sort_list" description: 'OLD Common_functions module. Function returns sorted list of strings ' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.sort_list(${1:list});$0""" "OLD functions.run_priv_cmd(host, command, priv_cmd := 'PRIV_RUNCMD')": prefix: "_functions.run_priv_cmd" description: """OLD Common_functions module. Run the given command, using privilege elevation on UNIX, if required. The command is first run as given. If this fails, produces no output and the platform is UNIX then the command is executed again using the given priv_cmd. """ body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.run_priv_cmd(${1:host}, ${2:command}, priv_cmd := 'PRIV_RUNCMD');$0""" "OLD functions.has_process(host, command)": prefix: "_functions.has_process" description: 'OLD Common_functions module. Returns true if the given process is running on the given host. ' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.has_process(${1:host}, ${2:command});$0""" "OLD functions.isValidSerialNumber(serial)": prefix: "_functions.isValidSerialNumber" description: 'OLD Common_functions module. Returns true if the given serial number is valid ' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.isValidSerialNumber(${1:serial});$0""" "OLD functions.convertToCharString(ascii_codes)": prefix: "_functions.convertToCharString" description: 'OLD Common_functions module. Converts list of ASCII code integers into a string of characters. ' body: """// WARNING: This is an old implementation, please use new (ConversionFunctions)\nfunctions.convertToCharString(${1:ascii_codes});$0""" "OLD functions.wmiFollowAssociations(host, namespace, initial_paths, associations)": prefix: "_functions.wmiFollowAssociations" description: """OLD Common_functions module. Starting from initial_paths, a list of WMI source instance paths, follows multiple WMI associations to reach a set of target instances. """ body: """// WARNING: This is an old implementation, please use new (ConversionFunctions)\nfunctions.wmiFollowAssociations(${1:host}, ${2:namespace}, ${3:initial_paths}, ${4:associations});$0""" "OLD functions.checkForDecimal(value, bValue)": prefix: "_functions.checkForDecimal" description: 'OLD Common_functions module. Check for decimal and convert the value into Bytes ' body: """// WARNING: This is an old implementation, please use new (ConversionFunctions)\nfunctions.checkForDecimal(${1:value}, ${2:bValue});$0""" "OLD functions.convertToBytes(value, gib)": prefix: "_functions.convertToBytes" description: 'OLD Common_functions module. Convert the value into Bytes ' body: """// WARNING: This is an old implementation, please use new (ConversionFunctions)\nfunctions.convertToBytes(${1:value}, ${2:gib});$0""" "OLD functions.identify_host_with_uuid(uuid)": prefix: "_functions.identify_host_with_uuid" description: 'OLD Common_functions module. Function returns host with searched UUID ' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.identify_host_with_uuid(${1:uuid});$0""" "OLD functions.locateCommands(host, command_list)": prefix: "_functions.locateCommands" description: """OLD Common_functions module. Attempts to locate the required commands. Returns a table of each command location. The location is none if the command could not be found. This call returns none if the location process fails.""" body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.locateCommands(${1:host}, ${2:command_list});$0""" "OLD functions.find_server(host, server_address, port, si_type, alt_types := none, all := false)": prefix: "_functions.find_server" description: 'OLD Common_functions module. Function that searches for the appropriate server node based on the provided server details. ' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)!\nfunctions.find_server(${1:host}, ${2:server_address}, ${3:port}, ${4:si_type}, alt_types := ${5:none}, all := ${6:false});$0""" "OLD functions.checkCommandList(host, command_list)": prefix: "_functions.checkCommandList" description: 'OLD Common_functions module. Checks whether the commands exist. Returns true if all the commands exist. Even one command we are looking for is not present we return false. ' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.checkCommandList(${1:host}, ${2:command_list});$0""" # CONVERSION FUNCTIONS:: "ConversionFunctions.isValidSerialNumber(serial) -> valid": prefix: "ConversionFunctions.isValidSerialNumber" description: 'SupportingFiles ConversionFunctions module -> isValidSerialNumber() - checks if the provided serial number is valid;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.isValidSerialNumber(${1:serial});$0" "isValidSerialNumber(serial) -> valid": prefix: "isValidSerialNumber" description: 'SupportingFiles ConversionFunctions module -> isValidSerialNumber() - checks if the provided serial number is valid;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.isValidSerialNumber(${1:serial});$0" "ConversionFunctions.convertToCharString(ascii_codes) -> ascii_string": prefix: "ConversionFunctions.convertToCharString" description: 'SupportingFiles ConversionFunctions module -> convertToCharString() - converts list of ASCII code integers into a string of characters;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertToCharString(${1:ascii_codes});$0" "convertToCharString(ascii_codes) -> ascii_string": prefix: "convertToCharString" description: 'SupportingFiles ConversionFunctions module -> convertToCharString() - converts list of ASCII code integers into a string of characters;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertToCharString(${1:ascii_codes});$0" "ConversionFunctions.convertToBytes(value, gib) -> result": prefix: "ConversionFunctions.convertToBytes" description: 'SupportingFiles ConversionFunctions module -> convertToBytes() - converts the value into Bytes;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertToBytes(${1:value}, gib);$0" "convertToBytes(value, gib) -> result": prefix: "convertToBytes" description: 'SupportingFiles ConversionFunctions module -> convertToBytes() - converts the value into Bytes;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertToBytes(${1:value}, gib);$0" "ConversionFunctions.convertStringToHex(string, sep := \"\") -> result": prefix: "ConversionFunctions.convertStringToHex" description: 'SupportingFiles ConversionFunctions module -> convertStringToHex() - converts String To HexaDecimal string;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertStringToHex(${1:string}, sep := \"\");$0" "convertStringToHex(string, sep := \"\") -> result": prefix: "convertStringToHex" description: 'SupportingFiles ConversionFunctions module -> convertStringToHex() - converts String To HexaDecimal string;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertStringToHex(${1:string}, sep := \"\");$0" # cluster_support_functions "cluster_support_functions.getHostingNode(host, fallback_kind := Host, instance := inst, clustered_data_path := path)": prefix: "cluster_support_functions.getHostingNode" description: """SI can be identified as clustered (running on cluster): - if SI has specific processes/commands that indicates clustered installation - if SI is managed/monitored by ClusterService. Usually SI\'s instance or paths can be found in ClusterService information. - if SI binary or data directory resides on file system managed by Cluster - if SI is listening on IP address which is managed by Cluster""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.getHostingNode(host, fallback_kind := \"${1:t_host}\", instance := \"${2:inst}\", clustered_data_path := \"${3:path}\");$0" "cluster_support_functions.add_resource_attrs(resource, resource_type, resource_properties, resource_mapping)": prefix: "cluster_support_functions.add_resource_attrs" description: 'Add resource attributes of interest to the cluster resource node along with a standardised resource type attribute.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.add_resource_attrs(${1:resource}, ${2:resource_type}, ${3:resource_properties}, ${4:resource_mapping});$0" "cluster_support_functions.get_cluster_dns_names(cluster, ipv4_addrs, ipv6_addrs, host:=none)": prefix: "cluster_support_functions.get_cluster_dns_names" description: 'Get DNS names associated with the hosts of a cluster.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.get_cluster_dns_names(${1:cluster}, ${2:ipv4_addrs}, ${3:ipv6_addrs}, host := \"${4:none}\");$0" "cluster_support_functions.get_cluster_service_vip(si)": prefix: "cluster_support_functions.get_cluster_service_vip" description: 'Obtain the virtual ip address of the provided SoftwareInstance node if it is related to a ClusterService node. Also return the port if reported.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.get_cluster_service_vip(${1:si});$0" "cluster_support_functions.get_si_host(si, ip_addr)": prefix: "cluster_support_functions.get_si_host" description: """Obtain the host related to the provided SoftwareInstance node. If the SoftwareInstance is related to multiple hosts due to the software running on a cluster, then it selects the host based on the host currently supporting the provided IP address or the host known to be actively running the clustered software.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.get_si_host(${1:si}, ${2:ip_addr});$0" # DISCOVERY BUILT IN FUNCTIONS:: "discovery.process(node)": prefix: "discovery.process" description: 'Returns the process node corresponding to the source node, which must be a ListeningPort or NetworkConnection node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.process' body: "discovery.process(${1:process});$0" "discovery.children(node)": prefix: "discovery.children" description: 'Returns a list of the child processes for the given DiscoveredProcess node. Returns an empty list if there no children or the parameter is not a DiscoveredProcess node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.children' body: "discovery.children(${1:process});$0" "discovery.descendents(node)": prefix: "discovery.descendents" description: "Returns a list consisting of the children of the given DiscoveredProcess node, and recursively all of the children's children." descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.descendents' body: "discovery.descendents(${1:process});$0" "discovery.parent(node)": prefix: "discovery.parent" description: 'Returns the parent process for the given DiscoveredProcess node. Returns none if the process has no parent.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.parent' body: "discovery.parent(${1:process});$0" "discovery.allProcesses(node)": prefix: "discovery.allProcesses" description: 'Returns a list of all processes corresponding to the directly discovered data source node. Returns an empty list if the source node is not a valid directly discovered data node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.allProcesses' body: "discovery.allProcesses(${1:process});$0" "discovery.access(node)": prefix: "discovery.access" description: 'Returns the Discovery Access node for the source DDD node, if given. If no node is given, it returns the DiscoveryAccess currently in use.Returns none if the source is not valid.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.access' body: "discovery.access(${1:process});$0" # GET AND QUERY: "discovery.fileGet(host, config_filepath)": prefix: "discovery.fileGet" description: 'Retrieves the specified file. target is a node used to identify the discovery target, either a directly discovered data node, or a Host node. Requires PRIV_CAT to be defined to retrieve files not readable by the current user.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.fileGet' body: "discovery.fileGet(host, ${1:config_filepath});$0" "discovery.fileInfo(host, \"file_path\")": prefix: "discovery.fileInfo" description: "Retrieves information about the specified file, but not the file content. This is useful if the file is a binary file or particularly large." descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.fileInfo' body: "discovery.fileInfo(host, \"${1:file_path}\");$0" "discovery.getNames(target, ip_address)": prefix: "discovery.getNames" description: 'Performs a DNS lookup on the IP address and returns a list of FQDN strings.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.getNames' body: "discovery.getNames(${1:target}, ${2:ip_address});$0" "discovery.listDirectory(host, directory)": prefix: "discovery.listDirectory" description: 'Retrieves the directory listing of the directory specified by the path on the specified target. You cannot use wildcards in the path.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.listDirectory' body: "discovery.listDirectory(host, ${1:directory});$0" "discovery.listRegistry(host, registry_root)": prefix: "discovery.listRegistry" description: 'Returns a list of the registry entries of the registry key specified by the key_path.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.listRegistry' body: "discovery.listRegistry(host, ${1:registry_root});$0" "discovery.registryKey(host, reg_key_inst_dir)": prefix: "discovery.registryKey" description: 'Retrieves a registry key from a Windows computer.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.registryKey' body: "discovery.registryKey(host, ${1:reg_key_inst_dir});$0" "discovery.wmiQuery(host, wmiQuery, wmiNS)": prefix: "discovery.wmiQuery_wmiNS" description: 'Performs a WMI query on a Windows computer. Returns a list of DiscoveredWMI nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.wmiQuery' body: "discovery.wmiQuery(host, ${1:wmiQuery}, ${2:wmiNS});$0" "discovery.wmiQuery(host, wmiQuery, raw \"path_to\")": prefix: "discovery.wmiQuery_path_to" description: 'Performs a WMI query on a Windows computer. Returns a list of DiscoveredWMI nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.wmiQuery' body: "discovery.wmiQuery(host, ${1:wmiQuery}, raw \"${2:path_to}\");$0" "discovery.wbemQuery(target, class_name, [properties], namespace)": prefix: "discovery.wbemQuery" description: 'Performs a WBEM query on the target and returns a list of DiscoveredWBEM DDD nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.wbemQuery' body: "discovery.wbemQuery(${1:target}, ${2:class_name}, [${3:properties}], ${4:namespace});$0" "discovery.wbemEnumInstances(target, class_name, properties, namespace, filter_locally)": prefix: "discovery.wbemEnumInstances" description: 'Performs a WBEM query on the target and returns a list of DiscoveredWBEMInstance DDD nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.wbemEnumInstances' body: "discovery.wbemEnumInstances(${1:target}, ${2:class_name}, ${3:properties}, ${4:namespace}, ${5:filter_locally});$0" # New implementation of runCommand: "Future.runCommand(host, \"command_to_run\", \"path_to_command\")": prefix: "Future.runCommand" description: 'FUTURE Returns a DiscoveredCommandResult node containing the result of running the specified command.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Future.runCommand' body: "Future.runCommand(host, \"${1:command}\", \"${2:path_to_command}\");$0" # Classical implementation of runCommand: "discovery.runCommand(host, \"command_to_run\")": prefix: "discovery.runCommand" description: 'Returns a DiscoveredCommandResult node containing the result of running the specified command.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.runCommand' body: "discovery.runCommand(host, \"${1:command_to_run}\");$0" "discovery.snmpGet(target, oid_table, [binary_oid_list])": prefix: "discovery.snmpGet" description: 'Performs an SNMP query on the target and returns a DiscoveredSNMP node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.snmpGet' body: "discovery.snmpGet(${1:target}, ${2:oid_table}, [${3:binary_oid_list}]);$0" "discovery.snmpGetTable(target, table_oid, column_table, [binary_oid_list])": prefix: "discovery.snmpGetTable" description: 'Performs an SNMP query that returns a table on the target.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.snmpGetTable' body: "discovery.snmpGetTable(${1:target}, ${2:table_oid}, ${3:column_table}, [${4:binary_oid_list}]);$0" # New functions for REST API: "discovery.restfulGet(target, protocol, path[, header])": prefix: "discovery.restfulGet" description: 'Performs a GET request on the target using the RESTful protocol specified and returns a node containing information on the discovered system.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.restfulGet' body: "discovery.restfulGet(${1:target}, ${2:protocol}, ${3:path}[, ${4:header}]);$0" "discovery.restfulPost(target, protocol, path, body[, header])": prefix: "discovery.restfulPost" description: 'Performs a POST request on the target using the RESTful system and returns a node containing information on the discovered system.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.restfulPost' body: "discovery.restfulPost(${1:target}, ${2:protocol}, ${3:path}, ${4:body}[, ${5:header}]);$0" # New functions for vSphere: "discovery.vSphereFindObjects": prefix: "discovery.vSphereFindObjects" description: 'Queries to search from the root folder the instances of an object type and returns the requested properties for each object found.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.vSphereFindObjects' body: "discovery.vSphereFindObjects(${1:vc_host}, \"${2:HostSystem}\", [\"name\", \"hardware.systemInfo.uuid\"]);$0" "discovery.vSphereTraverseToObjects": prefix: "discovery.vSphereTraverseToObjects" description: 'Queries to traverse from the initial object to instances of an object type and get properties on those objects.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.vSphereTraverseToObjects' body: "discovery.vSphereTraverseToObjects(${1:host}, \"${2:HostSystem}\", storage_info.storage_id, \"datastore\", \"Datastore\", [\"name\"]);$0" "discovery.vSphereGetProperties": prefix: "discovery.vSphereGetProperties" description: 'Queries to retrieve properties from a given MOR and returns the requested properties for each object found.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.vSphereGetProperties' body: "discovery.vSphereGetProperties(${1:host}, \"${2:HostSystem}\", host_id, [\"config.storageDevice.scsiLun[\"%disk_info.key%\"].deviceName\", \"config.storageDevice.scsiLun[\"%disk_info.key%\"].capabilities.updateDisplayNameSupported\"]);$0" "discovery.vSphereGetPropertyTable": prefix: "discovery.vSphereGetPropertyTable" description: 'Queries to retrieve a table of values from a given MOR and is intended to be used to retrieve nested properties from lists and arrays.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.vSphereGetPropertyTable' body: "discovery.vSphereGetPropertyTable(${1:host}, \"${2:HostSystem}\", host_id, \"config.storageDevice.scsiLun\", [\"serialNumber\", \"deviceName\"]);$0" # https://docs.bmc.com/docs/display/DISCO111/Binary+functions "binary.toHexString(value)": prefix: "binary.toHexString" description: 'Returns the given binary value as a hex string, that is, two hex digits per byte.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toHexString' body: "binary.toHexString(${1:value});$0" "binary.toIPv4(value)": prefix: "binary.toIPv4" description: 'Returns the given binary value as the text representation of an IPv4 address.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toIPv4' body: "binary.toIPv4(${1:value});$0" "binary.toIPv4z(value)": prefix: "binary.toIPv4z" description: 'Returns the given binary value as the text representation of an IPv4 address with a zone index.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toIPv4z' body: "binary.toIPv4z(${1:value});$0" "binary.toIPv6(value)": prefix: "binary.toIPv6" description: 'Returns the given binary value as the text representation of a canonical IPv6 address.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toIPv6' body: "binary.toIPv6(${1:value});$0" "binary.toIPv6z(value)": prefix: "binary.toIPv6z" description: 'Returns the given binary value as the text representation of a canonical IPv6 address with zone index.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toIPv6z' body: "binary.toIPv6z(${1:value});$0" "binary.toMACAddress(value)": prefix: "binary.toMACAddress" description: 'Returns the given binary value as the text representation of a MAC address.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toMACAddress' body: "binary.toMACAddress(${1:value});$0" "binary.toValue(data, format)": prefix: "binary.toValue" description: 'Converts the given binary value into the specified format.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toValue' body: "binary.toValue(${1:data}, ${2:format});$0" "binary.toWWN(value)": prefix: "binary.toWWN" description: 'Returns the given binary value as the text representation of a WWN value.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toWWN' body: "binary.toWWN(${1:value});$0" # MATRIX: "filepath_info Matrix": prefix: "filepath_info_Matrix" description: 'Development function. Allows us to gather all file get and command run from patterns to show it in docs.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: """ $0// *filepath_info_start $0// filepath_windows := \"${1:filepath_windows}\" $0// filepath_unix := \"${2:filepath_unix}\" $0// reason := \"${3:Obtain something}\" $0// when := \"${4:Only if installation is path obtained}\" $0// *filepath_info_end$0 """ "command_info Matrix": prefix: "command_info_Matrix" description: 'Development function. Allows us to gather all file get and command run from patterns to show it in docs.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: """ $0// *command_info_start $0// command_windows := \"${1:command_windows}\" $0// command_unix := \"${2:command_unix}\" $0// reason := \"${3:Obtain something}\" $0// when := \"${4:Only if installation path is obtained}\" $0// *command_info_end$0 """ "filepath_info Unix Matrix": prefix: "filepath_info_Unix_Matrix" description: 'Development function. Allows us to gather all file get and command run from patterns to show it in docs.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: """ $0// *filepath_info_start $0// filepath_unix := \"${2:filepath_unix}\" $0// reason := \"${3:Obtain something}\" $0// when := \"${4:Only if installation is path obtained}\" $0// *filepath_info_end$0 """ "command_info Windows Matrix": prefix: "command_info_Windows_Matrix" description: 'Development function. Allows us to gather all file get and command run from patterns to show it in docs.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: """ $0// *command_info_start $0// command_windows := \"${1:command_windows}\" $0// reason := \"${3:Obtain something}\" $0// when := \"${4:Only if installation path is obtained}\" $0// *command_info_end$0 """ # JSON: "json.encode(\"value\")": prefix: "json.encode" description: 'Converts value to a JSON encoded string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/json.encode' body: "json.encode(${1:value});$0" "json.decode(\"value\")": prefix: "json.decode" description: 'Decodes a JSON encoded string and returns a structure containing a string, table or list including nested structures.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/json.decode' body: "json.decode(${1:value});$0" # DISCOVERY FUNCTIONS: "DiscoveryFunctions.escapePath(host, install_root) -> install_root": prefix: "DiscoveryFunctions.escapePath" description: 'DiscoveryFunctions.escapePath() -> escape extra characters and resolve /../ in path.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.escapePath(${1:host}, ${2:install_root});$0" "escapePath(host, install_root) -> install_root": prefix: "escapePath" description: 'DiscoveryFunctions.escapePath() -> escape extra characters and resolve /../ in path.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.escapePath(${1:host}, ${2:install_root});$0" "DiscoveryFunctions.escapeArg(host, value, permit_env_vars := false) -> escaped": prefix: "DiscoveryFunctions.escapeArg" description: 'DiscoveryFunctions.escapeArg(host, value, permit_env_vars := false) -> escapes an argument for use in a command' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.escapeArg(${1:host}, ${2:value}, ${2:permit_env_vars} := false);$0" "escapeArg(host, value, permit_env_vars := false) -> escaped": prefix: "escapeArg" description: 'DiscoveryFunctions.escapeArg(host, value, permit_env_vars := false) -> escapes an argument for use in a command' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.escapeArg(${1:host}, ${2:value}, ${2:permit_env_vars} := false);$0" "DiscoveryFunctions.pathNormalization(host, install_root) -> install_root // deprecated": prefix: "DiscoveryFunctions.pathNormalization" description: 'deprecated synonym for expandWindowsPath' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "// deprecated synonym for expandWindowsPath\nDiscoveryFunctions.pathNormalization(${1:host}, ${2:install_root});$0 // deprecated" "pathNormalization(host, install_root) -> install_root // deprecated": prefix: "pathNormalization" description: 'deprecated synonym for expandWindowsPath' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "// deprecated synonym for expandWindowsPath\nDiscoveryFunctions.pathNormalization(${1:host}, ${2:install_root});$0 // deprecated" "DiscoveryFunctions.getCleanedupPath(path, os) -> path_normalized // deprecated": prefix: "DiscoveryFunctions.getCleanedupPath" description: 'deprecated function to normalize a path, like normalizePath, but without expanding Windows short names;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "// deprecated synonym for expandWindowsPath\nDiscoveryFunctions.getCleanedupPath(${1:path}, ${2:os});$0 // deprecated" "getCleanedupPath(path, os) -> path_normalized // deprecated": prefix: "getCleanedupPath" description: 'deprecated function to normalize a path, like normalizePath, but without expanding Windows short names;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "// deprecated synonym for expandWindowsPath\nDiscoveryFunctions.getCleanedupPath(${1:path}, ${2:os});$0 // deprecated" "DiscoveryFunctions.expandWindowsPath(host, path) -> expanded": prefix: "DiscoveryFunctions.expandWindowsPath" description: 'Convert short-form DOS 8.3 names in path into the long form.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.expandWindowsPath(${1:host}, ${2:path});$0" "expandWindowsPath(host, path) -> expanded": prefix: "expandWindowsPath" description: 'Convert short-form DOS 8.3 names in path into the long form.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.expandWindowsPath(${1:host}, ${2:path});$0" "DiscoveryFunctions.getMaxVersion(ver1, ver2) -> maxversion": prefix: "DiscoveryFunctions.getMaxVersion" description: 'DiscoveryFunctions.getMaxVersion() -> compares two versions and returns the highest one.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.getMaxVersion(${1:ver1}, ${2:ver2});$0" "getMaxVersion(ver1, ver2) -> maxversion": prefix: "getMaxVersion" description: 'DiscoveryFunctions.getMaxVersion() -> compares two versions and returns the highest one.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.getMaxVersion(${1:ver1}, ${2:ver2});$0" "DiscoveryFunctions.getExeCwdPath(process, expected_binary_name) -> exe_path, cwd_path": prefix: "DiscoveryFunctions.getExeCwdPath" description: 'DiscoveryFunctions.getExeCwdPath() -> returns full path of the binary file location and the full path from where it\'s been execute.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.getExeCwdPath(${1:process}, ${2:expected_binary_name});$0" "getExeCwdPath(process, expected_binary_name) -> exe_path, cwd_path": prefix: "getExeCwdPath" description: 'DiscoveryFunctions.getExeCwdPath() -> returns full path of the binary file location and the full path from where it\'s been execute.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.getExeCwdPath(${1:process}, ${2:expected_binary_name});$0" "DiscoveryFunctions.sortList(list) -> sorted_list": prefix: "DiscoveryFunctions.sortList" description: 'DiscoveryFunctions.sortList() -> sorts the list and returns its sorted copy.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.sortList(${1:list});$0" "sortList(list) -> sorted_list": prefix: "sortList" description: 'DiscoveryFunctions.sortList() -> sorts the list and returns its sorted copy.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.sortList(${1:list});$0" "DiscoveryFunctions.runActiveCommand(host, command_line, expected_content_regex := none, priv_cmd := none) -> result": prefix: "DiscoveryFunctions.runActiveCommand" description: 'DiscoveryFunctions.runActiveCommand() -> runs the command and then re-runs it with privileged permissions if needed.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.runActiveCommand(${1:host}, ${2:command_line}, expected_content_regex := ${3:none}, priv_cmd := ${4:none});$0" "runActiveCommand(host, command_line, expected_content_regex := none, priv_cmd := none) -> result": prefix: "runActiveCommand" description: 'DiscoveryFunctions.runActiveCommand() -> runs the command and then re-runs it with privileged permissions if needed.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.runActiveCommand(${1:host}, ${2:command_line}, expected_content_regex := ${3:none}, priv_cmd := ${4:none});$0" "DiscoveryFunctions.runFutureActiveCommand(host, command_line, expected_content_regex := none, priv_cmd := none, full_process := full_process) -> result": prefix: "DiscoveryFunctions.runFutureActiveCommand" description: 'DiscoveryFunctions.runFutureActiveCommand() -> runs the command and then re-runs it with privileged permissions if needed.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.runFutureActiveCommand(${1:host}, ${2:command_line}, expected_content_regex := ${3:none}, priv_cmd := ${4:none}, full_process := ${5:full_process});$0" "runFutureActiveCommand(host, command_line, expected_content_regex := none, priv_cmd := none, full_process := full_process) -> result": prefix: "runFutureActiveCommand" description: 'DiscoveryFunctions.runFutureActiveCommand() -> runs the command and then re-runs it with privileged permissions if needed.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.runFutureActiveCommand(${1:host}, ${2:command_line}, expected_content_regex := ${3:none}, priv_cmd := ${4:none}, full_process := ${5:full_process});$0" "DiscoveryFunctions.locateCommands(host, command_list) -> result": prefix: "DiscoveryFunctions.locateCommands" description: 'DiscoveryFunctions.locateCommands() -> searches for the location of the provided command list.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.locateCommands(${1:host}, ${2:command_list});$0" "locateCommands(host, command_list) -> result": prefix: "locateCommands" description: 'DiscoveryFunctions.locateCommands() -> searches for the location of the provided command list.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.locateCommands(${1:host}, ${2:command_list});$0" "DiscoveryFunctions.checkCommandList(host, command_list) -> result": prefix: "DiscoveryFunctions.checkCommandList" description: 'DiscoveryFunctions.checkCommandList() -> checks that the list of commands exist on the given Host.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.checkCommandList(${1:host}, ${2:command_list});$0" "checkCommandList(host, command_list) -> result": prefix: "checkCommandList" description: 'DiscoveryFunctions.checkCommandList() -> checks that the list of commands exist on the given Host.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.checkCommandList(${1:host}, ${2:command_list});$0" "DiscoveryFunctions.getErrorRegexes(arg1, arg2) -> result": prefix: "DiscoveryFunctions.getErrorRegexes" description: 'returns a list of known regexes to parse errored command outputs' body: "// This is not implemented yet. Reffer to DiscoveryFunctions 1.7 docstrings" "getErrorRegexes(arg1, arg2) -> result": prefix: "getErrorRegexes" description: 'returns a list of known regexes to parse errored command outputs' body: "// This is not implemented yet. Reffer to DiscoveryFunctions 1.7 docstrings" # RDBMS OLD:: # // This is an old implementation, please use new (RDBMSFunctions) "OLD rdbms_functions.oracle_ora_file_parser(section_name, oracle_ora_file_content) -> section": prefix: "_rdbms_functions.oracle_ora_file_parser" description: 'OLD rdbms_functions.oracle_ora_file_parser -> function tries to obtain full section from Oracle listener.ora or tnsnames.ora file. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.oracleOraFileParser)\nrdbms_functions.oracle_ora_file_parser(${1:section_name}, ${2:oracle_ora_file_content});$0""" "OLD rdbms_functions.perform_rdbms_sis_search(related_sis_raw, rel_si_type, instance, port, db_name, extended) -> related_rdbms_sis": prefix: "_rdbms_functions.perform_rdbms_sis_search" description: 'OLD rdbms_functions.perform_rdbms_sis_search -> This internal function is used by related_rdbms_sis_search() and related_rdbms_sis_search_extended() and searches for specific RDBMS SI \"rel_si_type\" TYPE on \"rel_host_address\" host, which can be uniquely identified by attribute (depends on RDBMS Type) ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.perform_rdbms_sis_search(${1:related_sis_raw}, ${2:rel_si_type}, ${3:instance}, ${4:port}, ${5:db_name}, ${6:extended});$0""" "OLD rdbms_functions.related_rdbms_sis_search(host, rel_host_address, rel_si_type, instance, port, db_name, extended) -> related_rdbms_sis": prefix: "_rdbms_functions.related_rdbms_sis_search" description: 'OLD rdbms_functions.related_rdbms_sis_search -> Function searches for specific RDBMS SI \"rel_si_type\" TYPE on \"rel_host_address\" host. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.related_rdbms_sis_search(${1:host}, ${2:rel_host_address}, ${3:rel_si_type}, ${4:instance}, ${5:port}, ${6:db_name}, ${7:extended});$0""" "OLD rdbms_functions.related_rdbms_sis_search_extended(host, rel_host_address, rel_si_type, instance, port, db_name, extended) -> related_rdbms_sis": prefix: "_rdbms_functions.related_rdbms_sis_search_extended" description: 'OLD rdbms_functions.related_rdbms_sis_search_extended -> Function searches for specific RDBMS SI \"rel_si_type\" TYPE on \"rel_host_address\" host. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.related_rdbms_sis_search_extended(${1:host}, ${2:rel_host_address}, ${3:rel_si_type}, ${4:instance}, ${5:port}, ${6:db_name}, ${7:extended});$0""" "OLD rdbms_functions.oracle_net_service_name_search(host, net_service_name, tnsnames_file_full_location) -> related_oracle_si": prefix: "_rdbms_functions.oracle_net_service_name_search" description: 'OLD rdbms_functions.oracle_net_service_name_search -> Function returns Oracle Database SI which is end point for local \<net_service_name\>. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.oracleNetServiceNameSearch)\nrdbms_functions.oracle_net_service_name_search(${1:host}, ${2:net_service_name}, ${3:tnsnames_file_full_location});$0""" "OLD rdbms_functions.dsn_rdbms_servers(host,dsn_name) -> db_srvs": prefix: "_rdbms_functions.dsn_rdbms_servers" description: 'OLD rdbms_functions.dsn_rdbms_servers -> Function returns related RDBMS SI by its DSN (Data Source Name) value. For WINDOWS ONLY! ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.dsnRdbmsServers)\nrdbms_functions.dsn_rdbms_servers(${1:host}, ${2:dsn_name});$0""" "OLD rdbms_functions.parseJDBC(url) -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name": prefix: "_rdbms_functions.parseJDBC" description: 'OLD rdbms_functions.parseJDBC -> Parse a JDBC URL and extract the details ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.parseJDBC)\nrdbms_functions.parseJDBC(${1:url});$0""" "OLD rdbms_functions.jdbc_search(host,jdbc_url) -> db_srvs": prefix: "_rdbms_functions.jdbc_search" description: 'OLD rdbms_functions.jdbc_search -> Function returns related RDBMS SI by JDBC URL value. First it parses the JDBC URL(the function from j2eeinferredmodel module was taken as a basis), then it uses related_rdbms_sis_search or oracle_net_service_name_search function to find the related RDBMS SIs. Supported RDBMS: MSSQL, Oracle, DB2, MySQL, PostgreSQL, Ingres DB, Sybase ASE, Informix. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.jdbc_search(${1:host}, ${2:jdbc_url});$0""" "OLD rdbms_functions.find_db_server(host, server_address, port, si_type, db_details) -> server_nodes": prefix: "_rdbms_functions.find_db_server" description: 'OLD rdbms_functions.find_db_server -> Function that searches for the appropriate database server node based on the provided server details. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.find_db_server(${1:host}, ${2:server_address}, ${3:port}, ${4:si_type}, ${5:db_details});$0""" # RDBMS NEW:: "RDBMSFunctions.oracleOraFileParser(section_name, oracle_ora_file_content) -> section": prefix: "RDBMSFunctions.oracleOraFileParser" description: 'obtains full section from Oracle listener.ora or tnsnames.ora files' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.oracleOraFileParser(${1:section_name}, ${2:oracle_ora_file_content}); // -> section$0" "oracleOraFileParser(section_name, oracle_ora_file_content) -> section": prefix: "oracleOraFileParser" description: 'obtains full section from Oracle listener.ora or tnsnames.ora files' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.oracleOraFileParser(${1:section_name}, ${2:oracle_ora_file_content}); // -> section$0" "RDBMSFunctions.performRdbmsSisSearch(related_sis_raw, rel_si_type, port, instance, db_name, ora_service_name, db2_copy_name) -> related_rdbms_nodes": prefix: "RDBMSFunctions.performRdbmsSisSearch" description: 'searches for the RDBMS Software by provided parameters' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ RDBMSFunctions.performRdbmsSisSearch(related_sis_raw = ${1:related_sis_raw}, rel_si_type = ${2:rel_si_type}, port = ${3:port}, instance = ${4:instance}, db_name = ${5:db_name}, ora_service_name = ${6:ora_service_name}, db2_copy_name = ${7:db2_copy_name}); // -> -> related_rdbms_nodes$0 """ "performRdbmsSisSearch(related_sis_raw, rel_si_type, port, instance, db_name, ora_service_name, db2_copy_name) -> related_rdbms_nodes": prefix: "performRdbmsSisSearch" description: 'searches for the RDBMS Software by provided parameters' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ RDBMSFunctions.performRdbmsSisSearch(related_sis_raw = ${1:related_sis_raw}, rel_si_type = ${2:rel_si_type}, port = ${3:port}, instance = ${4:instance}, db_name = ${5:db_name}, ora_service_name = ${6:ora_service_name}, db2_copy_name = ${7:db2_copy_name}); // -> -> related_rdbms_nodes$0 """ "RDBMSFunctions.oracleNetServiceNameSearch(host, net_service_name, tnsnames_file_full_location) -> ora_host, ora_sid, ora_service_name": prefix: "RDBMSFunctions.oracleNetServiceNameSearch" description: 'returns Oracle Database SI parameters by the provided Net Service Name' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ RDBMSFunctions.oracleNetServiceNameSearch(host = ${1:host}, net_service_name = ${2:net_service_name}, tnsnames_file_full_location = ${3:tnsnames_file_full_location}); // -> ora_host, ora_sid, ora_service_name$0 """ "oracleNetServiceNameSearch(host, net_service_name, tnsnames_file_full_location) -> ora_host, ora_sid, ora_service_name": prefix: "oracleNetServiceNameSearch" description: 'returns Oracle Database SI parameters by the provided Net Service Name' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ RDBMSFunctions.oracleNetServiceNameSearch(host = ${1:host}, net_service_name = ${2:net_service_name}, tnsnames_file_full_location = ${3:tnsnames_file_full_location}); // -> ora_host, ora_sid, ora_service_name$0 """ "RDBMSFunctions.dsnRdbmsServers(host,dsn_name) -> db_host, db_type, db_instance, ora_service_name, db_port, db_name": prefix: "RDBMSFunctions.dsnRdbmsServers" description: 'determines RDBMS Server details by the provided DSN' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.dsnRdbmsServers(host, ${1:dsn_name}); // -> db_host, db_type, db_instance, ora_service_name, db_port, db_name$0" "dsnRdbmsServers(host,dsn_name) -> db_host, db_type, db_instance, ora_service_name, db_port, db_name": prefix: "dsnRdbmsServers" description: 'determines RDBMS Server details by the provided DSN' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.dsnRdbmsServers(host, ${1:dsn_name}); // -> db_host, db_type, db_instance, ora_service_name, db_port, db_name$0" "RDBMSFunctions.parseJDBC(url) -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name": prefix: "RDBMSFunctions.parseJDBC" description: 'extracts RDBMS details by the provided JDBC URL' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.parseJDBC(${1:url}); // -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name$0" "parseJDBC(url) -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name": prefix: "parseJDBC" description: 'extracts RDBMS details by the provided JDBC URL' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.parseJDBC(${1:url}); // -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name$0" # SEARCH FUNCTIONS:: "SearchFunctions.getNodeIp(host, rel_host_address_domain) -> node_ip": prefix: "SearchFunctions.getNodeIp" description: 'converts alphanumeric Host address into IP address' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getNodeIp(host, ${1:rel_host_address_domain}); // -> node_ip$0" "getNodeIp(host, rel_host_address_domain) -> node_ip": prefix: "getNodeIp" description: 'converts alphanumeric Host address into IP address' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getNodeIp(host, ${1:rel_host_address_domain}); // -> node_ip$0" "SearchFunctions.getHostingNodes(host, node_address, balancer_port := none) -> hosting_nodes, nodes_type": prefix: "SearchFunctions.getHostingNodes" description: 'searches for Hosting Nodes' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getHostingNodes(host, ${1:node_address}, balancer_port := ${2:none}); // -> hosting_nodes, nodes_type$0" "getHostingNodes(host, node_address, balancer_port := none) -> hosting_nodes, nodes_type": prefix: "getHostingNodes" description: 'searches for Hosting Nodes' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getHostingNodes(host, ${1:node_address}, balancer_port := ${2:none}); // -> hosting_nodes, nodes_type$0" # GET SOFTWARE NODES: "SearchFunctions.getSoftwareNodes(evrything) -> software_nodes": prefix: "SearchFunctions.getSoftwareNodes" description: 'searches for software(SoftwareInstance, DatabaseDetail, SoftwareComponent or LoadBalancerService)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, node_address := ${1:none}, software_type := ${2:none}, balancer_port := ${3:none}, port := ${4:none}, instance := ${5:none}, listen_tcp_socket := ${6:none}, server_name := ${7:none}, installed_product := ${8:none}, db_name := ${9:none}, net_service_name := ${10:none}, ora_service_name := ${11:none}, db2_copy_name := ${12:none}, dsn_name := ${13:none}, jdbc_url := ${14:none}, tnsnames_file_location := ${15:none}, get_remote_nodes_only := ${16:none} ); // -> software_nodes $0 """ "getSoftwareNodes(evrything) -> software_nodes": prefix: "getSoftwareNodes" description: 'searches for software(SoftwareInstance, DatabaseDetail, SoftwareComponent or LoadBalancerService)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, node_address := ${1:none}, software_type := ${2:none}, balancer_port := ${3:none}, port := ${4:none}, instance := ${5:none}, listen_tcp_socket := ${6:none}, server_name := ${7:none}, installed_product := ${8:none}, db_name := ${9:none}, net_service_name := ${10:none}, ora_service_name := ${11:none}, db2_copy_name := ${12:none}, dsn_name := ${13:none}, jdbc_url := ${14:none}, tnsnames_file_location := ${15:none}, get_remote_nodes_only := ${16:none} ); // -> software_nodes $0 """ "SearchFunctions.getSI(related_node, si_types_raw) -> related_si": prefix: "SearchFunctions.getSI" description: 'returns the SI Node which is running behind LoadBalancer or hosts DatabaseDetail Node' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getSI(${1:related_node}, ${2:si_types_raw}); // -> related_si$0" "getSI(related_node, si_types_raw) -> related_si": prefix: "getSI" description: 'returns the SI Node which is running behind LoadBalancer or hosts DatabaseDetail Node' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getSI(${1:related_node}, ${2:si_types_raw}); // -> related_si$0" "SearchFunctions.relatedSisSearchOnMultipleHosts(host, rel_host_addresses, rel_si_type) -> related_sis": prefix: "SearchFunctions.relatedSisSearchOnMultipleHosts" description: 'searches for software on multiple Hosts' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.relatedSisSearchOnMultipleHosts(host, rel_host_addresses = ${1:rel_host_addresses}, rel_si_type = ${2:rel_si_type}); // -> related_sis$0" "relatedSisSearchOnMultipleHosts(host, rel_host_addresses, rel_si_type) -> related_sis": prefix: "relatedSisSearchOnMultipleHosts" description: 'searches for software on multiple Hosts' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.relatedSisSearchOnMultipleHosts(host, rel_host_addresses = ${1:rel_host_addresses}, rel_si_type = ${2:rel_si_type}); // -> related_sis$0" "SearchFunctions.identifyHostWithUuid(uuid) -> searched_host": prefix: "SearchFunctions.identifyHostWithUuid" description: 'searches for the Host with the specific UUID' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.identifyHostWithUuid(${1:uuid}); // -> searched_host$0" "identifyHostWithUuid(uuid) -> searched_host": prefix: "identifyHostWithUuid" description: 'searches for the Host with the specific UUID' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.identifyHostWithUuid(${1:uuid}); // -> searched_host$0" # Templates: # GET SOFTWARE NODES JDBC: "SearchFunctions.getSoftwareNodes(host, jdbc_url)": prefix: "_jdbc_url_SearchFunctions.getSoftwareNodes" description: 'Template of common SearchFunctions.getSoftwareNodes to find database via jdbc url.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, jdbc_url := ${2:jdbc_url}); $0 """ # GET SOFTWARE NODES CUSTOM: "SearchFunctions.getSoftwareNodes(host, node_address, software_type, db_name)": prefix: "_db_host_type_SearchFunctions.getSoftwareNodes" description: 'Template of common SearchFunctions.getSoftwareNodes to find related database.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, node_address := ${1:db_host}, software_type := ${2:db_type}, db_name := ${3:db_name} ); $0 """ "SearchFunctions.getSoftwareNodes(host, node_address, software_type, port, instance, db_name)": prefix: "_db_host_port_SearchFunctions.getSoftwareNodes" description: 'Template of common SearchFunctions.getSoftwareNodes to find related database by node_address, software_type, port, instance, db_name.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, node_address := ${1:db_host}, software_type := ${2:db_type}, port := ${3:port}, instance := ${4:instance}, db_name := ${5:db_name} ); $0 """ # REGEX USUAL USAGE:: "full ver (\\\\d+(?:\\\\.\\\\d+)*) greedy": prefix: "_regex_full_ver" description: 'Template regex expression to catch full version.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(\\\\d+(?:\\\\.\\\\d+)*)$0" "full ver ^(\\\\d+(?:\\\\.\\\\d+)?) zero or one": prefix: "_regex_full_ver_" description: 'Template regex expression to catch full version from start if string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "^(\\\\d+(?:\\\\.\\\\d+)?)$0" "product ver (\\\\d+(?:\\\\.\\\\d+)?) zero or one": prefix: "_regex_product_ver" description: 'Template regex expression to catch product version.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(\\\\d+(?:\\\\.\\\\d+)?)$0" "bjavaw (?i)\\bjavaw?(?:\\\\.exe)\\$": prefix: "_regex_bjavaw" description: 'Template regex expression to catch bjavaw cmd.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(?i)\\bjavaw?(?:\\\\.exe)\\$$0" "bjava (?i)\\bjava(?:\\\\.exe)?\\$": prefix: "_regex_bjava" description: 'Template regex expression to catch bjava cmd.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(?i)\\bjava(?:\\\\.exe)?\\$$0" "java (?i)^(\\w:.*\\)Java\\": prefix: "_regex_java" description: 'Template regex expression to catch java cmd.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(?i)^(\\w:.*\\)Java\\$0" "java (/\\\\.+/)java/": prefix: "_regex_java" description: 'Template regex expression to catch java cmd.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "^(/\\\\.+/)java/$0" "ipv4 (\\\\d+(?:\\\\.\\\\d+){3})": prefix: "_regex_ipv4" description: 'Template regex expression to catch ipv4.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(\\\\d+(?:\\\\.\\\\d+){3})$0" "ver ^(\\\\d+)": prefix: "_regex_ver" description: 'Template regex expression to catch simple decimals.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "^(\\\\d+)$0" "ver ^\\\\d+\\$": prefix: "_regex_ver" description: 'Template regex expression to catch simple decimals.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "^\\\\d+\\$$0" "Win_path catch path with spaces": prefix: "_regex_Win_path" description: 'Template regex expression to catch path with spaces in windows.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(?i)\\\"([^\"]+)PATH_TO_FILE_LIB\\\"$0" "Win_path_alt catch path with spaces in windows, alternative": prefix: "_regex_Win_path_alt" description: 'Template regex expression to catch path with spaces in windows, alternative.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "([^\"]+)PATH_TO_FILE_CONF$0" # INFERRENCE: https://docs.bmc.com/docs/display/DISCO111/Inference+functions "inference.associate(inferred_node, associate)": prefix: "inference.associate" description: 'Create associate inference relationship(s) from the specified node(s) to the inferred node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.associate' body: "inference.associate(${1:inferred_node}, ${2:associate});$0" "inference.contributor(inferred_node, contributor, contributes)": prefix: "inference.contributor" description: 'Create contributor inference relationship(s) from the specified node(s) to the inferred node, for attribute names specified in the contributes list.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.contributor' body: "inference.contributor(${1:inferred_node}, ${2:contributor}, ${3:contributes});$0" "inference.primary(inferred_node, primary)": prefix: "inference.primary" description: 'Create primary inference relationship(s) from the specified node(s) to the inferred node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.primary' body: "inference.primary(${1:inferred_node}, ${2:primary});$0" "inference.relation(inferred_relationship, source)": prefix: "inference.relation" description: 'Create relation inference relationship(s) from the specified node(s) to the inferred relationship.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.relation' body: "inference.relation(${1:inferred_relationship}, ${2:source});$0" "inference.withdrawal(inferred_node, evidence, withdrawn)": prefix: "inference.withdrawal" description: 'Create withdrawal inference relationship(s) from the specified node(s) to the inferred node, indicating the withdrawal of the withdrawn attribute name.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.withdrawal' body: "inference.withdrawal(${1:inferred_node}, ${2:evidence}, ${3:withdrawn});$0" "inference.destruction(destroyed_node, source)": prefix: "inference.destruction" description: 'When destroying a node, indicate that the source node was responsible for its destruction.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.destruction' body: "inference.destruction(${1:destroyed_node}, ${2:source});$0" # https://docs.bmc.com/docs/display/DISCO111/System+functions "system.getOption(option_name)": prefix: "system.getOption" description: 'Takes the name of a BMC Discovery system option and returns the value.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: "system.getOption(${1:option_name});$0" "system.cmdbSync(nodes)": prefix: "system.cmdbSync" description: 'Addssystem.cmdbSync the given root node or list of root nodes to the CMDB synchronization queue for all sync connections where continuous synchronization is enabled.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: "system.cmdbSync(${1:nodes});$0" # MODEL FUNCTIONS:: "model.addContainment(container, containees)": prefix: "model.addContainment" description: 'Adds the containees to the container by creating suitable relationships between the nodes. containees can be a single node, or a list of nodes, for example: [node1, node2].' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.addContainment' body: "model.addContainment(${1:si_node}, ${2:software_components});$0" "model.setContainment(container, containees)": prefix: "model.setContainment" description: """Equivalent to addContainment, except that at the end of the pattern body, any relationships to contained nodes that have not been confirmed by setContainment or addContainment calls are removed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.setContainment' body: "model.setContainment(${1:cluster_si_node}, ${2:related_sis});$0" "model.destroy(node)": prefix: "model.destroy" description: 'Destroy the specified node or relationship in the model. (Not usually used in pattern bodies, but in removal sections.)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.destroy' body: "model.destroy(${1:dummy});$0" "model.withdraw(node, attribute)": prefix: "model.withdraw" description: 'Removes the named attribute from the node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.withdraw' body: "model.withdraw(si_node, \"${1:detail}\");$0" "model.setRemovalGroup(node, [name])": prefix: "model.setRemovalGroup" description: 'Add the specified node or nodes to a named removal group. The purpose of this function is to identify a group of nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.setRemovalGroup' body: "model.setRemovalGroup(${1:cluster_si}, \"${2:Dummy_Server_Cluster}\");$0" "model.anchorRemovalGroup(node, [name])": prefix: "model.anchorRemovalGroup" description: 'Specify an anchor node for a named removal group. If a group name is not specified the default name group is used.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.anchorRemovalGroup' body: "model.anchorRemovalGroup(${1:si}, \"${2:license_dts}\");$0" "model.suppressRemovalGroup([name])": prefix: "model.suppressRemovalGroup" description: 'Suppress removal of the named removal group. If a group name is not specified the default name group is used. ' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.suppressRemovalGroup' body: "model.suppressRemovalGroup(\"%${1:detail_type}%\");$0" "model.host(node)": prefix: "model.host" description: """Returns the Host node corresponding to the given node. The given node can be any directly discovered data node, or a Software Instance or Business Application Instance. If more than one Host is related to the given node (for example a Business Application Instance spread across multiple Hosts), an arbitrary one of the Hosts is returned.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.host' body: "model.host(${1:process});$0" "model.hosts(node)": prefix: "model.hosts" description: """Returns a list of all the Host nodes corresponding to the given node. As with model.host, the given node can be any directly discovered data node or a Software Instance or Business Application Instance.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.hosts' body: "model.hosts(${1:model_sis});$0" "model.findPackages(node, regexes)": prefix: "model.findPackages" description: """Traverses from the node, which must be a Host or a directly discovered data node, and returns a set of all Package nodes that have names matching the provided list of regular expressions.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.findPackages' body: "model.findPackages(host, [regex \"${1:}\"]);$0" "model.addDisplayAttribute(node, value)": prefix: "model.addDisplayAttribute" description: 'Adds a named attribute, or a list of named attributes to the additional attributes displayed in a node view. Added attributes can be removed using model.removeDisplayAttribute.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO113/model.addDisplayAttribute' body: "model.addDisplayAttribute(${1:node}, ${2:value});$0" "model.removeDisplayAttribute(node, value)": prefix: "model.removeDisplayAttribute" description: 'Removes a named attribute, or a list of named attributes from the additional attributes displayed in a node view. Additional attributes are added using the model.addDisplayAttribute function.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO113/model.removeDisplayAttribute' body: "model.removeDisplayAttribute(${1:node}, ${2:value});$0" "model.kind(node)": prefix: "model.kind" description: 'Returns the node kind corresponding to the given node.The given node can be any node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.kind' body: "model.kind(${1:hosting_node});$0" # REL: "model.rel.Communication(Server, Client)": prefix: "rel_Communication" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Communication(Server := ${1:related_sis}, Client := ${2:si_node});$0" "model.rel.Containment(Contained, Container)": prefix: "rel_Containment" description: description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Containment(Contained := ${1:cluster_member_node}, Container := ${2:cluster});$0" "model.rel.Dependency(Dependant, DependedUpon)": prefix: "rel_Dependency" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Dependency(Dependant := ${1:si_node}, DependedUpon := ${2:dep_si});$0" "model.rel.Detail(ElementWithDetail, Detail)": prefix: "rel_Detail" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Detail(ElementWithDetail := ${1:si_node}, Detail := ${2:details});$0" "model.rel.HostContainment(HostContainer, ContainedHost)": prefix: "rel_HostContainment" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.HostContainment(HostContainer := ${1:si_node}, ContainedHost := ${2:host});$0" "model.rel.HostedFile(HostedFile, Host)": prefix: "rel_HostedFile" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.HostedFile(HostedFile := ${1:file}, Host := ${2:host});$0" "model.rel.HostedSoftware(Host, RunningSoftware)": prefix: "rel_HostedSoftware" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.HostedSoftware(Host := ${1:host}, RunningSoftware := ${2:si_node});$0" "model.rel.Management(Manager, ManagedElement)": prefix: "rel_Management" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Management(Manager := ${1:manager_si}, ManagedElement := ${2:si_node});$0" "model.rel.RelatedFile(ElementUsingFile, File)": prefix: "rel_RelatedFile" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.RelatedFile(ElementUsingFile := ${1:si_node}, File := ${2:file});$0" "model.rel.SoftwareService(ServiceProvider, Service)": prefix: "rel_SoftwareService" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.SoftwareService(ServiceProvider := ${1:si_node}, Service := ${2:cluster});$0" "model.rel.SoftwareContainment(SoftwareContainer, ContainedSoftware)": prefix: "rel_SoftwareContainment" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.SoftwareContainment(SoftwareContainer := ${1:si_node}, ContainedSoftware := ${2:sc_lst});$0" "model.rel.StorageUse(Consumer, Provider)": prefix: "rel_StorageUse" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.StorageUse(Consumer := ${1:virtual_disk}, Provider := ${2:dest_disks});$0" # UNIQUE REL: "model.uniquerel.Communication(Server, Client)": prefix: "uniquerel_Communication" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Communication(Server := ${1:related_sis}, Client := ${2:si_node});$0" "model.uniquerel.Containment(Contained, Container)": prefix: "uniquerel_Containment" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Containment(Contained := ${1:cluster_member_node}, Container := ${2:cluster});$0" "model.uniquerel.Dependency(Dependant, DependedUpon)": prefix: "uniquerel_Dependency" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Dependency(Dependant := ${1:si_node}, DependedUpon := ${2:dep_si});$0" "model.uniquerel.Detail(ElementWithDetail, Detail)": prefix: "uniquerel_Detail" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Detail(ElementWithDetail := ${1:si_node}, Detail := ${2:details});$0" "model.uniquerel.HostContainment(HostContainer, ContainedHost)": prefix: "uniquerel_HostContainment" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.HostContainment(HostContainer := ${1:si_node}, ContainedHost := ${2:host});$0" "model.uniquerel.HostedFile(HostedFile, Host)": prefix: "uniquerel_HostedFile" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.HostedFile(HostedFile := ${1:file}, Host := ${2:host});$0" "model.uniquerel.HostedSoftware(Host, RunningSoftware)": prefix: "uniquerel_HostedSoftware" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.HostedSoftware(Host := ${1:host}, RunningSoftware := ${2:si_node});$0" "model.uniquerel.HostedService(ServiceHost, RunningService)": prefix: "uniquerel_HostedService" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.HostedService(ServiceHost := ${1:cluster}, RunningService := ${2:cluster_service_node});$0" "model.uniquerel.Management(Manager, ManagedElement)": prefix: "uniquerel_Management" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Management(Manager := ${1:manager_si}, ManagedElement := ${2:si_node});$0" "model.uniquerel.RelatedFile(ElementUsingFile, File)": prefix: "uniquerel_RelatedFile" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.RelatedFile(ElementUsingFile := ${1:si_node}, File := ${2:file});$0" "model.uniquerel.SoftwareService(ServiceProvider, Service)": prefix: "uniquerel_SoftwareService" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.SoftwareService(ServiceProvider := ${1:si_node}, Service := ${2:cluster});$0" "model.uniquerel.SoftwareContainment(SoftwareContainer, ContainedSoftware)": prefix: "uniquerel_SoftwareContainment" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.SoftwareContainment(SoftwareContainer := ${1:si_node}, ContainedSoftware := ${2:sc_lst});$0" "model.uniquerel.StorageUse(Consumer, Provider)": prefix: "uniquerel_StorageUse" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.StorageUse(Consumer := ${1:virtual_disk}, Provider := ${2:dest_disks});$0" # Customization:: "SoftwareInstance Short": prefix: "SoftwareInstance_Short_" body: """ model.SoftwareInstance(key := key, $0name := name, $0short_name := short_name );$0 """ "SoftwareInstance Key": prefix: "SoftwareInstance_Key_" body: """ model.SoftwareInstance(key := \"%port%/%key_si_type%/%host.key%\", $0 name := name, $0 short_name := short_name, $0 version := full_version, $0 product_version := product_version, $0 port := port, $0 listening_ports := listening_ports, $0 type := si_type $0 ); $0 """ "SoftwareInstance Key_group": prefix: "SoftwareInstance_Key_group_" body: """ model.SoftwareInstance(key := \"%port%/%key_si_type%/%host.key%\", $0 name := name, $0 short_name := short_name, $0 version := full_version, $0 product_version := product_version, $0 port := port, $0 listening_ports := listening_ports, $0 type := si_type $0 ); $0 """ "SoftwareInstance Detailed": prefix: "SoftwareInstance_Detailed_" body: """ model.SoftwareInstance(key := \"%product_version%/%si_type%/%host.key%\", $0 name := name, $0 short_name := short_name, $0 version := full_version, $0 product_version := product_version, $0 publisher := publisher, $0 product := product, $0 type := si_type $0 ); $0 """ # Extra: "Communication type model.uniquerel.": prefix: "Communication_type_model.uniquerel._" body: "model.uniquerel.Communication(Server := ${1:related_sis}, Client := ${2:si_node}, type := \"${3:%type%}\");$0" # NUMBER FUNCTIONS:: "number.toChar(number)": prefix: "number.toChar" description: 'Converts the integer number in the ASCII range to a character.If the value is outside the ASCII range, it returns none.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/number.toChar' body: "number.toChar(${1:number});$0" "number.toText(number)": prefix: "number.toText" description: 'Converts the integer number to a text form' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/number.toText' body: "number.toText(${1:number});$0" "number.range(number)": prefix: "number.range" description: 'Generate a list containing 0 to number - 1. If number is less than 1 the list will be empty.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/number.range' body: "number.range(${1:number});$0" # TEXT FUNCTIONS:: "text.lower(string)": prefix: "text.lower" description: 'Returns the lower-cased version of the string argument.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.lower' body: "text.lower(string)$0" "text.upper(string)": prefix: "text.upper" description: 'Returns the upper-cased version of the string argument.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.upper' body: "text.upper(string)$0" "text.toNumber(string [, base ] )": prefix: "text.toNumber" description: """Converts its string argument into a number. By default, the number is treated as a base 10 value; if the optional base is provided, the number is treated as being in the specified base. Bases from 2 to 36 are supported. Bases larger than 10 use the letters a through z to represent digits.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.toNumber' body: "text.toNumber(port);$0" # REPLACE: "text.replace(string, old, new)": prefix: "text.replace" description: 'Returns a modified version of the string formed by replacing all occurrences of the string old with new.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.replace' body: "text.replace(${1:where_string}, \"${2:from_char}\", \"${3:to_char}\");$0" "text.replace() -> replace , to .": prefix: "_text.replace_col" description: 'Template to replace common characters.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.replace' body: "text.replace(${1:string}, \",\", \".\");$0" "text.replace() -> replace - to .": prefix: "_text.replace_min" description: 'Template to replace common characters.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.replace' body: "text.replace(${1:string}, \"-\", \".\");$0" "text.replace() -> replace \\\\ to \\\\\\\\": prefix: "_text.replace_sla" description: 'Template to replace common characters.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.replace' body: "text.replace(${1:string}, \"\\\\\\\", \"\\\\\\\\\\\\\\\");$0" # STRING OPTIONS: "text.join(list, \"separator\")": prefix: "text.join" description: 'Returns a string containing all items in a list of strings joined with the specified separator.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.join' body: "text.join(${1:list}, \"${2:separator}\");$0" "text.split(string, [separator])": prefix: "text.split" description: 'Returns a list consisting of portions of the string split according to the separator string, where specified.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.split' body: "text.split(${1:string}, \"${2:separator}\");$0" "text.strip(string [, characters ] )": prefix: "text.strip" description: 'Strips unwanted characters from the start and end of the given string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.strip' body: "text.strip(${1:string});$0" "text.leftStrip(string [, characters ] )": prefix: "text.leftStrip" description: 'Equivalent to text.strip, but only strips from the left side of the string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.leftStrip' body: "text.leftStrip(${1:string} [, ${2:characters} ] );$0" "text.rightStrip(string [, characters ] )": prefix: "text.rightStrip" description: 'Equivalent to text.strip, but only strips from the right side of the string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.rightStrip' body: "text.rightStrip(${1:string} [, ${2:characters} ] );$0" "text.hash(string)": prefix: "text.hash" description: 'Returns a hashed form of the string, generated with the MD5 hash algorithm.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.hash' body: "text.hash(${1:string});$0" "text.ordinal(string)": prefix: "text.ordinal" description: 'Returns the ordinal value of the string argument. The string must be one character in length.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.ordinal' body: "text.ordinal(${1:string});$0" # LIST: "append list": prefix: "append_list_" body: "list.append(${1:the_list}, ${2:string});$0" # TRAVERCE: "search(in da ::DiscoveryResult:ProcessList \#DiscoveredProcess where pid": prefix: "_trav_rel_proc_parent" description: 'search(in da traverse DiscoveryAccess:DiscoveryAccessResult:DiscoveryResult:ProcessList traverse List:List:Member:DiscoveredProcess where pid' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: """ rel_services := search(in ${1:da_node} traverse DiscoveryAccess:DiscoveryAccessResult:DiscoveryResult:ProcessList $0traverse List:List:Member:DiscoveredProcess where pid = %pproc_pid%);$0 """ "search(in si ::SoftwareContainer:SoftwareInstance": prefix: "_trav_ContainedSoftware::SoftwareInstance" description: 'search(in si traverse ContainedSoftware:SoftwareContainment:SoftwareContainer:SoftwareInstance where type and key <> %key% step in SoftwareContainer:SoftwareContainment where \#:ContainedSoftware:SoftwareInstance.key = si.key)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: """ obsolete_links := search(in ${1:related_si} traverse ContainedSoftware:SoftwareContainment:SoftwareContainer:SoftwareInstance where type = %${2:si_type}% and key <> %key% step in SoftwareContainer:SoftwareContainment where #:ContainedSoftware:SoftwareInstance.key = %${3:related_si}.key%);$0 """ "search(in si ::DiscoveredProcess)": prefix: "_trav_InferredElement::DiscoveredProcess" description: 'search(in si traverse InferredElement:Inference:Primary:DiscoveredProcess)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "procs := search(in si traverse InferredElement:Inference:Primary:DiscoveredProcess);$0" "search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where type)": prefix: "_trav_Host:HostedSoftware::SoftwareInstance" description: 'search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where type)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: """ some_si := search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where ${1:type} = \"${2:type_here}\");$0 """ "search(in si ::Communication:Server:SoftwareInstance where type": prefix: "_trav_Client::SoftwareInstance" description: 'search(in si traverse Client:Communication:Server:SoftwareInstance where type = smth)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "srv_si_list := search(in ${1:related_si} traverse Client:Communication:Server:SoftwareInstance where type = \"${2:type_here}\");$0" "search(in si ::Client:SoftwareInstance where type": prefix: "_trav_Server::SoftwareInstance" description: 'search(in si traverse Server:Communication:Client:SoftwareInstance where type = smth)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "client_si_list := search(in ${1:related_si} traverse Server:Communication:Client:SoftwareInstance where type = \"${2:type_here}\");$0" "search(in si ::SoftwareContainer:BusinessApplicationInstance where type": prefix: "_trav_ContainedSoftware::BusinessApplicationInstance" description: 'search(in si traverse ContainedSoftware:SoftwareContainment:SoftwareContainer:BusinessApplicationInstance where type = si_type)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "bai_candidates := search(in ${1:related_si} traverse ContainedSoftware:SoftwareContainment:SoftwareContainer:BusinessApplicationInstance where type = \"%${2:si_type}%\");$0" "search(in host ::SoftwareInstance where type ::Detail:DatabaseDetail": prefix: "_trav_Host::SoftwareInstance" description: "search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where type = smth traverse ElementWithDetail:Detail:Detail:DatabaseDetail where instance has subword subword)" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "db2_si := search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where type = \"${1:type_here}\" traverse ElementWithDetail:Detail:Detail:DatabaseDetail where instance has subword '%${2:subword}%');$0" "search(in si ::Detail:Detail:Detail where type": prefix: "_trav_ElementWithDetail::Detail" description: 'search(in si traverse ElementWithDetail:Detail:Detail:Detail where type = smth)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "existing_dts := search(in si traverse ElementWithDetail:Detail:Detail:Detail where ${1:type} = \"${2:type_here}\");$0" "search(in si ::DependedUpon:SoftwareInstance": prefix: "_trav_Dependant::SoftwareInstance" description: 'search(in si traverse Dependant:Dependency:DependedUpon:SoftwareInstance)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "mains_si := search(in ${1:related_si} traverse Dependant:Dependency:DependedUpon:SoftwareInstance);$0" "search(in si ::Communication:Server:SoftwareInstance": prefix: "_trav_Client::Server:SoftwareInstance" description: 'search(in si traverse Client:Communication:Server:SoftwareInstance)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "main_db_sis := search(in ${1:related_si} traverse Client:Communication:Server:SoftwareInstance);$0" # OTHER - DIFFERENT: # LOG USUAL: "log.debug(\"message\")": prefix: "log.debug" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.debug' body: "log.debug(\"${1:message}\");$0" "log.info(\"message\")": prefix: "log.info" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.info' body: "log.info(\"${1:message}\");$0" "log.warn(\"message\")": prefix: "log.warn" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.warn' body: "log.warn(\"${1:message}\");$0" "log.error(\"message\")": prefix: "log.error" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.error' body: "log.error(\"${1:message}\");$0" "log.critical(\"message\")": prefix: "log.critical" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.critical' body: "log.critical(\"${1:message}\");$0" # LOG CUSTOM: "_debug simple": prefix: "_debug_simple_" body: "log.debug(\"DEBUG_RUN: -----------> ${1:message} on line:\");$0" "_warn simple": prefix: "_warn_simple_" body: "log.warn(\"DEBUG_RUN: -----------> ${1:message} on line:\");$0" "_debug %variable%": prefix: "_debug_%variable%_" body: "log.debug(\"DEBUG_RUN: -----------> ${1:message} %${2:variable}% - ${4:message} on line:\");$0" "_warn %variable%": prefix: "_warn_%variable%_" body: "log.warn (\"DEBUG_RUN: -----------> ${1:message} %${2:variable}% - ${4:message} on line:\");$0" "_debug %node.attrs%": prefix: "_debug_%node.attrs%_" body: "log.debug(\"DEBUG_RUN: -----------> ${1:message} %${2:host}.${3:name}% - ${4:message} on line:\");$0" "_debug %node.attrs% Exec": prefix: "_debug_%node.attrs%_Exec_" body: """ delta_time_tics := time.toTicks(time.current()) - time.toTicks(start_time); log\\\\.debug(\"DEBUG_RUN: -----------> ${1:message} %${2:host}.${3:name}% - ${4:message} on line: Execution time:\" + number.toText(delta_time_tics/10000) + \"ms\");$0 """ # LOG SI: "_info log SI": prefix: "_info_log_SI_" body: "log.info(\"%host.name%: SI created for %${1:si_type}%\");$0" # EXTRACTIONS REGEX: "regex.extract(string, expression [, substitution] [, no_match])": prefix: "regex.extract" description: 'Returns the result of extracting the regular expression from the string, optionally with a substitution expression and a specified result if no match is found. Returns an empty string, or the string specified in no_match if the expression does not match. ' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extract(${1:string}, ${2:expression}, raw '\\\\1', no_match := '${3:NoMatch}');$0" "regex.extractAll(string, pattern)": prefix: "regex.extractAll" description: 'Returns a list containing all the non-overlapping matches of the pattern in the string. If the pattern contains more than one group, returns a list of lists containing the groups in order.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extractAll(${1:string}, ${2:pattern});$0" "regex.extract(variable, regex regex_raw, raw '\\\\1')": prefix: "regex.extract_Var" description: 'Tamplate for regex - extracting from: variable with some content in it.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extract(${1:variable}, regex \"${2:regex_raw}\", raw '\\\\1');$0" "regex.extract(node.attrs, regex regex_raw, raw '\\\\1')": prefix: "regex.extract_node.attrs" description: 'Tamplate for regex - extracting from: node with attribues.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extract(${1:node}.${2:attrs}, regex \"${3:regex_raw}\", raw '\\\\1');$0" "regex.extract(variable, regex regex_raw, raw '\\\\1', raw '\\\\2)": prefix: "regex.extract_raw_1,2" description: 'Tamplate for regex - extracting from: variable with two groups to check.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extract(${1:variable}, regex \"${2:regex_raw}\", raw '\\\\${3:1}', raw '\\\\${4:2}');$0" # EXTRACTIONS Xpath: "xpath.evaluate(string, expression)": prefix: "xpath.evaluate" description: 'Returns the result of evaluating the xpath expression against the XML string. Returns a list of strings containing the selected values. The result is always a list, even if the expression is guaranteed to always return just one result.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/xpath.evaluate' body: "xpath.evaluate(${1:some_file_path}, \"${2:xpath_string}\");$0" "xpath.openDocument(string)": prefix: "xpath.openDocument" description: 'Returns the DOM object resulting from parsing the XML string. The DOM object returned is suitable for passing to xpath.evaluate.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/xpath.openDocument' body: "xpath.openDocument(${1:some_file_path});$0" "xpath.closeDocument(DOM object)": prefix: "xpath.closeDocument" description: 'Closes the DOM object resulting from xpath.openDocument.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/xpath.closeDocument' body: "xpath.closeDocument(${1:some_file_path});$0" # Table functions: "table( [ parameters ] )": prefix: "table" description: 'Creates a new table.With no parameters, creates an empty table. If parameters are given, initializes the table with items where the keys are the parameter names and the values are the parameter values.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/table' body: "table();$0" "table.remove(table, key)": prefix: "table.remove" description: 'Removes the specified key from the specified table.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/table.remove' body: "table.remove(${1:table}, ${2:key});$0" # CONTAINERS: "related.detailContainer(node)": prefix: "related.detailContainer" description: 'Returns the Software Component, Software Instance, or Business Application Instance node containing the given node.The given node can be a Detail or DatabaseDetail. If no single container node can be found None is returned.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/related.detailContainer' body: "related.detailContainer(${1:node});$0" "related.hostingNode( [\"fallback_kind\"], attributes...)": prefix: "related.hostingNode" description: 'Returns a Host or Cluster node that is associated with the node that triggered the pattern.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/related.hostingNode' body: "related.hostingNode(\"${1:Cluster}\", type := \"${2:SQL Server}\", properties := ${3:required_properties});$0" "related.host(node)": prefix: "related.host" description: 'Returns the Host node corresponding to the given node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/related.host' body: "related.host(${1:node});$0" # https://docs.bmc.com/docs/display/DISCO111/Email+functions "mail.send(recipients, subject, message)": prefix: "mail.send" description: 'Sends an email. recipients is a single string containing an email address, or a list of email address strings; subject is the subject line to use in the email; message is the message contents.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/mail.send' body: "mail.send(${1:recipients}, ${2:subject}, ${3:message});$0" # https://docs.bmc.com/docs/display/DISCO111/Time+functions "time.current()": prefix: "time.current" description: 'Returns an internal datetime object representing the current UTC time.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.current' body: "time.current();$0" "time.delta(days, hours, minutes, seconds)": prefix: "time.delta" description: 'Creates a time delta that can be added to or subtracted from a time represented by an internal datetime object. ' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.delta' body: "time.delta(${1:days}, ${2:hours}, ${3:minutes}, ${4:seconds});$0" "time.parseLocal(string)": prefix: "time.parseLocal" description: 'Converts a string representing a local time into an internal UTC datetime object. If no time zone is present in the string it will use the time zone of the appliance.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.parseLocal' body: "time.parseLocal(${1:string});$0" "time.parseUTC(string)": prefix: "time.parseUTC" description: 'Take a UTC time string and converts it into an internal datetime object. It is not adjusted for timezones or daylight saving time. ' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.parseUTC' body: "time.parseUTC(${1:string});$0" "time.formatLocal(datetime [, format ])": prefix: "time.formatLocal" description: 'Formats an internal datetime object into a human-readable string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.formatLocal' body: "time.formatUTC(${1:lastRebootedDate}, raw \"%m/%d/%Y %H:%M:%S\");$0" "time.formatUTC(datetime [, format ])": prefix: "time.formatUTC" description: 'Formats an internal datetime object into a human-readable string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.formatUTC' body: "time.formatUTC(${1:datetime} [, format ]);$0" "time.toTicks(datetime)": prefix: "time.toTicks" description: 'Converts an internal datatime object (UTC) to ticks.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.toTicks' body: "time.toTicks(${1:datetime});$0" "time.fromTicks(ticks)": prefix: "time.fromTicks" description: 'Converts ticks to an internal datetime object (UTC).' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.fromTicks' body: "time.fromTicks(${1:ticks});$0" "time.deltaFromTicks(ticks)": prefix: "time.deltaFromTicks" description: 'Converts ticks into a time delta.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.deltaFromTicks' body: "time.deltaFromTicks(${1:ticks});$0" # SIMPLE IDENTIFIERS:: "_regex Simple Identifiers": prefix: "_regex_Simple_Identifiers_" body: "(?1:regex )/}\"${1:regex}\" -> \"${2:product_name}\";$0" "_windows_cmd Simple Identifiers": prefix: "_windows_cmd_Simple_Identifiers_" body: "(?1:windows_cmd )/}\"${1:windows_cmd}\" -> \"${2:product_name}\";$0" "_unix_cmd Simple Identifiers": prefix: "_unix_cmd_Simple_Identifiers_" body: "(?1:unix_cmd )/}\"${1:unix_cmd}\" -> \"${2:product_name}\";$0" # IF OS_CLASS:: "_os_class host.os_class": prefix: "_os_class_host.os_class_" body: """ if host.os_class = "Windows" then sep := '\\\\\\'; else sep := '/'; end if; $0 """
true
# PI:NAME:<NAME>END_PI # BMC tpl\tplre language completions snippet. # 2017-08-14 - Latest version. ".source.tplpre": # PATTERN BLOCK COMPLETIONS:: "_Copyright BMC Copyright": prefix: "_Copyright_BMC_Copyright_" body: "// INFO: Add current year!\n// (c) Copyright 2019 BMC Software, Inc. All rights reserved.$0" description: 'Copyright info' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/The+Pattern+Language+TPL' "_tpl": prefix: "_tpl" body: "tpl \\$\\$TPLVERSION\\$\\$ module ${1:Module}.${2:Name};$0" description: 'Dev option. Header for TPLPreprocessor' "_pattern": prefix: "_pattern" description: 'Pattern block template' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Pattern+Overview' body: """ pattern ${1:PatternName} 1.0 \"\"\" Pattern trigger on ... Pattern also tries to ... Supported platforms: UNIX Windows \"\"\" metadata products := ''; urls := ''; publishers := ''; categories := ''; known_versions := '', '', ''; end metadata; overview tags TKU, TKU_YYYY_MM_DD, Name, Product; end overview; constants si_type := 'Product Name'; end constants; triggers on process := DiscoveredProcess where cmd matches unix_cmd \"CMD\" and args matches regex \"ARGS\"; end triggers; body host := model.host(process); end body; end pattern; $0 """ "from SearchFunctions": prefix: "from_SearchFunctions_" body: "// INFO: Check the latest version!\nfrom SearchFunctions import SearchFunctions ${1:1}.${2:0};$0" "from RDBMSFunctions": prefix: "from_RDBMSFunctions_" body: "// INFO: Check the latest version!\nfrom RDBMSFunctions import RDBMSFunctions ${1:1}.${2:0};$0" "from DiscoveryFunctions": prefix: "from_DiscoveryFunctions_" body: "// INFO: Check the latest version!\nfrom DiscoveryFunctions import DiscoveryFunctions ${1:1}.${2:0};$0" "from ConversionFunctions": prefix: "from_ConversionFunctions_" body: "// INFO: Check the latest version!\nfrom ConversionFunctions import ConversionFunctions ${1:1}.${2:0};$0" "import Future": prefix: "from_System_Future" body: "// INFO: Check the latest version!\nfrom System import Future ${1:1}.${2:0};$0" # METADATA: "metadata pattern": prefix: "_metadata_pattern" description: 'Metadata in pattern body block template' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Pattern+Overview' body: """ metadata products := \"\"; urls := \"\"; publishers := \"\"; categories := \"\"; known_versions := \"\", \"\", \"\", \"\", \"\"; end metadata; $0 """ "metadata module": prefix: "_metadata_module" description: 'Metadata in module block template' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Pattern+Overview' body: """ metadata origin := \"TKU\"; tkn_name := \"${1:name}\"; tree_path := '${2:category}', '${3:category}', '${4:category}'; end metadata; $0 """ # TRIGGER: "_triggers unix_cmd": prefix: "_triggers_unix_cmd_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on process := DiscoveredProcess where cmd matches unix_cmd \"${1:name}\"; end triggers; $0 """ "_triggers windows_cmd": prefix: "_triggers_windows_cmd_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on process := DiscoveredProcess where cmd matches windows_cmd \"${1:name}\"; end triggers; $0 """ "_triggers host": prefix: "_triggers_host_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on Host created, confirmed where ${1:name}; end triggers; $0 """ "_triggers hardware_detail": prefix: "_triggers_hardware_detail_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on detail := HardwareDetail created, confirmed where ${1:name}; end triggers; $0 """ "_triggers management_controller": prefix: "_triggers_management_controller_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on mc := ManagementController created, confirmed where ${1:name}; end triggers; $0 """ "_triggers network_device": prefix: "_triggers_network_device_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on device := NetworkDevice created, confirmed where ${1:vendor}; end triggers; $0 """ "_triggers software_instance": prefix: "_triggers_software_instance_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on SoftwareInstance created, confirmed where type = ${1:name}; end triggers; $0 """ "_triggers software_component": prefix: "_triggers_software_component_" description: 'Triggers define the conditions in which the body of the pattern are evaluated.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Triggers' body: """ triggers on SoftwareComponent created, confirmed where instance = ${1:name}; end triggers; $0 """ # IDENTIFIERS: "_identify Simple Identifiers": prefix: "_identify_Simple_Identifiers_" description: 'Identify tables are active tables used to annotate matching nodes with particular values.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Identify' body: """ identify ${1:SOME} 1.0 tags simple_identity, ${2:tag1}; DiscoveredProcess cmd -> simple_identity; end identify; $0 """ # TABLES: "_table Two cols": prefix: "_table_Two_cols_" description: 'Tables provide simple look-up tables that can be used by functions in pattern bodies.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Static+Tables' body: """ table ${1:table_name} 1.0 \"one\" -> \"val_name1\", \"val_name2\"; \"two\" -> \"val_name3\", \"val_name4\"; default -> \"val_name5\", \"val_name6\"; end table; $0 """ "_table One col": prefix: "_table_One_col_" description: 'Tables provide simple look-up tables that can be used by functions in pattern bodies.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Static+Tables' body: """ table ${1:table_name} 1.0 \"one\" -> val_1; \"two\" -> val_2; default -> val_100; end table; $0 """ # DEFINITIONS: "_definitions Small": prefix: "_definitions_Small_" description: 'Additional functions to call in patterns are described in definitions blocks. In TPL 1.5, definitions blocks are used for User defined functions and for data integration with SQL databases.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Definitions' body: """ definitions ${1:def_name} 1.0 \'''${2:Describe definitions}\'''$0 end definitions; $0 """ "_definitions Big": prefix: "_definitions_Big_" description: 'Additional functions to call in patterns are described in definitions blocks. In TPL 1.5, definitions blocks are used for User defined functions and for data integration with SQL databases.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Definitions' body: """ definitions ${1:def_name} 1.0 \'''${2:Describe definitions} Change History: \''' $0 end definitions; $0 """ "_define Function": prefix: "_define_Function_" description: 'User defined functions are specified in definitions blocks. In order to specify a function the type parameter within the definitions block must be set to the value function or omitted.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ define ${1:function_name}(${2:argument}) -> ${3:return} \''' ${4:Describe function} \''' $0 return ${5:dummy}; end define; $0 """ # FULL VERSION: "_full_version (\\\\d*\\\\.\\\\d*)": prefix: "_full_version_(\\\\d*\\\\.\\\\d*)_" description: 'Template for product version extract when full version is obtained.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ // Assign product version if full_version then product_version := regex.extract(full_version, regex '(\\\\d*\\\\.\\\\d*)', raw '\\\\1'); if not product_version then product_version := full_version; end if; end if; $0 """ "_packages Find packages": prefix: "_packages_Find_packages_" description: 'Template for find packages and get full version.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.findPackages' body: """ packages := model.findPackages( host, [regex \"${1:PACKAGE_NAME}\"] ); for package in packages do if package.version then full_version := package.version; break; end if; end for;$0 """ # TPLPRE: # COMMON FUNCTIONS:: # // This is an old implementation, please use new (SearchFunctions.getNodeIp) "OLD functions.validate_host_address_format(rel_host_address)": prefix: "_functions.validate_host_address_format" description: 'OLD Common_functions module. If <rel_host_address> does not meet requirements(regex \'^[\da-z\:][\w\:\.\-]*$\') then functions returns empty string' body: """// WARNING: This is an old implementation, please use new (SearchFunctions.getNodeIp)\nfunctions.validate_host_address_format(${1:rel_host_address});$0""" "OLD functions.domain_lookup(host, rel_host_address_domain)": prefix: "_functions.domain_lookup" description: 'OLD Common_functions module. Function resolves domain to IP address using "nslookup" command' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.domain_lookup(${1:host}, ${2:rel_host_address_domain});$0""" "OLD functions.identify_host_perform_search(host, rel_host_address)": prefix: "_functions.identify_host_perform_search" description: 'OLD Common_functions module. Function searches for one "rel_host_address" Host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions.getHostingNodes)\nfunctions.identify_host_perform_search(${1:host}, ${2:rel_host_address});$0""" "OLD functions.identify_host_perform_search_in_scope(host, rel_host_address, hosts_scope)": prefix: "_functions.identify_host_perform_search_in_scope" description: """OLD Common_functions module. Function searches for one rel_host_address Host in some narrowed scope of hosts, but not on all available hosts like identify_host_perform_search()""" body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.identify_host_perform_search_in_scope(${1:host}, ${2:rel_host_address}, ${3:hosts_scope});$0""" "OLD functions.identify_host(host, rel_host_address, extended)": prefix: "_functions.identify_host" description: 'OLD Common_functions module. Function searches for one "rel_host_address" Host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.identify_host(${1:host}, ${2:rel_host_address}, ${3:extended});$0""" "OLD functions.identify_host_extended(host, rel_host_address, extended)": prefix: "_functions.identify_host_extended" description: 'OLD Common_functions module. Function searches for one "rel_host_address" Host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.identify_host_extended(${1:host}, ${2:rel_host_address}, ${3:extended});$0""" "OLD functions.related_sis_search(host, rel_host_address, rel_si_type)": prefix: "_functions.related_sis_search" description: 'OLD Common_functions module. Function searches for all SIs with "rel_si_type" TYPE on "rel_host_address" host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_sis_search(${1:host}, ${2:rel_host_address}, ${3:rel_si_type});$0""" "OLD functions.related_sis_search_on_multiple_hosts(host, rel_host_addresses, rel_si_type)": prefix: "_functions.related_sis_search_on_multiple_hosts" description: 'OLD Common_functions module. Function searches for all SIs with "rel_si_type" TYPE on multiple "rel_host_addresses" hosts.' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_sis_search_on_multiple_hosts(${1:host}, ${2:rel_host_addresses}, ${3:rel_si_type});$0""" "OLD functions.related_sis_search_on_multiple_hosts_extended(host, rel_host_addresses, rel_si_type)": prefix: "_functions.related_sis_search_on_multiple_hosts_extended" description: 'OLD Common_functions module. Function searches for all SIs with "rel_si_type" TYPE on multiple "rel_host_addresses" hosts.' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_sis_search_on_multiple_hosts_extended(${1:host}, ${2:rel_host_addresses}, ${3:rel_si_type});$0""" "OLD functions.related_sis_search_extended(host, rel_host_address, rel_si_type, extended)": prefix: "_functions.related_sis_search_extended" description: 'OLD Common_functions module. Function searches for all SIs with "rel_si_type" TYPE on "rel_host_address" host.' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_sis_search_extended(${1:host}, ${2:rel_host_address}, ${3:rel_si_type}, ${4:extended}),$0""" "OLD functions.related_si_types_search(host, rel_host_address, rel_si_types)": prefix: "_functions.related_si_types_search" description: 'OLD Common_functions module. Function searches for all SIs with different TYPEs in "rel_si_types" LIST on "rel_host_address" host' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.related_si_types_search(${1:host}, ${2:rel_host_address}, ${3:rel_si_types});$0""" "OLD functions.path_normalization(host, install_root)": prefix: "_functions.path_normalization" description: 'OLD Common_functions module. Current function determines "~" in the path, normalizes it and returns back full path' body: """// WARNING: This is an old implementation, please use new (New.New)\nfunctions.path_normalization(${1:host}, ${2:install_root});$0""" "OLD functions.links_management(si_node, recently_found_sis, related_si_type)": prefix: "_functions.links_management" description: 'OLD Common_functions module. Function that manages Communication and Dependency links between the current SI and related SIs' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.links_management(${1:si_node}, ${2:recently_found_sis}, ${3:related_si_type});$0""" "OLD functions.get_cleanedup_path(path, os)": prefix: "_functions.get_cleanedup_path" description: 'OLD Common_functions module. Function which normalizes directory path by removing "\.\", "\..\", etc.' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.get_cleanedup_path(${1:path}, ${2:os});$0""" "OLD functions.get_max_version(ver1, ver2)": prefix: "_functions.get_max_version" description: 'OLD Common_functions module. Compares to version strings like "10.08.10" and "7.18" and returns the biggest one' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.get_max_version(${1:ver1}, ${2:ver2});$0""" "OLD functions.get_exe_cwd_path(process, expected_binary_name)": prefix: "_functions.get_exe_cwd_path" description: """OLD Common_functions module. Function tries to obtain: - full process command path (exe_path) and/or - current working directory (cwd_path) - directory the process was started from. """ body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.get_exe_cwd_path(${1:process}, ${2:expected_binary_name});$0""" "OLD functions.sort_list(list)": prefix: "_functions.sort_list" description: 'OLD Common_functions module. Function returns sorted list of strings ' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.sort_list(${1:list});$0""" "OLD functions.run_priv_cmd(host, command, priv_cmd := 'PRIV_RUNCMD')": prefix: "_functions.run_priv_cmd" description: """OLD Common_functions module. Run the given command, using privilege elevation on UNIX, if required. The command is first run as given. If this fails, produces no output and the platform is UNIX then the command is executed again using the given priv_cmd. """ body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.run_priv_cmd(${1:host}, ${2:command}, priv_cmd := 'PRIV_RUNCMD');$0""" "OLD functions.has_process(host, command)": prefix: "_functions.has_process" description: 'OLD Common_functions module. Returns true if the given process is running on the given host. ' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.has_process(${1:host}, ${2:command});$0""" "OLD functions.isValidSerialNumber(serial)": prefix: "_functions.isValidSerialNumber" description: 'OLD Common_functions module. Returns true if the given serial number is valid ' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.isValidSerialNumber(${1:serial});$0""" "OLD functions.convertToCharString(ascii_codes)": prefix: "_functions.convertToCharString" description: 'OLD Common_functions module. Converts list of ASCII code integers into a string of characters. ' body: """// WARNING: This is an old implementation, please use new (ConversionFunctions)\nfunctions.convertToCharString(${1:ascii_codes});$0""" "OLD functions.wmiFollowAssociations(host, namespace, initial_paths, associations)": prefix: "_functions.wmiFollowAssociations" description: """OLD Common_functions module. Starting from initial_paths, a list of WMI source instance paths, follows multiple WMI associations to reach a set of target instances. """ body: """// WARNING: This is an old implementation, please use new (ConversionFunctions)\nfunctions.wmiFollowAssociations(${1:host}, ${2:namespace}, ${3:initial_paths}, ${4:associations});$0""" "OLD functions.checkForDecimal(value, bValue)": prefix: "_functions.checkForDecimal" description: 'OLD Common_functions module. Check for decimal and convert the value into Bytes ' body: """// WARNING: This is an old implementation, please use new (ConversionFunctions)\nfunctions.checkForDecimal(${1:value}, ${2:bValue});$0""" "OLD functions.convertToBytes(value, gib)": prefix: "_functions.convertToBytes" description: 'OLD Common_functions module. Convert the value into Bytes ' body: """// WARNING: This is an old implementation, please use new (ConversionFunctions)\nfunctions.convertToBytes(${1:value}, ${2:gib});$0""" "OLD functions.identify_host_with_uuid(uuid)": prefix: "_functions.identify_host_with_uuid" description: 'OLD Common_functions module. Function returns host with searched UUID ' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)\nfunctions.identify_host_with_uuid(${1:uuid});$0""" "OLD functions.locateCommands(host, command_list)": prefix: "_functions.locateCommands" description: """OLD Common_functions module. Attempts to locate the required commands. Returns a table of each command location. The location is none if the command could not be found. This call returns none if the location process fails.""" body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.locateCommands(${1:host}, ${2:command_list});$0""" "OLD functions.find_server(host, server_address, port, si_type, alt_types := none, all := false)": prefix: "_functions.find_server" description: 'OLD Common_functions module. Function that searches for the appropriate server node based on the provided server details. ' body: """// WARNING: This is an old implementation, please use new (SearchFunctions)!\nfunctions.find_server(${1:host}, ${2:server_address}, ${3:port}, ${4:si_type}, alt_types := ${5:none}, all := ${6:false});$0""" "OLD functions.checkCommandList(host, command_list)": prefix: "_functions.checkCommandList" description: 'OLD Common_functions module. Checks whether the commands exist. Returns true if all the commands exist. Even one command we are looking for is not present we return false. ' body: """// WARNING: This is an old implementation, please use new (DiscoveryFunctions)\nfunctions.checkCommandList(${1:host}, ${2:command_list});$0""" # CONVERSION FUNCTIONS:: "ConversionFunctions.isValidSerialNumber(serial) -> valid": prefix: "ConversionFunctions.isValidSerialNumber" description: 'SupportingFiles ConversionFunctions module -> isValidSerialNumber() - checks if the provided serial number is valid;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.isValidSerialNumber(${1:serial});$0" "isValidSerialNumber(serial) -> valid": prefix: "isValidSerialNumber" description: 'SupportingFiles ConversionFunctions module -> isValidSerialNumber() - checks if the provided serial number is valid;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.isValidSerialNumber(${1:serial});$0" "ConversionFunctions.convertToCharString(ascii_codes) -> ascii_string": prefix: "ConversionFunctions.convertToCharString" description: 'SupportingFiles ConversionFunctions module -> convertToCharString() - converts list of ASCII code integers into a string of characters;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertToCharString(${1:ascii_codes});$0" "convertToCharString(ascii_codes) -> ascii_string": prefix: "convertToCharString" description: 'SupportingFiles ConversionFunctions module -> convertToCharString() - converts list of ASCII code integers into a string of characters;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertToCharString(${1:ascii_codes});$0" "ConversionFunctions.convertToBytes(value, gib) -> result": prefix: "ConversionFunctions.convertToBytes" description: 'SupportingFiles ConversionFunctions module -> convertToBytes() - converts the value into Bytes;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertToBytes(${1:value}, gib);$0" "convertToBytes(value, gib) -> result": prefix: "convertToBytes" description: 'SupportingFiles ConversionFunctions module -> convertToBytes() - converts the value into Bytes;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertToBytes(${1:value}, gib);$0" "ConversionFunctions.convertStringToHex(string, sep := \"\") -> result": prefix: "ConversionFunctions.convertStringToHex" description: 'SupportingFiles ConversionFunctions module -> convertStringToHex() - converts String To HexaDecimal string;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertStringToHex(${1:string}, sep := \"\");$0" "convertStringToHex(string, sep := \"\") -> result": prefix: "convertStringToHex" description: 'SupportingFiles ConversionFunctions module -> convertStringToHex() - converts String To HexaDecimal string;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "ConversionFunctions.convertStringToHex(${1:string}, sep := \"\");$0" # cluster_support_functions "cluster_support_functions.getHostingNode(host, fallback_kind := Host, instance := inst, clustered_data_path := path)": prefix: "cluster_support_functions.getHostingNode" description: """SI can be identified as clustered (running on cluster): - if SI has specific processes/commands that indicates clustered installation - if SI is managed/monitored by ClusterService. Usually SI\'s instance or paths can be found in ClusterService information. - if SI binary or data directory resides on file system managed by Cluster - if SI is listening on IP address which is managed by Cluster""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.getHostingNode(host, fallback_kind := \"${1:t_host}\", instance := \"${2:inst}\", clustered_data_path := \"${3:path}\");$0" "cluster_support_functions.add_resource_attrs(resource, resource_type, resource_properties, resource_mapping)": prefix: "cluster_support_functions.add_resource_attrs" description: 'Add resource attributes of interest to the cluster resource node along with a standardised resource type attribute.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.add_resource_attrs(${1:resource}, ${2:resource_type}, ${3:resource_properties}, ${4:resource_mapping});$0" "cluster_support_functions.get_cluster_dns_names(cluster, ipv4_addrs, ipv6_addrs, host:=none)": prefix: "cluster_support_functions.get_cluster_dns_names" description: 'Get DNS names associated with the hosts of a cluster.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.get_cluster_dns_names(${1:cluster}, ${2:ipv4_addrs}, ${3:ipv6_addrs}, host := \"${4:none}\");$0" "cluster_support_functions.get_cluster_service_vip(si)": prefix: "cluster_support_functions.get_cluster_service_vip" description: 'Obtain the virtual ip address of the provided SoftwareInstance node if it is related to a ClusterService node. Also return the port if reported.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.get_cluster_service_vip(${1:si});$0" "cluster_support_functions.get_si_host(si, ip_addr)": prefix: "cluster_support_functions.get_si_host" description: """Obtain the host related to the provided SoftwareInstance node. If the SoftwareInstance is related to multiple hosts due to the software running on a cluster, then it selects the host based on the host currently supporting the provided IP address or the host known to be actively running the clustered software.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "cluster_support_functions.get_si_host(${1:si}, ${2:ip_addr});$0" # DISCOVERY BUILT IN FUNCTIONS:: "discovery.process(node)": prefix: "discovery.process" description: 'Returns the process node corresponding to the source node, which must be a ListeningPort or NetworkConnection node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.process' body: "discovery.process(${1:process});$0" "discovery.children(node)": prefix: "discovery.children" description: 'Returns a list of the child processes for the given DiscoveredProcess node. Returns an empty list if there no children or the parameter is not a DiscoveredProcess node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.children' body: "discovery.children(${1:process});$0" "discovery.descendents(node)": prefix: "discovery.descendents" description: "Returns a list consisting of the children of the given DiscoveredProcess node, and recursively all of the children's children." descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.descendents' body: "discovery.descendents(${1:process});$0" "discovery.parent(node)": prefix: "discovery.parent" description: 'Returns the parent process for the given DiscoveredProcess node. Returns none if the process has no parent.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.parent' body: "discovery.parent(${1:process});$0" "discovery.allProcesses(node)": prefix: "discovery.allProcesses" description: 'Returns a list of all processes corresponding to the directly discovered data source node. Returns an empty list if the source node is not a valid directly discovered data node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.allProcesses' body: "discovery.allProcesses(${1:process});$0" "discovery.access(node)": prefix: "discovery.access" description: 'Returns the Discovery Access node for the source DDD node, if given. If no node is given, it returns the DiscoveryAccess currently in use.Returns none if the source is not valid.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.access' body: "discovery.access(${1:process});$0" # GET AND QUERY: "discovery.fileGet(host, config_filepath)": prefix: "discovery.fileGet" description: 'Retrieves the specified file. target is a node used to identify the discovery target, either a directly discovered data node, or a Host node. Requires PRIV_CAT to be defined to retrieve files not readable by the current user.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.fileGet' body: "discovery.fileGet(host, ${1:config_filepath});$0" "discovery.fileInfo(host, \"file_path\")": prefix: "discovery.fileInfo" description: "Retrieves information about the specified file, but not the file content. This is useful if the file is a binary file or particularly large." descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.fileInfo' body: "discovery.fileInfo(host, \"${1:file_path}\");$0" "discovery.getNames(target, ip_address)": prefix: "discovery.getNames" description: 'Performs a DNS lookup on the IP address and returns a list of FQDN strings.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.getNames' body: "discovery.getNames(${1:target}, ${2:ip_address});$0" "discovery.listDirectory(host, directory)": prefix: "discovery.listDirectory" description: 'Retrieves the directory listing of the directory specified by the path on the specified target. You cannot use wildcards in the path.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.listDirectory' body: "discovery.listDirectory(host, ${1:directory});$0" "discovery.listRegistry(host, registry_root)": prefix: "discovery.listRegistry" description: 'Returns a list of the registry entries of the registry key specified by the key_path.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.listRegistry' body: "discovery.listRegistry(host, ${1:registry_root});$0" "discovery.registryKey(host, reg_key_inst_dir)": prefix: "discovery.registryKey" description: 'Retrieves a registry key from a Windows computer.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.registryKey' body: "discovery.registryKey(host, ${1:reg_key_inst_dir});$0" "discovery.wmiQuery(host, wmiQuery, wmiNS)": prefix: "discovery.wmiQuery_wmiNS" description: 'Performs a WMI query on a Windows computer. Returns a list of DiscoveredWMI nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.wmiQuery' body: "discovery.wmiQuery(host, ${1:wmiQuery}, ${2:wmiNS});$0" "discovery.wmiQuery(host, wmiQuery, raw \"path_to\")": prefix: "discovery.wmiQuery_path_to" description: 'Performs a WMI query on a Windows computer. Returns a list of DiscoveredWMI nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.wmiQuery' body: "discovery.wmiQuery(host, ${1:wmiQuery}, raw \"${2:path_to}\");$0" "discovery.wbemQuery(target, class_name, [properties], namespace)": prefix: "discovery.wbemQuery" description: 'Performs a WBEM query on the target and returns a list of DiscoveredWBEM DDD nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.wbemQuery' body: "discovery.wbemQuery(${1:target}, ${2:class_name}, [${3:properties}], ${4:namespace});$0" "discovery.wbemEnumInstances(target, class_name, properties, namespace, filter_locally)": prefix: "discovery.wbemEnumInstances" description: 'Performs a WBEM query on the target and returns a list of DiscoveredWBEMInstance DDD nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.wbemEnumInstances' body: "discovery.wbemEnumInstances(${1:target}, ${2:class_name}, ${3:properties}, ${4:namespace}, ${5:filter_locally});$0" # New implementation of runCommand: "Future.runCommand(host, \"command_to_run\", \"path_to_command\")": prefix: "Future.runCommand" description: 'FUTURE Returns a DiscoveredCommandResult node containing the result of running the specified command.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Future.runCommand' body: "Future.runCommand(host, \"${1:command}\", \"${2:path_to_command}\");$0" # Classical implementation of runCommand: "discovery.runCommand(host, \"command_to_run\")": prefix: "discovery.runCommand" description: 'Returns a DiscoveredCommandResult node containing the result of running the specified command.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.runCommand' body: "discovery.runCommand(host, \"${1:command_to_run}\");$0" "discovery.snmpGet(target, oid_table, [binary_oid_list])": prefix: "discovery.snmpGet" description: 'Performs an SNMP query on the target and returns a DiscoveredSNMP node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.snmpGet' body: "discovery.snmpGet(${1:target}, ${2:oid_table}, [${3:binary_oid_list}]);$0" "discovery.snmpGetTable(target, table_oid, column_table, [binary_oid_list])": prefix: "discovery.snmpGetTable" description: 'Performs an SNMP query that returns a table on the target.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.snmpGetTable' body: "discovery.snmpGetTable(${1:target}, ${2:table_oid}, ${3:column_table}, [${4:binary_oid_list}]);$0" # New functions for REST API: "discovery.restfulGet(target, protocol, path[, header])": prefix: "discovery.restfulGet" description: 'Performs a GET request on the target using the RESTful protocol specified and returns a node containing information on the discovered system.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.restfulGet' body: "discovery.restfulGet(${1:target}, ${2:protocol}, ${3:path}[, ${4:header}]);$0" "discovery.restfulPost(target, protocol, path, body[, header])": prefix: "discovery.restfulPost" description: 'Performs a POST request on the target using the RESTful system and returns a node containing information on the discovered system.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.restfulPost' body: "discovery.restfulPost(${1:target}, ${2:protocol}, ${3:path}, ${4:body}[, ${5:header}]);$0" # New functions for vSphere: "discovery.vSphereFindObjects": prefix: "discovery.vSphereFindObjects" description: 'Queries to search from the root folder the instances of an object type and returns the requested properties for each object found.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.vSphereFindObjects' body: "discovery.vSphereFindObjects(${1:vc_host}, \"${2:HostSystem}\", [\"name\", \"hardware.systemInfo.uuid\"]);$0" "discovery.vSphereTraverseToObjects": prefix: "discovery.vSphereTraverseToObjects" description: 'Queries to traverse from the initial object to instances of an object type and get properties on those objects.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.vSphereTraverseToObjects' body: "discovery.vSphereTraverseToObjects(${1:host}, \"${2:HostSystem}\", storage_info.storage_id, \"datastore\", \"Datastore\", [\"name\"]);$0" "discovery.vSphereGetProperties": prefix: "discovery.vSphereGetProperties" description: 'Queries to retrieve properties from a given MOR and returns the requested properties for each object found.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.vSphereGetProperties' body: "discovery.vSphereGetProperties(${1:host}, \"${2:HostSystem}\", host_id, [\"config.storageDevice.scsiLun[\"%disk_info.key%\"].deviceName\", \"config.storageDevice.scsiLun[\"%disk_info.key%\"].capabilities.updateDisplayNameSupported\"]);$0" "discovery.vSphereGetPropertyTable": prefix: "discovery.vSphereGetPropertyTable" description: 'Queries to retrieve a table of values from a given MOR and is intended to be used to retrieve nested properties from lists and arrays.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/discovery.vSphereGetPropertyTable' body: "discovery.vSphereGetPropertyTable(${1:host}, \"${2:HostSystem}\", host_id, \"config.storageDevice.scsiLun\", [\"serialNumber\", \"deviceName\"]);$0" # https://docs.bmc.com/docs/display/DISCO111/Binary+functions "binary.toHexString(value)": prefix: "binary.toHexString" description: 'Returns the given binary value as a hex string, that is, two hex digits per byte.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toHexString' body: "binary.toHexString(${1:value});$0" "binary.toIPv4(value)": prefix: "binary.toIPv4" description: 'Returns the given binary value as the text representation of an IPv4 address.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toIPv4' body: "binary.toIPv4(${1:value});$0" "binary.toIPv4z(value)": prefix: "binary.toIPv4z" description: 'Returns the given binary value as the text representation of an IPv4 address with a zone index.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toIPv4z' body: "binary.toIPv4z(${1:value});$0" "binary.toIPv6(value)": prefix: "binary.toIPv6" description: 'Returns the given binary value as the text representation of a canonical IPv6 address.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toIPv6' body: "binary.toIPv6(${1:value});$0" "binary.toIPv6z(value)": prefix: "binary.toIPv6z" description: 'Returns the given binary value as the text representation of a canonical IPv6 address with zone index.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toIPv6z' body: "binary.toIPv6z(${1:value});$0" "binary.toMACAddress(value)": prefix: "binary.toMACAddress" description: 'Returns the given binary value as the text representation of a MAC address.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toMACAddress' body: "binary.toMACAddress(${1:value});$0" "binary.toValue(data, format)": prefix: "binary.toValue" description: 'Converts the given binary value into the specified format.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toValue' body: "binary.toValue(${1:data}, ${2:format});$0" "binary.toWWN(value)": prefix: "binary.toWWN" description: 'Returns the given binary value as the text representation of a WWN value.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/binary.toWWN' body: "binary.toWWN(${1:value});$0" # MATRIX: "filepath_info Matrix": prefix: "filepath_info_Matrix" description: 'Development function. Allows us to gather all file get and command run from patterns to show it in docs.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: """ $0// *filepath_info_start $0// filepath_windows := \"${1:filepath_windows}\" $0// filepath_unix := \"${2:filepath_unix}\" $0// reason := \"${3:Obtain something}\" $0// when := \"${4:Only if installation is path obtained}\" $0// *filepath_info_end$0 """ "command_info Matrix": prefix: "command_info_Matrix" description: 'Development function. Allows us to gather all file get and command run from patterns to show it in docs.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: """ $0// *command_info_start $0// command_windows := \"${1:command_windows}\" $0// command_unix := \"${2:command_unix}\" $0// reason := \"${3:Obtain something}\" $0// when := \"${4:Only if installation path is obtained}\" $0// *command_info_end$0 """ "filepath_info Unix Matrix": prefix: "filepath_info_Unix_Matrix" description: 'Development function. Allows us to gather all file get and command run from patterns to show it in docs.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: """ $0// *filepath_info_start $0// filepath_unix := \"${2:filepath_unix}\" $0// reason := \"${3:Obtain something}\" $0// when := \"${4:Only if installation is path obtained}\" $0// *filepath_info_end$0 """ "command_info Windows Matrix": prefix: "command_info_Windows_Matrix" description: 'Development function. Allows us to gather all file get and command run from patterns to show it in docs.' # descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: """ $0// *command_info_start $0// command_windows := \"${1:command_windows}\" $0// reason := \"${3:Obtain something}\" $0// when := \"${4:Only if installation path is obtained}\" $0// *command_info_end$0 """ # JSON: "json.encode(\"value\")": prefix: "json.encode" description: 'Converts value to a JSON encoded string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/json.encode' body: "json.encode(${1:value});$0" "json.decode(\"value\")": prefix: "json.decode" description: 'Decodes a JSON encoded string and returns a structure containing a string, table or list including nested structures.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/json.decode' body: "json.decode(${1:value});$0" # DISCOVERY FUNCTIONS: "DiscoveryFunctions.escapePath(host, install_root) -> install_root": prefix: "DiscoveryFunctions.escapePath" description: 'DiscoveryFunctions.escapePath() -> escape extra characters and resolve /../ in path.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.escapePath(${1:host}, ${2:install_root});$0" "escapePath(host, install_root) -> install_root": prefix: "escapePath" description: 'DiscoveryFunctions.escapePath() -> escape extra characters and resolve /../ in path.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.escapePath(${1:host}, ${2:install_root});$0" "DiscoveryFunctions.escapeArg(host, value, permit_env_vars := false) -> escaped": prefix: "DiscoveryFunctions.escapeArg" description: 'DiscoveryFunctions.escapeArg(host, value, permit_env_vars := false) -> escapes an argument for use in a command' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.escapeArg(${1:host}, ${2:value}, ${2:permit_env_vars} := false);$0" "escapeArg(host, value, permit_env_vars := false) -> escaped": prefix: "escapeArg" description: 'DiscoveryFunctions.escapeArg(host, value, permit_env_vars := false) -> escapes an argument for use in a command' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.escapeArg(${1:host}, ${2:value}, ${2:permit_env_vars} := false);$0" "DiscoveryFunctions.pathNormalization(host, install_root) -> install_root // deprecated": prefix: "DiscoveryFunctions.pathNormalization" description: 'deprecated synonym for expandWindowsPath' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "// deprecated synonym for expandWindowsPath\nDiscoveryFunctions.pathNormalization(${1:host}, ${2:install_root});$0 // deprecated" "pathNormalization(host, install_root) -> install_root // deprecated": prefix: "pathNormalization" description: 'deprecated synonym for expandWindowsPath' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "// deprecated synonym for expandWindowsPath\nDiscoveryFunctions.pathNormalization(${1:host}, ${2:install_root});$0 // deprecated" "DiscoveryFunctions.getCleanedupPath(path, os) -> path_normalized // deprecated": prefix: "DiscoveryFunctions.getCleanedupPath" description: 'deprecated function to normalize a path, like normalizePath, but without expanding Windows short names;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "// deprecated synonym for expandWindowsPath\nDiscoveryFunctions.getCleanedupPath(${1:path}, ${2:os});$0 // deprecated" "getCleanedupPath(path, os) -> path_normalized // deprecated": prefix: "getCleanedupPath" description: 'deprecated function to normalize a path, like normalizePath, but without expanding Windows short names;' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "// deprecated synonym for expandWindowsPath\nDiscoveryFunctions.getCleanedupPath(${1:path}, ${2:os});$0 // deprecated" "DiscoveryFunctions.expandWindowsPath(host, path) -> expanded": prefix: "DiscoveryFunctions.expandWindowsPath" description: 'Convert short-form DOS 8.3 names in path into the long form.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.expandWindowsPath(${1:host}, ${2:path});$0" "expandWindowsPath(host, path) -> expanded": prefix: "expandWindowsPath" description: 'Convert short-form DOS 8.3 names in path into the long form.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.expandWindowsPath(${1:host}, ${2:path});$0" "DiscoveryFunctions.getMaxVersion(ver1, ver2) -> maxversion": prefix: "DiscoveryFunctions.getMaxVersion" description: 'DiscoveryFunctions.getMaxVersion() -> compares two versions and returns the highest one.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.getMaxVersion(${1:ver1}, ${2:ver2});$0" "getMaxVersion(ver1, ver2) -> maxversion": prefix: "getMaxVersion" description: 'DiscoveryFunctions.getMaxVersion() -> compares two versions and returns the highest one.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.getMaxVersion(${1:ver1}, ${2:ver2});$0" "DiscoveryFunctions.getExeCwdPath(process, expected_binary_name) -> exe_path, cwd_path": prefix: "DiscoveryFunctions.getExeCwdPath" description: 'DiscoveryFunctions.getExeCwdPath() -> returns full path of the binary file location and the full path from where it\'s been execute.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.getExeCwdPath(${1:process}, ${2:expected_binary_name});$0" "getExeCwdPath(process, expected_binary_name) -> exe_path, cwd_path": prefix: "getExeCwdPath" description: 'DiscoveryFunctions.getExeCwdPath() -> returns full path of the binary file location and the full path from where it\'s been execute.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.getExeCwdPath(${1:process}, ${2:expected_binary_name});$0" "DiscoveryFunctions.sortList(list) -> sorted_list": prefix: "DiscoveryFunctions.sortList" description: 'DiscoveryFunctions.sortList() -> sorts the list and returns its sorted copy.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.sortList(${1:list});$0" "sortList(list) -> sorted_list": prefix: "sortList" description: 'DiscoveryFunctions.sortList() -> sorts the list and returns its sorted copy.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.sortList(${1:list});$0" "DiscoveryFunctions.runActiveCommand(host, command_line, expected_content_regex := none, priv_cmd := none) -> result": prefix: "DiscoveryFunctions.runActiveCommand" description: 'DiscoveryFunctions.runActiveCommand() -> runs the command and then re-runs it with privileged permissions if needed.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.runActiveCommand(${1:host}, ${2:command_line}, expected_content_regex := ${3:none}, priv_cmd := ${4:none});$0" "runActiveCommand(host, command_line, expected_content_regex := none, priv_cmd := none) -> result": prefix: "runActiveCommand" description: 'DiscoveryFunctions.runActiveCommand() -> runs the command and then re-runs it with privileged permissions if needed.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.runActiveCommand(${1:host}, ${2:command_line}, expected_content_regex := ${3:none}, priv_cmd := ${4:none});$0" "DiscoveryFunctions.runFutureActiveCommand(host, command_line, expected_content_regex := none, priv_cmd := none, full_process := full_process) -> result": prefix: "DiscoveryFunctions.runFutureActiveCommand" description: 'DiscoveryFunctions.runFutureActiveCommand() -> runs the command and then re-runs it with privileged permissions if needed.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.runFutureActiveCommand(${1:host}, ${2:command_line}, expected_content_regex := ${3:none}, priv_cmd := ${4:none}, full_process := ${5:full_process});$0" "runFutureActiveCommand(host, command_line, expected_content_regex := none, priv_cmd := none, full_process := full_process) -> result": prefix: "runFutureActiveCommand" description: 'DiscoveryFunctions.runFutureActiveCommand() -> runs the command and then re-runs it with privileged permissions if needed.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.runFutureActiveCommand(${1:host}, ${2:command_line}, expected_content_regex := ${3:none}, priv_cmd := ${4:none}, full_process := ${5:full_process});$0" "DiscoveryFunctions.locateCommands(host, command_list) -> result": prefix: "DiscoveryFunctions.locateCommands" description: 'DiscoveryFunctions.locateCommands() -> searches for the location of the provided command list.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.locateCommands(${1:host}, ${2:command_list});$0" "locateCommands(host, command_list) -> result": prefix: "locateCommands" description: 'DiscoveryFunctions.locateCommands() -> searches for the location of the provided command list.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.locateCommands(${1:host}, ${2:command_list});$0" "DiscoveryFunctions.checkCommandList(host, command_list) -> result": prefix: "DiscoveryFunctions.checkCommandList" description: 'DiscoveryFunctions.checkCommandList() -> checks that the list of commands exist on the given Host.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.checkCommandList(${1:host}, ${2:command_list});$0" "checkCommandList(host, command_list) -> result": prefix: "checkCommandList" description: 'DiscoveryFunctions.checkCommandList() -> checks that the list of commands exist on the given Host.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "DiscoveryFunctions.checkCommandList(${1:host}, ${2:command_list});$0" "DiscoveryFunctions.getErrorRegexes(arg1, arg2) -> result": prefix: "DiscoveryFunctions.getErrorRegexes" description: 'returns a list of known regexes to parse errored command outputs' body: "// This is not implemented yet. Reffer to DiscoveryFunctions 1.7 docstrings" "getErrorRegexes(arg1, arg2) -> result": prefix: "getErrorRegexes" description: 'returns a list of known regexes to parse errored command outputs' body: "// This is not implemented yet. Reffer to DiscoveryFunctions 1.7 docstrings" # RDBMS OLD:: # // This is an old implementation, please use new (RDBMSFunctions) "OLD rdbms_functions.oracle_ora_file_parser(section_name, oracle_ora_file_content) -> section": prefix: "_rdbms_functions.oracle_ora_file_parser" description: 'OLD rdbms_functions.oracle_ora_file_parser -> function tries to obtain full section from Oracle listener.ora or tnsnames.ora file. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.oracleOraFileParser)\nrdbms_functions.oracle_ora_file_parser(${1:section_name}, ${2:oracle_ora_file_content});$0""" "OLD rdbms_functions.perform_rdbms_sis_search(related_sis_raw, rel_si_type, instance, port, db_name, extended) -> related_rdbms_sis": prefix: "_rdbms_functions.perform_rdbms_sis_search" description: 'OLD rdbms_functions.perform_rdbms_sis_search -> This internal function is used by related_rdbms_sis_search() and related_rdbms_sis_search_extended() and searches for specific RDBMS SI \"rel_si_type\" TYPE on \"rel_host_address\" host, which can be uniquely identified by attribute (depends on RDBMS Type) ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.perform_rdbms_sis_search(${1:related_sis_raw}, ${2:rel_si_type}, ${3:instance}, ${4:port}, ${5:db_name}, ${6:extended});$0""" "OLD rdbms_functions.related_rdbms_sis_search(host, rel_host_address, rel_si_type, instance, port, db_name, extended) -> related_rdbms_sis": prefix: "_rdbms_functions.related_rdbms_sis_search" description: 'OLD rdbms_functions.related_rdbms_sis_search -> Function searches for specific RDBMS SI \"rel_si_type\" TYPE on \"rel_host_address\" host. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.related_rdbms_sis_search(${1:host}, ${2:rel_host_address}, ${3:rel_si_type}, ${4:instance}, ${5:port}, ${6:db_name}, ${7:extended});$0""" "OLD rdbms_functions.related_rdbms_sis_search_extended(host, rel_host_address, rel_si_type, instance, port, db_name, extended) -> related_rdbms_sis": prefix: "_rdbms_functions.related_rdbms_sis_search_extended" description: 'OLD rdbms_functions.related_rdbms_sis_search_extended -> Function searches for specific RDBMS SI \"rel_si_type\" TYPE on \"rel_host_address\" host. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.related_rdbms_sis_search_extended(${1:host}, ${2:rel_host_address}, ${3:rel_si_type}, ${4:instance}, ${5:port}, ${6:db_name}, ${7:extended});$0""" "OLD rdbms_functions.oracle_net_service_name_search(host, net_service_name, tnsnames_file_full_location) -> related_oracle_si": prefix: "_rdbms_functions.oracle_net_service_name_search" description: 'OLD rdbms_functions.oracle_net_service_name_search -> Function returns Oracle Database SI which is end point for local \<net_service_name\>. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.oracleNetServiceNameSearch)\nrdbms_functions.oracle_net_service_name_search(${1:host}, ${2:net_service_name}, ${3:tnsnames_file_full_location});$0""" "OLD rdbms_functions.dsn_rdbms_servers(host,dsn_name) -> db_srvs": prefix: "_rdbms_functions.dsn_rdbms_servers" description: 'OLD rdbms_functions.dsn_rdbms_servers -> Function returns related RDBMS SI by its DSN (Data Source Name) value. For WINDOWS ONLY! ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.dsnRdbmsServers)\nrdbms_functions.dsn_rdbms_servers(${1:host}, ${2:dsn_name});$0""" "OLD rdbms_functions.parseJDBC(url) -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name": prefix: "_rdbms_functions.parseJDBC" description: 'OLD rdbms_functions.parseJDBC -> Parse a JDBC URL and extract the details ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.parseJDBC)\nrdbms_functions.parseJDBC(${1:url});$0""" "OLD rdbms_functions.jdbc_search(host,jdbc_url) -> db_srvs": prefix: "_rdbms_functions.jdbc_search" description: 'OLD rdbms_functions.jdbc_search -> Function returns related RDBMS SI by JDBC URL value. First it parses the JDBC URL(the function from j2eeinferredmodel module was taken as a basis), then it uses related_rdbms_sis_search or oracle_net_service_name_search function to find the related RDBMS SIs. Supported RDBMS: MSSQL, Oracle, DB2, MySQL, PostgreSQL, Ingres DB, Sybase ASE, Informix. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.jdbc_search(${1:host}, ${2:jdbc_url});$0""" "OLD rdbms_functions.find_db_server(host, server_address, port, si_type, db_details) -> server_nodes": prefix: "_rdbms_functions.find_db_server" description: 'OLD rdbms_functions.find_db_server -> Function that searches for the appropriate database server node based on the provided server details. ' body: """// WARNING: This is an old implementation, please use new (RDBMSFunctions.performRdbmsSisSearch)\nrdbms_functions.find_db_server(${1:host}, ${2:server_address}, ${3:port}, ${4:si_type}, ${5:db_details});$0""" # RDBMS NEW:: "RDBMSFunctions.oracleOraFileParser(section_name, oracle_ora_file_content) -> section": prefix: "RDBMSFunctions.oracleOraFileParser" description: 'obtains full section from Oracle listener.ora or tnsnames.ora files' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.oracleOraFileParser(${1:section_name}, ${2:oracle_ora_file_content}); // -> section$0" "oracleOraFileParser(section_name, oracle_ora_file_content) -> section": prefix: "oracleOraFileParser" description: 'obtains full section from Oracle listener.ora or tnsnames.ora files' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.oracleOraFileParser(${1:section_name}, ${2:oracle_ora_file_content}); // -> section$0" "RDBMSFunctions.performRdbmsSisSearch(related_sis_raw, rel_si_type, port, instance, db_name, ora_service_name, db2_copy_name) -> related_rdbms_nodes": prefix: "RDBMSFunctions.performRdbmsSisSearch" description: 'searches for the RDBMS Software by provided parameters' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ RDBMSFunctions.performRdbmsSisSearch(related_sis_raw = ${1:related_sis_raw}, rel_si_type = ${2:rel_si_type}, port = ${3:port}, instance = ${4:instance}, db_name = ${5:db_name}, ora_service_name = ${6:ora_service_name}, db2_copy_name = ${7:db2_copy_name}); // -> -> related_rdbms_nodes$0 """ "performRdbmsSisSearch(related_sis_raw, rel_si_type, port, instance, db_name, ora_service_name, db2_copy_name) -> related_rdbms_nodes": prefix: "performRdbmsSisSearch" description: 'searches for the RDBMS Software by provided parameters' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ RDBMSFunctions.performRdbmsSisSearch(related_sis_raw = ${1:related_sis_raw}, rel_si_type = ${2:rel_si_type}, port = ${3:port}, instance = ${4:instance}, db_name = ${5:db_name}, ora_service_name = ${6:ora_service_name}, db2_copy_name = ${7:db2_copy_name}); // -> -> related_rdbms_nodes$0 """ "RDBMSFunctions.oracleNetServiceNameSearch(host, net_service_name, tnsnames_file_full_location) -> ora_host, ora_sid, ora_service_name": prefix: "RDBMSFunctions.oracleNetServiceNameSearch" description: 'returns Oracle Database SI parameters by the provided Net Service Name' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ RDBMSFunctions.oracleNetServiceNameSearch(host = ${1:host}, net_service_name = ${2:net_service_name}, tnsnames_file_full_location = ${3:tnsnames_file_full_location}); // -> ora_host, ora_sid, ora_service_name$0 """ "oracleNetServiceNameSearch(host, net_service_name, tnsnames_file_full_location) -> ora_host, ora_sid, ora_service_name": prefix: "oracleNetServiceNameSearch" description: 'returns Oracle Database SI parameters by the provided Net Service Name' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ RDBMSFunctions.oracleNetServiceNameSearch(host = ${1:host}, net_service_name = ${2:net_service_name}, tnsnames_file_full_location = ${3:tnsnames_file_full_location}); // -> ora_host, ora_sid, ora_service_name$0 """ "RDBMSFunctions.dsnRdbmsServers(host,dsn_name) -> db_host, db_type, db_instance, ora_service_name, db_port, db_name": prefix: "RDBMSFunctions.dsnRdbmsServers" description: 'determines RDBMS Server details by the provided DSN' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.dsnRdbmsServers(host, ${1:dsn_name}); // -> db_host, db_type, db_instance, ora_service_name, db_port, db_name$0" "dsnRdbmsServers(host,dsn_name) -> db_host, db_type, db_instance, ora_service_name, db_port, db_name": prefix: "dsnRdbmsServers" description: 'determines RDBMS Server details by the provided DSN' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.dsnRdbmsServers(host, ${1:dsn_name}); // -> db_host, db_type, db_instance, ora_service_name, db_port, db_name$0" "RDBMSFunctions.parseJDBC(url) -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name": prefix: "RDBMSFunctions.parseJDBC" description: 'extracts RDBMS details by the provided JDBC URL' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.parseJDBC(${1:url}); // -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name$0" "parseJDBC(url) -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name": prefix: "parseJDBC" description: 'extracts RDBMS details by the provided JDBC URL' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "RDBMSFunctions.parseJDBC(${1:url}); // -> db_type, db_host, db_port, db_name, oracle_tns_alias, oracle_service_name$0" # SEARCH FUNCTIONS:: "SearchFunctions.getNodeIp(host, rel_host_address_domain) -> node_ip": prefix: "SearchFunctions.getNodeIp" description: 'converts alphanumeric Host address into IP address' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getNodeIp(host, ${1:rel_host_address_domain}); // -> node_ip$0" "getNodeIp(host, rel_host_address_domain) -> node_ip": prefix: "getNodeIp" description: 'converts alphanumeric Host address into IP address' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getNodeIp(host, ${1:rel_host_address_domain}); // -> node_ip$0" "SearchFunctions.getHostingNodes(host, node_address, balancer_port := none) -> hosting_nodes, nodes_type": prefix: "SearchFunctions.getHostingNodes" description: 'searches for Hosting Nodes' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getHostingNodes(host, ${1:node_address}, balancer_port := ${2:none}); // -> hosting_nodes, nodes_type$0" "getHostingNodes(host, node_address, balancer_port := none) -> hosting_nodes, nodes_type": prefix: "getHostingNodes" description: 'searches for Hosting Nodes' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getHostingNodes(host, ${1:node_address}, balancer_port := ${2:none}); // -> hosting_nodes, nodes_type$0" # GET SOFTWARE NODES: "SearchFunctions.getSoftwareNodes(evrything) -> software_nodes": prefix: "SearchFunctions.getSoftwareNodes" description: 'searches for software(SoftwareInstance, DatabaseDetail, SoftwareComponent or LoadBalancerService)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, node_address := ${1:none}, software_type := ${2:none}, balancer_port := ${3:none}, port := ${4:none}, instance := ${5:none}, listen_tcp_socket := ${6:none}, server_name := ${7:none}, installed_product := ${8:none}, db_name := ${9:none}, net_service_name := ${10:none}, ora_service_name := ${11:none}, db2_copy_name := ${12:none}, dsn_name := ${13:none}, jdbc_url := ${14:none}, tnsnames_file_location := ${15:none}, get_remote_nodes_only := ${16:none} ); // -> software_nodes $0 """ "getSoftwareNodes(evrything) -> software_nodes": prefix: "getSoftwareNodes" description: 'searches for software(SoftwareInstance, DatabaseDetail, SoftwareComponent or LoadBalancerService)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, node_address := ${1:none}, software_type := ${2:none}, balancer_port := ${3:none}, port := ${4:none}, instance := ${5:none}, listen_tcp_socket := ${6:none}, server_name := ${7:none}, installed_product := ${8:none}, db_name := ${9:none}, net_service_name := ${10:none}, ora_service_name := ${11:none}, db2_copy_name := ${12:none}, dsn_name := ${13:none}, jdbc_url := ${14:none}, tnsnames_file_location := ${15:none}, get_remote_nodes_only := ${16:none} ); // -> software_nodes $0 """ "SearchFunctions.getSI(related_node, si_types_raw) -> related_si": prefix: "SearchFunctions.getSI" description: 'returns the SI Node which is running behind LoadBalancer or hosts DatabaseDetail Node' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getSI(${1:related_node}, ${2:si_types_raw}); // -> related_si$0" "getSI(related_node, si_types_raw) -> related_si": prefix: "getSI" description: 'returns the SI Node which is running behind LoadBalancer or hosts DatabaseDetail Node' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.getSI(${1:related_node}, ${2:si_types_raw}); // -> related_si$0" "SearchFunctions.relatedSisSearchOnMultipleHosts(host, rel_host_addresses, rel_si_type) -> related_sis": prefix: "SearchFunctions.relatedSisSearchOnMultipleHosts" description: 'searches for software on multiple Hosts' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.relatedSisSearchOnMultipleHosts(host, rel_host_addresses = ${1:rel_host_addresses}, rel_si_type = ${2:rel_si_type}); // -> related_sis$0" "relatedSisSearchOnMultipleHosts(host, rel_host_addresses, rel_si_type) -> related_sis": prefix: "relatedSisSearchOnMultipleHosts" description: 'searches for software on multiple Hosts' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.relatedSisSearchOnMultipleHosts(host, rel_host_addresses = ${1:rel_host_addresses}, rel_si_type = ${2:rel_si_type}); // -> related_sis$0" "SearchFunctions.identifyHostWithUuid(uuid) -> searched_host": prefix: "SearchFunctions.identifyHostWithUuid" description: 'searches for the Host with the specific UUID' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.identifyHostWithUuid(${1:uuid}); // -> searched_host$0" "identifyHostWithUuid(uuid) -> searched_host": prefix: "identifyHostWithUuid" description: 'searches for the Host with the specific UUID' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: "SearchFunctions.identifyHostWithUuid(${1:uuid}); // -> searched_host$0" # Templates: # GET SOFTWARE NODES JDBC: "SearchFunctions.getSoftwareNodes(host, jdbc_url)": prefix: "_jdbc_url_SearchFunctions.getSoftwareNodes" description: 'Template of common SearchFunctions.getSoftwareNodes to find database via jdbc url.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, jdbc_url := ${2:jdbc_url}); $0 """ # GET SOFTWARE NODES CUSTOM: "SearchFunctions.getSoftwareNodes(host, node_address, software_type, db_name)": prefix: "_db_host_type_SearchFunctions.getSoftwareNodes" description: 'Template of common SearchFunctions.getSoftwareNodes to find related database.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, node_address := ${1:db_host}, software_type := ${2:db_type}, db_name := ${3:db_name} ); $0 """ "SearchFunctions.getSoftwareNodes(host, node_address, software_type, port, instance, db_name)": prefix: "_db_host_port_SearchFunctions.getSoftwareNodes" description: 'Template of common SearchFunctions.getSoftwareNodes to find related database by node_address, software_type, port, instance, db_name.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/User+defined+functions' body: """ SearchFunctions.getSoftwareNodes(host, node_address := ${1:db_host}, software_type := ${2:db_type}, port := ${3:port}, instance := ${4:instance}, db_name := ${5:db_name} ); $0 """ # REGEX USUAL USAGE:: "full ver (\\\\d+(?:\\\\.\\\\d+)*) greedy": prefix: "_regex_full_ver" description: 'Template regex expression to catch full version.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(\\\\d+(?:\\\\.\\\\d+)*)$0" "full ver ^(\\\\d+(?:\\\\.\\\\d+)?) zero or one": prefix: "_regex_full_ver_" description: 'Template regex expression to catch full version from start if string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "^(\\\\d+(?:\\\\.\\\\d+)?)$0" "product ver (\\\\d+(?:\\\\.\\\\d+)?) zero or one": prefix: "_regex_product_ver" description: 'Template regex expression to catch product version.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(\\\\d+(?:\\\\.\\\\d+)?)$0" "bjavaw (?i)\\bjavaw?(?:\\\\.exe)\\$": prefix: "_regex_bjavaw" description: 'Template regex expression to catch bjavaw cmd.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(?i)\\bjavaw?(?:\\\\.exe)\\$$0" "bjava (?i)\\bjava(?:\\\\.exe)?\\$": prefix: "_regex_bjava" description: 'Template regex expression to catch bjava cmd.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(?i)\\bjava(?:\\\\.exe)?\\$$0" "java (?i)^(\\w:.*\\)Java\\": prefix: "_regex_java" description: 'Template regex expression to catch java cmd.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(?i)^(\\w:.*\\)Java\\$0" "java (/\\\\.+/)java/": prefix: "_regex_java" description: 'Template regex expression to catch java cmd.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "^(/\\\\.+/)java/$0" "ipv4 (\\\\d+(?:\\\\.\\\\d+){3})": prefix: "_regex_ipv4" description: 'Template regex expression to catch ipv4.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(\\\\d+(?:\\\\.\\\\d+){3})$0" "ver ^(\\\\d+)": prefix: "_regex_ver" description: 'Template regex expression to catch simple decimals.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "^(\\\\d+)$0" "ver ^\\\\d+\\$": prefix: "_regex_ver" description: 'Template regex expression to catch simple decimals.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "^\\\\d+\\$$0" "Win_path catch path with spaces": prefix: "_regex_Win_path" description: 'Template regex expression to catch path with spaces in windows.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "(?i)\\\"([^\"]+)PATH_TO_FILE_LIB\\\"$0" "Win_path_alt catch path with spaces in windows, alternative": prefix: "_regex_Win_path_alt" description: 'Template regex expression to catch path with spaces in windows, alternative.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "([^\"]+)PATH_TO_FILE_CONF$0" # INFERRENCE: https://docs.bmc.com/docs/display/DISCO111/Inference+functions "inference.associate(inferred_node, associate)": prefix: "inference.associate" description: 'Create associate inference relationship(s) from the specified node(s) to the inferred node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.associate' body: "inference.associate(${1:inferred_node}, ${2:associate});$0" "inference.contributor(inferred_node, contributor, contributes)": prefix: "inference.contributor" description: 'Create contributor inference relationship(s) from the specified node(s) to the inferred node, for attribute names specified in the contributes list.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.contributor' body: "inference.contributor(${1:inferred_node}, ${2:contributor}, ${3:contributes});$0" "inference.primary(inferred_node, primary)": prefix: "inference.primary" description: 'Create primary inference relationship(s) from the specified node(s) to the inferred node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.primary' body: "inference.primary(${1:inferred_node}, ${2:primary});$0" "inference.relation(inferred_relationship, source)": prefix: "inference.relation" description: 'Create relation inference relationship(s) from the specified node(s) to the inferred relationship.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.relation' body: "inference.relation(${1:inferred_relationship}, ${2:source});$0" "inference.withdrawal(inferred_node, evidence, withdrawn)": prefix: "inference.withdrawal" description: 'Create withdrawal inference relationship(s) from the specified node(s) to the inferred node, indicating the withdrawal of the withdrawn attribute name.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.withdrawal' body: "inference.withdrawal(${1:inferred_node}, ${2:evidence}, ${3:withdrawn});$0" "inference.destruction(destroyed_node, source)": prefix: "inference.destruction" description: 'When destroying a node, indicate that the source node was responsible for its destruction.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/inference.destruction' body: "inference.destruction(${1:destroyed_node}, ${2:source});$0" # https://docs.bmc.com/docs/display/DISCO111/System+functions "system.getOption(option_name)": prefix: "system.getOption" description: 'Takes the name of a BMC Discovery system option and returns the value.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: "system.getOption(${1:option_name});$0" "system.cmdbSync(nodes)": prefix: "system.cmdbSync" description: 'Addssystem.cmdbSync the given root node or list of root nodes to the CMDB synchronization queue for all sync connections where continuous synchronization is enabled.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/' body: "system.cmdbSync(${1:nodes});$0" # MODEL FUNCTIONS:: "model.addContainment(container, containees)": prefix: "model.addContainment" description: 'Adds the containees to the container by creating suitable relationships between the nodes. containees can be a single node, or a list of nodes, for example: [node1, node2].' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.addContainment' body: "model.addContainment(${1:si_node}, ${2:software_components});$0" "model.setContainment(container, containees)": prefix: "model.setContainment" description: """Equivalent to addContainment, except that at the end of the pattern body, any relationships to contained nodes that have not been confirmed by setContainment or addContainment calls are removed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.setContainment' body: "model.setContainment(${1:cluster_si_node}, ${2:related_sis});$0" "model.destroy(node)": prefix: "model.destroy" description: 'Destroy the specified node or relationship in the model. (Not usually used in pattern bodies, but in removal sections.)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.destroy' body: "model.destroy(${1:dummy});$0" "model.withdraw(node, attribute)": prefix: "model.withdraw" description: 'Removes the named attribute from the node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.withdraw' body: "model.withdraw(si_node, \"${1:detail}\");$0" "model.setRemovalGroup(node, [name])": prefix: "model.setRemovalGroup" description: 'Add the specified node or nodes to a named removal group. The purpose of this function is to identify a group of nodes.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.setRemovalGroup' body: "model.setRemovalGroup(${1:cluster_si}, \"${2:Dummy_Server_Cluster}\");$0" "model.anchorRemovalGroup(node, [name])": prefix: "model.anchorRemovalGroup" description: 'Specify an anchor node for a named removal group. If a group name is not specified the default name group is used.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.anchorRemovalGroup' body: "model.anchorRemovalGroup(${1:si}, \"${2:license_dts}\");$0" "model.suppressRemovalGroup([name])": prefix: "model.suppressRemovalGroup" description: 'Suppress removal of the named removal group. If a group name is not specified the default name group is used. ' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.suppressRemovalGroup' body: "model.suppressRemovalGroup(\"%${1:detail_type}%\");$0" "model.host(node)": prefix: "model.host" description: """Returns the Host node corresponding to the given node. The given node can be any directly discovered data node, or a Software Instance or Business Application Instance. If more than one Host is related to the given node (for example a Business Application Instance spread across multiple Hosts), an arbitrary one of the Hosts is returned.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.host' body: "model.host(${1:process});$0" "model.hosts(node)": prefix: "model.hosts" description: """Returns a list of all the Host nodes corresponding to the given node. As with model.host, the given node can be any directly discovered data node or a Software Instance or Business Application Instance.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.hosts' body: "model.hosts(${1:model_sis});$0" "model.findPackages(node, regexes)": prefix: "model.findPackages" description: """Traverses from the node, which must be a Host or a directly discovered data node, and returns a set of all Package nodes that have names matching the provided list of regular expressions.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.findPackages' body: "model.findPackages(host, [regex \"${1:}\"]);$0" "model.addDisplayAttribute(node, value)": prefix: "model.addDisplayAttribute" description: 'Adds a named attribute, or a list of named attributes to the additional attributes displayed in a node view. Added attributes can be removed using model.removeDisplayAttribute.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO113/model.addDisplayAttribute' body: "model.addDisplayAttribute(${1:node}, ${2:value});$0" "model.removeDisplayAttribute(node, value)": prefix: "model.removeDisplayAttribute" description: 'Removes a named attribute, or a list of named attributes from the additional attributes displayed in a node view. Additional attributes are added using the model.addDisplayAttribute function.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO113/model.removeDisplayAttribute' body: "model.removeDisplayAttribute(${1:node}, ${2:value});$0" "model.kind(node)": prefix: "model.kind" description: 'Returns the node kind corresponding to the given node.The given node can be any node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/model.kind' body: "model.kind(${1:hosting_node});$0" # REL: "model.rel.Communication(Server, Client)": prefix: "rel_Communication" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Communication(Server := ${1:related_sis}, Client := ${2:si_node});$0" "model.rel.Containment(Contained, Container)": prefix: "rel_Containment" description: description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Containment(Contained := ${1:cluster_member_node}, Container := ${2:cluster});$0" "model.rel.Dependency(Dependant, DependedUpon)": prefix: "rel_Dependency" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Dependency(Dependant := ${1:si_node}, DependedUpon := ${2:dep_si});$0" "model.rel.Detail(ElementWithDetail, Detail)": prefix: "rel_Detail" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Detail(ElementWithDetail := ${1:si_node}, Detail := ${2:details});$0" "model.rel.HostContainment(HostContainer, ContainedHost)": prefix: "rel_HostContainment" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.HostContainment(HostContainer := ${1:si_node}, ContainedHost := ${2:host});$0" "model.rel.HostedFile(HostedFile, Host)": prefix: "rel_HostedFile" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.HostedFile(HostedFile := ${1:file}, Host := ${2:host});$0" "model.rel.HostedSoftware(Host, RunningSoftware)": prefix: "rel_HostedSoftware" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.HostedSoftware(Host := ${1:host}, RunningSoftware := ${2:si_node});$0" "model.rel.Management(Manager, ManagedElement)": prefix: "rel_Management" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.Management(Manager := ${1:manager_si}, ManagedElement := ${2:si_node});$0" "model.rel.RelatedFile(ElementUsingFile, File)": prefix: "rel_RelatedFile" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.RelatedFile(ElementUsingFile := ${1:si_node}, File := ${2:file});$0" "model.rel.SoftwareService(ServiceProvider, Service)": prefix: "rel_SoftwareService" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.SoftwareService(ServiceProvider := ${1:si_node}, Service := ${2:cluster});$0" "model.rel.SoftwareContainment(SoftwareContainer, ContainedSoftware)": prefix: "rel_SoftwareContainment" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.SoftwareContainment(SoftwareContainer := ${1:si_node}, ContainedSoftware := ${2:sc_lst});$0" "model.rel.StorageUse(Consumer, Provider)": prefix: "rel_StorageUse" description: """Where additional relationships are required, they can be created explicitly. For each relationship defined in the taxonomy, a corresponding function is also defined in the model.rel scope.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Modelrelationshipexistencefunctions' body: "model.rel.StorageUse(Consumer := ${1:virtual_disk}, Provider := ${2:dest_disks});$0" # UNIQUE REL: "model.uniquerel.Communication(Server, Client)": prefix: "uniquerel_Communication" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Communication(Server := ${1:related_sis}, Client := ${2:si_node});$0" "model.uniquerel.Containment(Contained, Container)": prefix: "uniquerel_Containment" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Containment(Contained := ${1:cluster_member_node}, Container := ${2:cluster});$0" "model.uniquerel.Dependency(Dependant, DependedUpon)": prefix: "uniquerel_Dependency" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Dependency(Dependant := ${1:si_node}, DependedUpon := ${2:dep_si});$0" "model.uniquerel.Detail(ElementWithDetail, Detail)": prefix: "uniquerel_Detail" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Detail(ElementWithDetail := ${1:si_node}, Detail := ${2:details});$0" "model.uniquerel.HostContainment(HostContainer, ContainedHost)": prefix: "uniquerel_HostContainment" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.HostContainment(HostContainer := ${1:si_node}, ContainedHost := ${2:host});$0" "model.uniquerel.HostedFile(HostedFile, Host)": prefix: "uniquerel_HostedFile" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.HostedFile(HostedFile := ${1:file}, Host := ${2:host});$0" "model.uniquerel.HostedSoftware(Host, RunningSoftware)": prefix: "uniquerel_HostedSoftware" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.HostedSoftware(Host := ${1:host}, RunningSoftware := ${2:si_node});$0" "model.uniquerel.HostedService(ServiceHost, RunningService)": prefix: "uniquerel_HostedService" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.HostedService(ServiceHost := ${1:cluster}, RunningService := ${2:cluster_service_node});$0" "model.uniquerel.Management(Manager, ManagedElement)": prefix: "uniquerel_Management" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.Management(Manager := ${1:manager_si}, ManagedElement := ${2:si_node});$0" "model.uniquerel.RelatedFile(ElementUsingFile, File)": prefix: "uniquerel_RelatedFile" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.RelatedFile(ElementUsingFile := ${1:si_node}, File := ${2:file});$0" "model.uniquerel.SoftwareService(ServiceProvider, Service)": prefix: "uniquerel_SoftwareService" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.SoftwareService(ServiceProvider := ${1:si_node}, Service := ${2:cluster});$0" "model.uniquerel.SoftwareContainment(SoftwareContainer, ContainedSoftware)": prefix: "uniquerel_SoftwareContainment" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.SoftwareContainment(SoftwareContainer := ${1:si_node}, ContainedSoftware := ${2:sc_lst});$0" "model.uniquerel.StorageUse(Consumer, Provider)": prefix: "uniquerel_StorageUse" description: """It takes the same form as the equivalent model.rel function, but its behaviour is different - If a relationship already exists between the source and destination, its attributes are updated. - If a relationship does not exist from the source to the destination it is created. - All other matching relationships from the source to other destinations are destroyed.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Model+functions#Modelfunctions-Uniquerelationshipfunctions' body: "model.uniquerel.StorageUse(Consumer := ${1:virtual_disk}, Provider := ${2:dest_disks});$0" # Customization:: "SoftwareInstance Short": prefix: "SoftwareInstance_Short_" body: """ model.SoftwareInstance(key := key, $0name := name, $0short_name := short_name );$0 """ "SoftwareInstance Key": prefix: "SoftwareInstance_Key_" body: """ model.SoftwareInstance(key := \"%port%/%key_si_type%/%host.key%\", $0 name := name, $0 short_name := short_name, $0 version := full_version, $0 product_version := product_version, $0 port := port, $0 listening_ports := listening_ports, $0 type := si_type $0 ); $0 """ "SoftwareInstance Key_group": prefix: "SoftwareInstance_Key_group_" body: """ model.SoftwareInstance(key := \"%port%/%key_si_type%/%host.key%\", $0 name := name, $0 short_name := short_name, $0 version := full_version, $0 product_version := product_version, $0 port := port, $0 listening_ports := listening_ports, $0 type := si_type $0 ); $0 """ "SoftwareInstance Detailed": prefix: "SoftwareInstance_Detailed_" body: """ model.SoftwareInstance(key := \"%product_version%/%si_type%/%host.key%\", $0 name := name, $0 short_name := short_name, $0 version := full_version, $0 product_version := product_version, $0 publisher := publisher, $0 product := product, $0 type := si_type $0 ); $0 """ # Extra: "Communication type model.uniquerel.": prefix: "Communication_type_model.uniquerel._" body: "model.uniquerel.Communication(Server := ${1:related_sis}, Client := ${2:si_node}, type := \"${3:%type%}\");$0" # NUMBER FUNCTIONS:: "number.toChar(number)": prefix: "number.toChar" description: 'Converts the integer number in the ASCII range to a character.If the value is outside the ASCII range, it returns none.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/number.toChar' body: "number.toChar(${1:number});$0" "number.toText(number)": prefix: "number.toText" description: 'Converts the integer number to a text form' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/number.toText' body: "number.toText(${1:number});$0" "number.range(number)": prefix: "number.range" description: 'Generate a list containing 0 to number - 1. If number is less than 1 the list will be empty.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/number.range' body: "number.range(${1:number});$0" # TEXT FUNCTIONS:: "text.lower(string)": prefix: "text.lower" description: 'Returns the lower-cased version of the string argument.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.lower' body: "text.lower(string)$0" "text.upper(string)": prefix: "text.upper" description: 'Returns the upper-cased version of the string argument.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.upper' body: "text.upper(string)$0" "text.toNumber(string [, base ] )": prefix: "text.toNumber" description: """Converts its string argument into a number. By default, the number is treated as a base 10 value; if the optional base is provided, the number is treated as being in the specified base. Bases from 2 to 36 are supported. Bases larger than 10 use the letters a through z to represent digits.""" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.toNumber' body: "text.toNumber(port);$0" # REPLACE: "text.replace(string, old, new)": prefix: "text.replace" description: 'Returns a modified version of the string formed by replacing all occurrences of the string old with new.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.replace' body: "text.replace(${1:where_string}, \"${2:from_char}\", \"${3:to_char}\");$0" "text.replace() -> replace , to .": prefix: "_text.replace_col" description: 'Template to replace common characters.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.replace' body: "text.replace(${1:string}, \",\", \".\");$0" "text.replace() -> replace - to .": prefix: "_text.replace_min" description: 'Template to replace common characters.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.replace' body: "text.replace(${1:string}, \"-\", \".\");$0" "text.replace() -> replace \\\\ to \\\\\\\\": prefix: "_text.replace_sla" description: 'Template to replace common characters.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.replace' body: "text.replace(${1:string}, \"\\\\\\\", \"\\\\\\\\\\\\\\\");$0" # STRING OPTIONS: "text.join(list, \"separator\")": prefix: "text.join" description: 'Returns a string containing all items in a list of strings joined with the specified separator.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.join' body: "text.join(${1:list}, \"${2:separator}\");$0" "text.split(string, [separator])": prefix: "text.split" description: 'Returns a list consisting of portions of the string split according to the separator string, where specified.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.split' body: "text.split(${1:string}, \"${2:separator}\");$0" "text.strip(string [, characters ] )": prefix: "text.strip" description: 'Strips unwanted characters from the start and end of the given string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.strip' body: "text.strip(${1:string});$0" "text.leftStrip(string [, characters ] )": prefix: "text.leftStrip" description: 'Equivalent to text.strip, but only strips from the left side of the string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.leftStrip' body: "text.leftStrip(${1:string} [, ${2:characters} ] );$0" "text.rightStrip(string [, characters ] )": prefix: "text.rightStrip" description: 'Equivalent to text.strip, but only strips from the right side of the string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.rightStrip' body: "text.rightStrip(${1:string} [, ${2:characters} ] );$0" "text.hash(string)": prefix: "text.hash" description: 'Returns a hashed form of the string, generated with the MD5 hash algorithm.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.hash' body: "text.hash(${1:string});$0" "text.ordinal(string)": prefix: "text.ordinal" description: 'Returns the ordinal value of the string argument. The string must be one character in length.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/text.ordinal' body: "text.ordinal(${1:string});$0" # LIST: "append list": prefix: "append_list_" body: "list.append(${1:the_list}, ${2:string});$0" # TRAVERCE: "search(in da ::DiscoveryResult:ProcessList \#DiscoveredProcess where pid": prefix: "_trav_rel_proc_parent" description: 'search(in da traverse DiscoveryAccess:DiscoveryAccessResult:DiscoveryResult:ProcessList traverse List:List:Member:DiscoveredProcess where pid' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: """ rel_services := search(in ${1:da_node} traverse DiscoveryAccess:DiscoveryAccessResult:DiscoveryResult:ProcessList $0traverse List:List:Member:DiscoveredProcess where pid = %pproc_pid%);$0 """ "search(in si ::SoftwareContainer:SoftwareInstance": prefix: "_trav_ContainedSoftware::SoftwareInstance" description: 'search(in si traverse ContainedSoftware:SoftwareContainment:SoftwareContainer:SoftwareInstance where type and key <> %key% step in SoftwareContainer:SoftwareContainment where \#:ContainedSoftware:SoftwareInstance.key = si.key)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: """ obsolete_links := search(in ${1:related_si} traverse ContainedSoftware:SoftwareContainment:SoftwareContainer:SoftwareInstance where type = %${2:si_type}% and key <> %key% step in SoftwareContainer:SoftwareContainment where #:ContainedSoftware:SoftwareInstance.key = %${3:related_si}.key%);$0 """ "search(in si ::DiscoveredProcess)": prefix: "_trav_InferredElement::DiscoveredProcess" description: 'search(in si traverse InferredElement:Inference:Primary:DiscoveredProcess)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "procs := search(in si traverse InferredElement:Inference:Primary:DiscoveredProcess);$0" "search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where type)": prefix: "_trav_Host:HostedSoftware::SoftwareInstance" description: 'search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where type)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: """ some_si := search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where ${1:type} = \"${2:type_here}\");$0 """ "search(in si ::Communication:Server:SoftwareInstance where type": prefix: "_trav_Client::SoftwareInstance" description: 'search(in si traverse Client:Communication:Server:SoftwareInstance where type = smth)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "srv_si_list := search(in ${1:related_si} traverse Client:Communication:Server:SoftwareInstance where type = \"${2:type_here}\");$0" "search(in si ::Client:SoftwareInstance where type": prefix: "_trav_Server::SoftwareInstance" description: 'search(in si traverse Server:Communication:Client:SoftwareInstance where type = smth)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "client_si_list := search(in ${1:related_si} traverse Server:Communication:Client:SoftwareInstance where type = \"${2:type_here}\");$0" "search(in si ::SoftwareContainer:BusinessApplicationInstance where type": prefix: "_trav_ContainedSoftware::BusinessApplicationInstance" description: 'search(in si traverse ContainedSoftware:SoftwareContainment:SoftwareContainer:BusinessApplicationInstance where type = si_type)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "bai_candidates := search(in ${1:related_si} traverse ContainedSoftware:SoftwareContainment:SoftwareContainer:BusinessApplicationInstance where type = \"%${2:si_type}%\");$0" "search(in host ::SoftwareInstance where type ::Detail:DatabaseDetail": prefix: "_trav_Host::SoftwareInstance" description: "search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where type = smth traverse ElementWithDetail:Detail:Detail:DatabaseDetail where instance has subword subword)" descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "db2_si := search(in host traverse Host:HostedSoftware:RunningSoftware:SoftwareInstance where type = \"${1:type_here}\" traverse ElementWithDetail:Detail:Detail:DatabaseDetail where instance has subword '%${2:subword}%');$0" "search(in si ::Detail:Detail:Detail where type": prefix: "_trav_ElementWithDetail::Detail" description: 'search(in si traverse ElementWithDetail:Detail:Detail:Detail where type = smth)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "existing_dts := search(in si traverse ElementWithDetail:Detail:Detail:Detail where ${1:type} = \"${2:type_here}\");$0" "search(in si ::DependedUpon:SoftwareInstance": prefix: "_trav_Dependant::SoftwareInstance" description: 'search(in si traverse Dependant:Dependency:DependedUpon:SoftwareInstance)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "mains_si := search(in ${1:related_si} traverse Dependant:Dependency:DependedUpon:SoftwareInstance);$0" "search(in si ::Communication:Server:SoftwareInstance": prefix: "_trav_Client::Server:SoftwareInstance" description: 'search(in si traverse Client:Communication:Server:SoftwareInstance)' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/Traversals' body: "main_db_sis := search(in ${1:related_si} traverse Client:Communication:Server:SoftwareInstance);$0" # OTHER - DIFFERENT: # LOG USUAL: "log.debug(\"message\")": prefix: "log.debug" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.debug' body: "log.debug(\"${1:message}\");$0" "log.info(\"message\")": prefix: "log.info" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.info' body: "log.info(\"${1:message}\");$0" "log.warn(\"message\")": prefix: "log.warn" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.warn' body: "log.warn(\"${1:message}\");$0" "log.error(\"message\")": prefix: "log.error" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.error' body: "log.error(\"${1:message}\");$0" "log.critical(\"message\")": prefix: "log.critical" description: 'Log the given message with a debug level message. The log messages that are output automatically include the name of the pattern performing the log action.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/log.critical' body: "log.critical(\"${1:message}\");$0" # LOG CUSTOM: "_debug simple": prefix: "_debug_simple_" body: "log.debug(\"DEBUG_RUN: -----------> ${1:message} on line:\");$0" "_warn simple": prefix: "_warn_simple_" body: "log.warn(\"DEBUG_RUN: -----------> ${1:message} on line:\");$0" "_debug %variable%": prefix: "_debug_%variable%_" body: "log.debug(\"DEBUG_RUN: -----------> ${1:message} %${2:variable}% - ${4:message} on line:\");$0" "_warn %variable%": prefix: "_warn_%variable%_" body: "log.warn (\"DEBUG_RUN: -----------> ${1:message} %${2:variable}% - ${4:message} on line:\");$0" "_debug %node.attrs%": prefix: "_debug_%node.attrs%_" body: "log.debug(\"DEBUG_RUN: -----------> ${1:message} %${2:host}.${3:name}% - ${4:message} on line:\");$0" "_debug %node.attrs% Exec": prefix: "_debug_%node.attrs%_Exec_" body: """ delta_time_tics := time.toTicks(time.current()) - time.toTicks(start_time); log\\\\.debug(\"DEBUG_RUN: -----------> ${1:message} %${2:host}.${3:name}% - ${4:message} on line: Execution time:\" + number.toText(delta_time_tics/10000) + \"ms\");$0 """ # LOG SI: "_info log SI": prefix: "_info_log_SI_" body: "log.info(\"%host.name%: SI created for %${1:si_type}%\");$0" # EXTRACTIONS REGEX: "regex.extract(string, expression [, substitution] [, no_match])": prefix: "regex.extract" description: 'Returns the result of extracting the regular expression from the string, optionally with a substitution expression and a specified result if no match is found. Returns an empty string, or the string specified in no_match if the expression does not match. ' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extract(${1:string}, ${2:expression}, raw '\\\\1', no_match := '${3:NoMatch}');$0" "regex.extractAll(string, pattern)": prefix: "regex.extractAll" description: 'Returns a list containing all the non-overlapping matches of the pattern in the string. If the pattern contains more than one group, returns a list of lists containing the groups in order.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extractAll(${1:string}, ${2:pattern});$0" "regex.extract(variable, regex regex_raw, raw '\\\\1')": prefix: "regex.extract_Var" description: 'Tamplate for regex - extracting from: variable with some content in it.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extract(${1:variable}, regex \"${2:regex_raw}\", raw '\\\\1');$0" "regex.extract(node.attrs, regex regex_raw, raw '\\\\1')": prefix: "regex.extract_node.attrs" description: 'Tamplate for regex - extracting from: node with attribues.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extract(${1:node}.${2:attrs}, regex \"${3:regex_raw}\", raw '\\\\1');$0" "regex.extract(variable, regex regex_raw, raw '\\\\1', raw '\\\\2)": prefix: "regex.extract_raw_1,2" description: 'Tamplate for regex - extracting from: variable with two groups to check.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/regex.extract' body: "regex.extract(${1:variable}, regex \"${2:regex_raw}\", raw '\\\\${3:1}', raw '\\\\${4:2}');$0" # EXTRACTIONS Xpath: "xpath.evaluate(string, expression)": prefix: "xpath.evaluate" description: 'Returns the result of evaluating the xpath expression against the XML string. Returns a list of strings containing the selected values. The result is always a list, even if the expression is guaranteed to always return just one result.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/xpath.evaluate' body: "xpath.evaluate(${1:some_file_path}, \"${2:xpath_string}\");$0" "xpath.openDocument(string)": prefix: "xpath.openDocument" description: 'Returns the DOM object resulting from parsing the XML string. The DOM object returned is suitable for passing to xpath.evaluate.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/xpath.openDocument' body: "xpath.openDocument(${1:some_file_path});$0" "xpath.closeDocument(DOM object)": prefix: "xpath.closeDocument" description: 'Closes the DOM object resulting from xpath.openDocument.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/xpath.closeDocument' body: "xpath.closeDocument(${1:some_file_path});$0" # Table functions: "table( [ parameters ] )": prefix: "table" description: 'Creates a new table.With no parameters, creates an empty table. If parameters are given, initializes the table with items where the keys are the parameter names and the values are the parameter values.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/table' body: "table();$0" "table.remove(table, key)": prefix: "table.remove" description: 'Removes the specified key from the specified table.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/table.remove' body: "table.remove(${1:table}, ${2:key});$0" # CONTAINERS: "related.detailContainer(node)": prefix: "related.detailContainer" description: 'Returns the Software Component, Software Instance, or Business Application Instance node containing the given node.The given node can be a Detail or DatabaseDetail. If no single container node can be found None is returned.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/related.detailContainer' body: "related.detailContainer(${1:node});$0" "related.hostingNode( [\"fallback_kind\"], attributes...)": prefix: "related.hostingNode" description: 'Returns a Host or Cluster node that is associated with the node that triggered the pattern.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/related.hostingNode' body: "related.hostingNode(\"${1:Cluster}\", type := \"${2:SQL Server}\", properties := ${3:required_properties});$0" "related.host(node)": prefix: "related.host" description: 'Returns the Host node corresponding to the given node.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/related.host' body: "related.host(${1:node});$0" # https://docs.bmc.com/docs/display/DISCO111/Email+functions "mail.send(recipients, subject, message)": prefix: "mail.send" description: 'Sends an email. recipients is a single string containing an email address, or a list of email address strings; subject is the subject line to use in the email; message is the message contents.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/mail.send' body: "mail.send(${1:recipients}, ${2:subject}, ${3:message});$0" # https://docs.bmc.com/docs/display/DISCO111/Time+functions "time.current()": prefix: "time.current" description: 'Returns an internal datetime object representing the current UTC time.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.current' body: "time.current();$0" "time.delta(days, hours, minutes, seconds)": prefix: "time.delta" description: 'Creates a time delta that can be added to or subtracted from a time represented by an internal datetime object. ' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.delta' body: "time.delta(${1:days}, ${2:hours}, ${3:minutes}, ${4:seconds});$0" "time.parseLocal(string)": prefix: "time.parseLocal" description: 'Converts a string representing a local time into an internal UTC datetime object. If no time zone is present in the string it will use the time zone of the appliance.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.parseLocal' body: "time.parseLocal(${1:string});$0" "time.parseUTC(string)": prefix: "time.parseUTC" description: 'Take a UTC time string and converts it into an internal datetime object. It is not adjusted for timezones or daylight saving time. ' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.parseUTC' body: "time.parseUTC(${1:string});$0" "time.formatLocal(datetime [, format ])": prefix: "time.formatLocal" description: 'Formats an internal datetime object into a human-readable string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.formatLocal' body: "time.formatUTC(${1:lastRebootedDate}, raw \"%m/%d/%Y %H:%M:%S\");$0" "time.formatUTC(datetime [, format ])": prefix: "time.formatUTC" description: 'Formats an internal datetime object into a human-readable string.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.formatUTC' body: "time.formatUTC(${1:datetime} [, format ]);$0" "time.toTicks(datetime)": prefix: "time.toTicks" description: 'Converts an internal datatime object (UTC) to ticks.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.toTicks' body: "time.toTicks(${1:datetime});$0" "time.fromTicks(ticks)": prefix: "time.fromTicks" description: 'Converts ticks to an internal datetime object (UTC).' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.fromTicks' body: "time.fromTicks(${1:ticks});$0" "time.deltaFromTicks(ticks)": prefix: "time.deltaFromTicks" description: 'Converts ticks into a time delta.' descriptionMoreURL: 'https://docs.bmc.com/docs/display/DISCO111/time.deltaFromTicks' body: "time.deltaFromTicks(${1:ticks});$0" # SIMPLE IDENTIFIERS:: "_regex Simple Identifiers": prefix: "_regex_Simple_Identifiers_" body: "(?1:regex )/}\"${1:regex}\" -> \"${2:product_name}\";$0" "_windows_cmd Simple Identifiers": prefix: "_windows_cmd_Simple_Identifiers_" body: "(?1:windows_cmd )/}\"${1:windows_cmd}\" -> \"${2:product_name}\";$0" "_unix_cmd Simple Identifiers": prefix: "_unix_cmd_Simple_Identifiers_" body: "(?1:unix_cmd )/}\"${1:unix_cmd}\" -> \"${2:product_name}\";$0" # IF OS_CLASS:: "_os_class host.os_class": prefix: "_os_class_host.os_class_" body: """ if host.os_class = "Windows" then sep := '\\\\\\'; else sep := '/'; end if; $0 """
[ { "context": "###\nCopyright © 201{5,6} Jess Austin <jess.austin@gmail.com>\nReleased under MIT Licens", "end": 36, "score": 0.9996318221092224, "start": 25, "tag": "NAME", "value": "Jess Austin" }, { "context": "###\nCopyright © 201{5,6} Jess Austin <jess.austin@gmail.com>\nReleased...
koa-signed-url.coffee
jessaustin/koa-signed-url
2
### Copyright © 201{5,6} Jess Austin <jess.austin@gmail.com> Released under MIT License ### { parse } = require 'url' debug = (require 'debug') 'koa-signed-url' Keygrip = require 'keygrip' add_query_parameter = (url, name, value) -> [ url, query ] = url.split '?' "#{url}?#{if query? then query + '&' else ''}#{name}=#{value}" # Export a function that returns url-signature-verifying middleware, with a # "sign" property containing a url-signing function. Urls are signed by # appending a signature to the query string. See readme.md for advice on secure # use of this module. module.exports = (keys, sigId='sig', expId='exp') -> # keys can be passed in as a single key, an array of keys, or a Keygrip unless keys?.constructor?.name is 'Keygrip' unless Array.isArray keys keys = [ keys ] keys = Keygrip keys debug "using Keygrip with hash #{keys.hash} and keys #{keys}" fn = (next) -> # this is the koa middleware [ ..., url, sig ] = @href.split ///[?&]#{sigId}=/// # Buffer will ignore anything after a '=', so check for that [ sig, rest... ] = sig.split '=' rest = rest.reduce ((acc, {length}) -> acc or length), false unless url? and not rest and keys.verify url, new Buffer sig, 'base64' @status = 404 debug "failed to verify #{@href}" else { query } = parse url, yes if new Date().valueOf() >= parseInt query[expId] @status = 404 debug "#{@href} expired at #{query[expId]}" else debug "verified #{@href}" yield next fn.sign = (url, duration=0) -> # sign() is a property of preceeding function # don't sign fragment [ url, fragment ] = url.split '#' if duration url = add_query_parameter url, expId, new Date().valueOf() + duration sig = keys.sign url .toString 'base64' debug "signing #{url} with signature #{sig}" add_query_parameter(url, sigId, sig) + if fragment? then '#' + fragment else '' fn # now return the original function
36248
### Copyright © 201{5,6} <NAME> <<EMAIL>> Released under MIT License ### { parse } = require 'url' debug = (require 'debug') 'koa-signed-url' Keygrip = require 'keygrip' add_query_parameter = (url, name, value) -> [ url, query ] = url.split '?' "#{url}?#{if query? then query + '&' else ''}#{name}=#{value}" # Export a function that returns url-signature-verifying middleware, with a # "sign" property containing a url-signing function. Urls are signed by # appending a signature to the query string. See readme.md for advice on secure # use of this module. module.exports = (keys, sigId='sig', expId='exp') -> # keys can be passed in as a single key, an array of keys, or a Keygrip unless keys?.constructor?.name is 'Keygrip' unless Array.isArray keys keys = [ keys ] keys = Keygrip keys debug "using Keygrip with hash #{keys.hash} and keys #{keys}" fn = (next) -> # this is the koa middleware [ ..., url, sig ] = @href.split ///[?&]#{sigId}=/// # Buffer will ignore anything after a '=', so check for that [ sig, rest... ] = sig.split '=' rest = rest.reduce ((acc, {length}) -> acc or length), false unless url? and not rest and keys.verify url, new Buffer sig, 'base64' @status = 404 debug "failed to verify #{@href}" else { query } = parse url, yes if new Date().valueOf() >= parseInt query[expId] @status = 404 debug "#{@href} expired at #{query[expId]}" else debug "verified #{@href}" yield next fn.sign = (url, duration=0) -> # sign() is a property of preceeding function # don't sign fragment [ url, fragment ] = url.split '#' if duration url = add_query_parameter url, expId, new Date().valueOf() + duration sig = keys.sign url .toString 'base64' debug "signing #{url} with signature #{sig}" add_query_parameter(url, sigId, sig) + if fragment? then '#' + fragment else '' fn # now return the original function
true
### Copyright © 201{5,6} PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> Released under MIT License ### { parse } = require 'url' debug = (require 'debug') 'koa-signed-url' Keygrip = require 'keygrip' add_query_parameter = (url, name, value) -> [ url, query ] = url.split '?' "#{url}?#{if query? then query + '&' else ''}#{name}=#{value}" # Export a function that returns url-signature-verifying middleware, with a # "sign" property containing a url-signing function. Urls are signed by # appending a signature to the query string. See readme.md for advice on secure # use of this module. module.exports = (keys, sigId='sig', expId='exp') -> # keys can be passed in as a single key, an array of keys, or a Keygrip unless keys?.constructor?.name is 'Keygrip' unless Array.isArray keys keys = [ keys ] keys = Keygrip keys debug "using Keygrip with hash #{keys.hash} and keys #{keys}" fn = (next) -> # this is the koa middleware [ ..., url, sig ] = @href.split ///[?&]#{sigId}=/// # Buffer will ignore anything after a '=', so check for that [ sig, rest... ] = sig.split '=' rest = rest.reduce ((acc, {length}) -> acc or length), false unless url? and not rest and keys.verify url, new Buffer sig, 'base64' @status = 404 debug "failed to verify #{@href}" else { query } = parse url, yes if new Date().valueOf() >= parseInt query[expId] @status = 404 debug "#{@href} expired at #{query[expId]}" else debug "verified #{@href}" yield next fn.sign = (url, duration=0) -> # sign() is a property of preceeding function # don't sign fragment [ url, fragment ] = url.split '#' if duration url = add_query_parameter url, expId, new Date().valueOf() + duration sig = keys.sign url .toString 'base64' debug "signing #{url} with signature #{sig}" add_query_parameter(url, sigId, sig) + if fragment? then '#' + fragment else '' fn # now return the original function
[ { "context": " port: 'string'\n user: 'string'\n password: 'string'\n\n\n mapArr: (arr)->\n arr.map (i)->\n i.dr", "end": 492, "score": 0.9995212554931641, "start": 486, "tag": "PASSWORD", "value": "string" } ]
server/classes/pasture.coffee
karudo/nodedbadmin
1
BaseCollection = require './base_collection' {join} = require 'path' {isString, chain, intval, pluck} = require '../utils/_' class Pasture extends BaseCollection @configure 'Pasture' structure: id: type: 'string' canEdit: no name: 'string' driver: type: 'drvselect' #canEdit: no #type: 'foreignKey' #fkCollection: 'drivers' #fkFullPath: 'system#drivers' host: 'string' port: 'string' user: 'string' password: 'string' mapArr: (arr)-> arr.map (i)-> i.driverPath = "pastures:#{i.id}" i.defPath = "#{i.driverPath}#databases" i makePk: (idx, item)-> cur = chain(@_items).pluck(@pkFields).filter().map((v)-> intval v.replace('conn', '')).max().value() if cur < 0 cur = 0 cur++ 'conn' + cur module.exports = Pasture
211402
BaseCollection = require './base_collection' {join} = require 'path' {isString, chain, intval, pluck} = require '../utils/_' class Pasture extends BaseCollection @configure 'Pasture' structure: id: type: 'string' canEdit: no name: 'string' driver: type: 'drvselect' #canEdit: no #type: 'foreignKey' #fkCollection: 'drivers' #fkFullPath: 'system#drivers' host: 'string' port: 'string' user: 'string' password: '<PASSWORD>' mapArr: (arr)-> arr.map (i)-> i.driverPath = "pastures:#{i.id}" i.defPath = "#{i.driverPath}#databases" i makePk: (idx, item)-> cur = chain(@_items).pluck(@pkFields).filter().map((v)-> intval v.replace('conn', '')).max().value() if cur < 0 cur = 0 cur++ 'conn' + cur module.exports = Pasture
true
BaseCollection = require './base_collection' {join} = require 'path' {isString, chain, intval, pluck} = require '../utils/_' class Pasture extends BaseCollection @configure 'Pasture' structure: id: type: 'string' canEdit: no name: 'string' driver: type: 'drvselect' #canEdit: no #type: 'foreignKey' #fkCollection: 'drivers' #fkFullPath: 'system#drivers' host: 'string' port: 'string' user: 'string' password: 'PI:PASSWORD:<PASSWORD>END_PI' mapArr: (arr)-> arr.map (i)-> i.driverPath = "pastures:#{i.id}" i.defPath = "#{i.driverPath}#databases" i makePk: (idx, item)-> cur = chain(@_items).pluck(@pkFields).filter().map((v)-> intval v.replace('conn', '')).max().value() if cur < 0 cur = 0 cur++ 'conn' + cur module.exports = Pasture
[ { "context": "om/hakanersu/AmaranJS\n# *\n# * Copyright 2013, 2014 Hakan ERSU\n# * Released under the MIT license\n# \n\n(($, windo", "end": 118, "score": 0.9998704195022583, "start": 108, "tag": "NAME", "value": "Hakan ERSU" }, { "context": "revent\n # on click ev...
core/amaranjs/src/coffee/jquery.amaran.coffee
ctslots/blizzcms
2
#! # * jQuery AmaranJS Plugin v0.5.1 # * https://github.com/hakanersu/AmaranJS # * # * Copyright 2013, 2014 Hakan ERSU # * Released under the MIT license # (($, window, document, undefined_) -> Plugin = (options) -> defaults = position: "bottom right" content: " " delay: 3000 sticky: false inEffect: "fadeIn" outEffect: "fadeOut" theme: "default" themeTemplate: null closeOnClick: true closeButton: false clearAll: false cssanimationIn: false cssanimationOut: false beforeStart: -> afterEnd: -> onClick: -> wrapper: ".amaran-wrapper" @config = $.extend({}, defaults, options) @config.beforeStart() @init() @close() return Plugin:: = init: -> wrapper= null wrapperInner = null elClass = @config.position.split(" ") # Lets create wrapper for amaranjs notification elements. # If wrapper not created yet lets create wrapper. unless $(@config.wrapper).length # Remove dot from wrapper and append position value. # Append wrapper to body. wrapper = $("<div>",class: @config.wrapper.substr(1, @config.wrapper.length) + " " + @config.position).appendTo("body") innerWrapper = $("<div>",class: "amaran-wrapper-inner").appendTo(wrapper) else # We have wrapper. # If our wrapper dont have same positon value # it must be another wrapper instance unless $(@config.wrapper).hasClass(@config.position) # Append new wrapper to body. wrapper = $("<div>",class: @config.wrapper.substr(1, @config.wrapper.length) + " " + @config.position).appendTo("body") innerWrapper = $("<div>",class: "amaran-wrapper-inner").appendTo(wrapper) else # If we have wrapper with same class just set wrapper value to # current wrapper. wrapper = $(@config.wrapper + "." + elClass[0] + "." + elClass[1]) innerWrapper = wrapper.find ".amaran-wrapper-inner" #message = (if (typeof (@config.content) is "object") then (if (@config.themeTemplate?) then @config.themeTemplate(@config.content) else themes[@config.theme.split(" ")[0] + "Theme"](@config.content)) else @config.content) # Is content is an object ? if typeof (@config.content) is "object" # Is custom theme setted ? if @config.themeTemplate? message = @config.themeTemplate(@config.content) else # If there is a theme call function and get html content message = themes[@config.theme.split(" ")[0] + "Theme"](@config.content) else # If content not an object it must be plain text # So lets create an object @config.content = {} @config.content.message = @config.message @config.content.color = "#27ae60" message = themes["defaultTheme"](@config.content) # Create object for element creation amaranObject = class: (if @config.themeTemplate then "amaran " + @config.content.themeName else (if (@config.theme and not @config.themeTemplate) then "amaran " + @config.theme else "amaran")) html: (if (@config.closeButton) then "<span class=\"amaran-close\" data-amaran-close=\"true\"></span>" + message else message) # Clear if clearAll option true $(".amaran").remove() if @config.clearAll # Finally lets create element and append to wrapper. element = $("<div>", amaranObject).appendTo(innerWrapper) @centerCalculate wrapper, innerWrapper if elClass[0] is "center" @animation @config.inEffect, element, "show" # OnClick callback if @config.onClick bu = this $(element).on "click",(e) -> # Quick fix when clicked close button it must prevent # on click event.Thanks Sibin Xavier to report. if $(e.target).is(".amaran-close") e.preventDefault() return bu.config.onClick() return # If its not sticky hide after delay @hideDiv element if @config.sticky isnt true return centerCalculate: (wrapper,innerWrapper) -> totalAmarans = innerWrapper.find(".amaran").length totalAmaransHeight = innerWrapper.height() topAmaranMargin = (wrapper.height()-totalAmaransHeight)/2 innerWrapper.find(".amaran:first-child").animate "margin-top": topAmaranMargin , 200 return # Lets decide which effect we will use animation: (effect, element, work) -> return @fade(element, work) if effect is "fadeIn" or effect is "fadeOut" return @cssanimate(element,work) if effect is "show" return @slide effect, element, work fade: (element,work) -> # Fade is easy one # if work is show just fadein element bu = @ if work is "show" if @.config.cssanimationIn element.addClass('animated '+@.config.cssanimationIn).show() else element.fadeIn() else if @.config.cssanimationOut element.addClass('animated '+@.config.cssanimationOut) element.css "min-height": 0 "height": element.outerHeight() element.animate opacity: 0 , -> element.animate height: 0 , -> #element.remove() bu.removeIt(element) return return return else # If work is not show basic fadeOut effect not good for us # we have to set height and when opacity reach 0 we have to set # height 0 otherwise when we remove element other elements seems like jumps down # lets create this effect element.css "min-height": 0 "height": element.outerHeight() element.animate opacity: 0 , -> element.animate height: 0 , -> bu.removeIt(element) #bu.config.afterEnd() return return return return removeIt: (element) -> clearTimeout(@.timeout) element.remove() wrapper = $(@config.wrapper+"."+@config.position.split(" ")[0]+"."+@config.position.split(" ")[1]) innerWrapper = wrapper.find ".amaran-wrapper-inner" @centerCalculate wrapper, innerWrapper if @config.position.split(" ")[0] is "center" @.config.afterEnd() return # why this method ? # i need elements width for calculation before show # i did this function before border-box become popular # so i will change this method soon getWidth: (el) -> # Lets clone the element and get width newEl = el.clone().hide().appendTo("body") # I will try to find better way to calculate this # This is not actual width #Right way is newElWidth=newEl.outerWidth()+parseInt(el.css('margin')); newElWidth = newEl.outerWidth() + newEl.outerWidth()/2 # we dont need this element anymote newEl.remove() return newElWidth # For sliding effects i need informantion about # element and wrapper position and size. getInfo: (element) -> # Element offset offset = element.offset() # Wrapper offset wrapperOffset = $(@config.wrapper).offset() # Lets set each values for the element and wrapper t: offset.top l: offset.left h: element.height() w: element.outerWidth() wT: wrapperOffset.top wL: wrapperOffset.left wH: $(@config.wrapper).outerHeight() wW: $(@config.wrapper).outerWidth() # Here is the calculations of slide effect # Some of them not accurate ill try to fix sometime getPosition: (element,effect) -> # Lets get info about element p = @getInfo(element) # where is the element parca = @config.position.split(" ")[1] # v is our position object v = # Slide top calculation slideTop: start: top: -(p.wT + p.wH + p.h*2) move: top: 0 hide: top: -(p.t+(p.h*2)) height: p.h slideBottom: start: top: ($(window).height() - p.wH + p.h * 2) move: top: 0 hide: top: ($(window).height() - p.wH + p.h * 2) height: p.h slideLeft: start: left: (if (parca is "left") then -p.w * 1.5 else -$(window).width()) move: left: 0 hide: left: (if (parca is "left") then -p.w * 1.5 else -$(window).width()) height: p.h slideRight: start: left: (if (parca is "right") then p.w * 1.5 else $(window).width()) move: left: 0 hide: left: (if (parca is "right") then p.w * 1.5 else $(window).width()) height: p.h (if v[effect] then v[effect] else 0) # We have all effect values from previous method # so lets create slide method slide: (effect,element,work) -> # Get calculated values with given element and effect position = @getPosition(element,effect) # if just show it is the easy one if work is "show" element.show().css(position.start).animate position.move return else # Yet again try to prevent jump effect bu = this element.animate(position.hide , -> element.css "min-height": 0 "height": position.height , -> element.html " " return return ).animate height: 0 , -> #element.remove() bu.removeIt(element) #bu.config.afterEnd() # Lets remove/close element close: -> bu = this # Let closeing with attiribute $("[data-amaran-close]").on "click", -> bu.animation bu.config.outEffect, $(this).closest("div.amaran"), "hide" return # if closeOnClick and closeButton not setted # lets set wrapper if not @config.closeOnClick and @config.closeButton bu.animation bu.config.outEffect , $(this).parent("div.amaran"), "hide" return # If closeOnClick setted else if @config.closeOnClick $(".amaran").on "click", -> bu.animation bu.config.outEffect, $(this), "hide" return return hideDiv: (element) -> bu = this bu.timeout=setTimeout (-> bu.animation bu.config.outEffect, element, "hide" return ), bu.config.delay return themes = defaultTheme: (data) -> color = "" color = data.color if typeof (data.color) isnt "undefined" "<div class='default-spinner'><span style='background-color:" + data.color + "'></span></div><div class='default-message'><span>" + data.message + "</span></div>" awesomeTheme: (data) -> "<i class=\"icon " + data.icon + " icon-large\"></i><p class=\"bold\">" + data.title + "</p><p><span>" + data.message + "</span><span class=\"light\">" + data.info + "</span></p>" userTheme: (data) -> "<div class=\"icon\"><img src=\"" + data.img + "\" alt=\"\" /></div><div class=\"info\"><b>" + data.user + "</b>" + data.message + "</div>" colorfulTheme: (data) -> color = data.color if typeof (data.color) isnt "undefined" bgcolor = data.bgcolor if typeof (data.bgcolor) isnt "undefined" "<div class='colorful-inner' style='background-color:" + data.bgcolor + ";color:" + data.color + "'>" + data.message + "</div>" tumblrTheme: (data) -> "<div class=\"title\">"+data.title+"</div><div class=\"content\">"+data.message+"</div>" $.amaran = (options) -> amaran = new Plugin(options) amaran $.amaran.close = -> $(".amaran-wrapper").remove() false ) jQuery, window, document
137
#! # * jQuery AmaranJS Plugin v0.5.1 # * https://github.com/hakanersu/AmaranJS # * # * Copyright 2013, 2014 <NAME> # * Released under the MIT license # (($, window, document, undefined_) -> Plugin = (options) -> defaults = position: "bottom right" content: " " delay: 3000 sticky: false inEffect: "fadeIn" outEffect: "fadeOut" theme: "default" themeTemplate: null closeOnClick: true closeButton: false clearAll: false cssanimationIn: false cssanimationOut: false beforeStart: -> afterEnd: -> onClick: -> wrapper: ".amaran-wrapper" @config = $.extend({}, defaults, options) @config.beforeStart() @init() @close() return Plugin:: = init: -> wrapper= null wrapperInner = null elClass = @config.position.split(" ") # Lets create wrapper for amaranjs notification elements. # If wrapper not created yet lets create wrapper. unless $(@config.wrapper).length # Remove dot from wrapper and append position value. # Append wrapper to body. wrapper = $("<div>",class: @config.wrapper.substr(1, @config.wrapper.length) + " " + @config.position).appendTo("body") innerWrapper = $("<div>",class: "amaran-wrapper-inner").appendTo(wrapper) else # We have wrapper. # If our wrapper dont have same positon value # it must be another wrapper instance unless $(@config.wrapper).hasClass(@config.position) # Append new wrapper to body. wrapper = $("<div>",class: @config.wrapper.substr(1, @config.wrapper.length) + " " + @config.position).appendTo("body") innerWrapper = $("<div>",class: "amaran-wrapper-inner").appendTo(wrapper) else # If we have wrapper with same class just set wrapper value to # current wrapper. wrapper = $(@config.wrapper + "." + elClass[0] + "." + elClass[1]) innerWrapper = wrapper.find ".amaran-wrapper-inner" #message = (if (typeof (@config.content) is "object") then (if (@config.themeTemplate?) then @config.themeTemplate(@config.content) else themes[@config.theme.split(" ")[0] + "Theme"](@config.content)) else @config.content) # Is content is an object ? if typeof (@config.content) is "object" # Is custom theme setted ? if @config.themeTemplate? message = @config.themeTemplate(@config.content) else # If there is a theme call function and get html content message = themes[@config.theme.split(" ")[0] + "Theme"](@config.content) else # If content not an object it must be plain text # So lets create an object @config.content = {} @config.content.message = @config.message @config.content.color = "#27ae60" message = themes["defaultTheme"](@config.content) # Create object for element creation amaranObject = class: (if @config.themeTemplate then "amaran " + @config.content.themeName else (if (@config.theme and not @config.themeTemplate) then "amaran " + @config.theme else "amaran")) html: (if (@config.closeButton) then "<span class=\"amaran-close\" data-amaran-close=\"true\"></span>" + message else message) # Clear if clearAll option true $(".amaran").remove() if @config.clearAll # Finally lets create element and append to wrapper. element = $("<div>", amaranObject).appendTo(innerWrapper) @centerCalculate wrapper, innerWrapper if elClass[0] is "center" @animation @config.inEffect, element, "show" # OnClick callback if @config.onClick bu = this $(element).on "click",(e) -> # Quick fix when clicked close button it must prevent # on click event.Thanks <NAME> to report. if $(e.target).is(".amaran-close") e.preventDefault() return bu.config.onClick() return # If its not sticky hide after delay @hideDiv element if @config.sticky isnt true return centerCalculate: (wrapper,innerWrapper) -> totalAmarans = innerWrapper.find(".amaran").length totalAmaransHeight = innerWrapper.height() topAmaranMargin = (wrapper.height()-totalAmaransHeight)/2 innerWrapper.find(".amaran:first-child").animate "margin-top": topAmaranMargin , 200 return # Lets decide which effect we will use animation: (effect, element, work) -> return @fade(element, work) if effect is "fadeIn" or effect is "fadeOut" return @cssanimate(element,work) if effect is "show" return @slide effect, element, work fade: (element,work) -> # Fade is easy one # if work is show just fadein element bu = @ if work is "show" if @.config.cssanimationIn element.addClass('animated '+@.config.cssanimationIn).show() else element.fadeIn() else if @.config.cssanimationOut element.addClass('animated '+@.config.cssanimationOut) element.css "min-height": 0 "height": element.outerHeight() element.animate opacity: 0 , -> element.animate height: 0 , -> #element.remove() bu.removeIt(element) return return return else # If work is not show basic fadeOut effect not good for us # we have to set height and when opacity reach 0 we have to set # height 0 otherwise when we remove element other elements seems like jumps down # lets create this effect element.css "min-height": 0 "height": element.outerHeight() element.animate opacity: 0 , -> element.animate height: 0 , -> bu.removeIt(element) #bu.config.afterEnd() return return return return removeIt: (element) -> clearTimeout(@.timeout) element.remove() wrapper = $(@config.wrapper+"."+@config.position.split(" ")[0]+"."+@config.position.split(" ")[1]) innerWrapper = wrapper.find ".amaran-wrapper-inner" @centerCalculate wrapper, innerWrapper if @config.position.split(" ")[0] is "center" @.config.afterEnd() return # why this method ? # i need elements width for calculation before show # i did this function before border-box become popular # so i will change this method soon getWidth: (el) -> # Lets clone the element and get width newEl = el.clone().hide().appendTo("body") # I will try to find better way to calculate this # This is not actual width #Right way is newElWidth=newEl.outerWidth()+parseInt(el.css('margin')); newElWidth = newEl.outerWidth() + newEl.outerWidth()/2 # we dont need this element anymote newEl.remove() return newElWidth # For sliding effects i need informantion about # element and wrapper position and size. getInfo: (element) -> # Element offset offset = element.offset() # Wrapper offset wrapperOffset = $(@config.wrapper).offset() # Lets set each values for the element and wrapper t: offset.top l: offset.left h: element.height() w: element.outerWidth() wT: wrapperOffset.top wL: wrapperOffset.left wH: $(@config.wrapper).outerHeight() wW: $(@config.wrapper).outerWidth() # Here is the calculations of slide effect # Some of them not accurate ill try to fix sometime getPosition: (element,effect) -> # Lets get info about element p = @getInfo(element) # where is the element parca = @config.position.split(" ")[1] # v is our position object v = # Slide top calculation slideTop: start: top: -(p.wT + p.wH + p.h*2) move: top: 0 hide: top: -(p.t+(p.h*2)) height: p.h slideBottom: start: top: ($(window).height() - p.wH + p.h * 2) move: top: 0 hide: top: ($(window).height() - p.wH + p.h * 2) height: p.h slideLeft: start: left: (if (parca is "left") then -p.w * 1.5 else -$(window).width()) move: left: 0 hide: left: (if (parca is "left") then -p.w * 1.5 else -$(window).width()) height: p.h slideRight: start: left: (if (parca is "right") then p.w * 1.5 else $(window).width()) move: left: 0 hide: left: (if (parca is "right") then p.w * 1.5 else $(window).width()) height: p.h (if v[effect] then v[effect] else 0) # We have all effect values from previous method # so lets create slide method slide: (effect,element,work) -> # Get calculated values with given element and effect position = @getPosition(element,effect) # if just show it is the easy one if work is "show" element.show().css(position.start).animate position.move return else # Yet again try to prevent jump effect bu = this element.animate(position.hide , -> element.css "min-height": 0 "height": position.height , -> element.html " " return return ).animate height: 0 , -> #element.remove() bu.removeIt(element) #bu.config.afterEnd() # Lets remove/close element close: -> bu = this # Let closeing with attiribute $("[data-amaran-close]").on "click", -> bu.animation bu.config.outEffect, $(this).closest("div.amaran"), "hide" return # if closeOnClick and closeButton not setted # lets set wrapper if not @config.closeOnClick and @config.closeButton bu.animation bu.config.outEffect , $(this).parent("div.amaran"), "hide" return # If closeOnClick setted else if @config.closeOnClick $(".amaran").on "click", -> bu.animation bu.config.outEffect, $(this), "hide" return return hideDiv: (element) -> bu = this bu.timeout=setTimeout (-> bu.animation bu.config.outEffect, element, "hide" return ), bu.config.delay return themes = defaultTheme: (data) -> color = "" color = data.color if typeof (data.color) isnt "undefined" "<div class='default-spinner'><span style='background-color:" + data.color + "'></span></div><div class='default-message'><span>" + data.message + "</span></div>" awesomeTheme: (data) -> "<i class=\"icon " + data.icon + " icon-large\"></i><p class=\"bold\">" + data.title + "</p><p><span>" + data.message + "</span><span class=\"light\">" + data.info + "</span></p>" userTheme: (data) -> "<div class=\"icon\"><img src=\"" + data.img + "\" alt=\"\" /></div><div class=\"info\"><b>" + data.user + "</b>" + data.message + "</div>" colorfulTheme: (data) -> color = data.color if typeof (data.color) isnt "undefined" bgcolor = data.bgcolor if typeof (data.bgcolor) isnt "undefined" "<div class='colorful-inner' style='background-color:" + data.bgcolor + ";color:" + data.color + "'>" + data.message + "</div>" tumblrTheme: (data) -> "<div class=\"title\">"+data.title+"</div><div class=\"content\">"+data.message+"</div>" $.amaran = (options) -> amaran = new Plugin(options) amaran $.amaran.close = -> $(".amaran-wrapper").remove() false ) jQuery, window, document
true
#! # * jQuery AmaranJS Plugin v0.5.1 # * https://github.com/hakanersu/AmaranJS # * # * Copyright 2013, 2014 PI:NAME:<NAME>END_PI # * Released under the MIT license # (($, window, document, undefined_) -> Plugin = (options) -> defaults = position: "bottom right" content: " " delay: 3000 sticky: false inEffect: "fadeIn" outEffect: "fadeOut" theme: "default" themeTemplate: null closeOnClick: true closeButton: false clearAll: false cssanimationIn: false cssanimationOut: false beforeStart: -> afterEnd: -> onClick: -> wrapper: ".amaran-wrapper" @config = $.extend({}, defaults, options) @config.beforeStart() @init() @close() return Plugin:: = init: -> wrapper= null wrapperInner = null elClass = @config.position.split(" ") # Lets create wrapper for amaranjs notification elements. # If wrapper not created yet lets create wrapper. unless $(@config.wrapper).length # Remove dot from wrapper and append position value. # Append wrapper to body. wrapper = $("<div>",class: @config.wrapper.substr(1, @config.wrapper.length) + " " + @config.position).appendTo("body") innerWrapper = $("<div>",class: "amaran-wrapper-inner").appendTo(wrapper) else # We have wrapper. # If our wrapper dont have same positon value # it must be another wrapper instance unless $(@config.wrapper).hasClass(@config.position) # Append new wrapper to body. wrapper = $("<div>",class: @config.wrapper.substr(1, @config.wrapper.length) + " " + @config.position).appendTo("body") innerWrapper = $("<div>",class: "amaran-wrapper-inner").appendTo(wrapper) else # If we have wrapper with same class just set wrapper value to # current wrapper. wrapper = $(@config.wrapper + "." + elClass[0] + "." + elClass[1]) innerWrapper = wrapper.find ".amaran-wrapper-inner" #message = (if (typeof (@config.content) is "object") then (if (@config.themeTemplate?) then @config.themeTemplate(@config.content) else themes[@config.theme.split(" ")[0] + "Theme"](@config.content)) else @config.content) # Is content is an object ? if typeof (@config.content) is "object" # Is custom theme setted ? if @config.themeTemplate? message = @config.themeTemplate(@config.content) else # If there is a theme call function and get html content message = themes[@config.theme.split(" ")[0] + "Theme"](@config.content) else # If content not an object it must be plain text # So lets create an object @config.content = {} @config.content.message = @config.message @config.content.color = "#27ae60" message = themes["defaultTheme"](@config.content) # Create object for element creation amaranObject = class: (if @config.themeTemplate then "amaran " + @config.content.themeName else (if (@config.theme and not @config.themeTemplate) then "amaran " + @config.theme else "amaran")) html: (if (@config.closeButton) then "<span class=\"amaran-close\" data-amaran-close=\"true\"></span>" + message else message) # Clear if clearAll option true $(".amaran").remove() if @config.clearAll # Finally lets create element and append to wrapper. element = $("<div>", amaranObject).appendTo(innerWrapper) @centerCalculate wrapper, innerWrapper if elClass[0] is "center" @animation @config.inEffect, element, "show" # OnClick callback if @config.onClick bu = this $(element).on "click",(e) -> # Quick fix when clicked close button it must prevent # on click event.Thanks PI:NAME:<NAME>END_PI to report. if $(e.target).is(".amaran-close") e.preventDefault() return bu.config.onClick() return # If its not sticky hide after delay @hideDiv element if @config.sticky isnt true return centerCalculate: (wrapper,innerWrapper) -> totalAmarans = innerWrapper.find(".amaran").length totalAmaransHeight = innerWrapper.height() topAmaranMargin = (wrapper.height()-totalAmaransHeight)/2 innerWrapper.find(".amaran:first-child").animate "margin-top": topAmaranMargin , 200 return # Lets decide which effect we will use animation: (effect, element, work) -> return @fade(element, work) if effect is "fadeIn" or effect is "fadeOut" return @cssanimate(element,work) if effect is "show" return @slide effect, element, work fade: (element,work) -> # Fade is easy one # if work is show just fadein element bu = @ if work is "show" if @.config.cssanimationIn element.addClass('animated '+@.config.cssanimationIn).show() else element.fadeIn() else if @.config.cssanimationOut element.addClass('animated '+@.config.cssanimationOut) element.css "min-height": 0 "height": element.outerHeight() element.animate opacity: 0 , -> element.animate height: 0 , -> #element.remove() bu.removeIt(element) return return return else # If work is not show basic fadeOut effect not good for us # we have to set height and when opacity reach 0 we have to set # height 0 otherwise when we remove element other elements seems like jumps down # lets create this effect element.css "min-height": 0 "height": element.outerHeight() element.animate opacity: 0 , -> element.animate height: 0 , -> bu.removeIt(element) #bu.config.afterEnd() return return return return removeIt: (element) -> clearTimeout(@.timeout) element.remove() wrapper = $(@config.wrapper+"."+@config.position.split(" ")[0]+"."+@config.position.split(" ")[1]) innerWrapper = wrapper.find ".amaran-wrapper-inner" @centerCalculate wrapper, innerWrapper if @config.position.split(" ")[0] is "center" @.config.afterEnd() return # why this method ? # i need elements width for calculation before show # i did this function before border-box become popular # so i will change this method soon getWidth: (el) -> # Lets clone the element and get width newEl = el.clone().hide().appendTo("body") # I will try to find better way to calculate this # This is not actual width #Right way is newElWidth=newEl.outerWidth()+parseInt(el.css('margin')); newElWidth = newEl.outerWidth() + newEl.outerWidth()/2 # we dont need this element anymote newEl.remove() return newElWidth # For sliding effects i need informantion about # element and wrapper position and size. getInfo: (element) -> # Element offset offset = element.offset() # Wrapper offset wrapperOffset = $(@config.wrapper).offset() # Lets set each values for the element and wrapper t: offset.top l: offset.left h: element.height() w: element.outerWidth() wT: wrapperOffset.top wL: wrapperOffset.left wH: $(@config.wrapper).outerHeight() wW: $(@config.wrapper).outerWidth() # Here is the calculations of slide effect # Some of them not accurate ill try to fix sometime getPosition: (element,effect) -> # Lets get info about element p = @getInfo(element) # where is the element parca = @config.position.split(" ")[1] # v is our position object v = # Slide top calculation slideTop: start: top: -(p.wT + p.wH + p.h*2) move: top: 0 hide: top: -(p.t+(p.h*2)) height: p.h slideBottom: start: top: ($(window).height() - p.wH + p.h * 2) move: top: 0 hide: top: ($(window).height() - p.wH + p.h * 2) height: p.h slideLeft: start: left: (if (parca is "left") then -p.w * 1.5 else -$(window).width()) move: left: 0 hide: left: (if (parca is "left") then -p.w * 1.5 else -$(window).width()) height: p.h slideRight: start: left: (if (parca is "right") then p.w * 1.5 else $(window).width()) move: left: 0 hide: left: (if (parca is "right") then p.w * 1.5 else $(window).width()) height: p.h (if v[effect] then v[effect] else 0) # We have all effect values from previous method # so lets create slide method slide: (effect,element,work) -> # Get calculated values with given element and effect position = @getPosition(element,effect) # if just show it is the easy one if work is "show" element.show().css(position.start).animate position.move return else # Yet again try to prevent jump effect bu = this element.animate(position.hide , -> element.css "min-height": 0 "height": position.height , -> element.html " " return return ).animate height: 0 , -> #element.remove() bu.removeIt(element) #bu.config.afterEnd() # Lets remove/close element close: -> bu = this # Let closeing with attiribute $("[data-amaran-close]").on "click", -> bu.animation bu.config.outEffect, $(this).closest("div.amaran"), "hide" return # if closeOnClick and closeButton not setted # lets set wrapper if not @config.closeOnClick and @config.closeButton bu.animation bu.config.outEffect , $(this).parent("div.amaran"), "hide" return # If closeOnClick setted else if @config.closeOnClick $(".amaran").on "click", -> bu.animation bu.config.outEffect, $(this), "hide" return return hideDiv: (element) -> bu = this bu.timeout=setTimeout (-> bu.animation bu.config.outEffect, element, "hide" return ), bu.config.delay return themes = defaultTheme: (data) -> color = "" color = data.color if typeof (data.color) isnt "undefined" "<div class='default-spinner'><span style='background-color:" + data.color + "'></span></div><div class='default-message'><span>" + data.message + "</span></div>" awesomeTheme: (data) -> "<i class=\"icon " + data.icon + " icon-large\"></i><p class=\"bold\">" + data.title + "</p><p><span>" + data.message + "</span><span class=\"light\">" + data.info + "</span></p>" userTheme: (data) -> "<div class=\"icon\"><img src=\"" + data.img + "\" alt=\"\" /></div><div class=\"info\"><b>" + data.user + "</b>" + data.message + "</div>" colorfulTheme: (data) -> color = data.color if typeof (data.color) isnt "undefined" bgcolor = data.bgcolor if typeof (data.bgcolor) isnt "undefined" "<div class='colorful-inner' style='background-color:" + data.bgcolor + ";color:" + data.color + "'>" + data.message + "</div>" tumblrTheme: (data) -> "<div class=\"title\">"+data.title+"</div><div class=\"content\">"+data.message+"</div>" $.amaran = (options) -> amaran = new Plugin(options) amaran $.amaran.close = -> $(".amaran-wrapper").remove() false ) jQuery, window, document
[ { "context": "ceLabs:\n startConnect: true\n testName: \"MacGyver\"\n\n customLaunchers:\n SL_Chrome:\n b", "end": 107, "score": 0.9556479454040527, "start": 99, "tag": "NAME", "value": "MacGyver" } ]
test/karma.conf.coffee
Benzinga/MacGyver
0
module.exports = (config) -> config.set sauceLabs: startConnect: true testName: "MacGyver" customLaunchers: SL_Chrome: base: "SauceLabs" browserName: "chrome" SL_Firefox: base: 'SauceLabs', browserName: 'firefox', version: '26' SL_Safari: base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.9', version: '7' SL_IE_9: base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 2008', version: '9' SL_IE_10: base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 2012', version: '10' SL_IE_11: base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 8.1', version: '11' # base path, that will be used to resolve files and exclude basePath: "../example" frameworks: ["jasmine"] # list of files / patterns to load in the browser files: [ # Javascript "../vendor/bower/jquery/jquery.js" "../vendor/bower/underscore.string/lib/underscore.string.js" "../vendor/bower/jquery.ui/ui/jquery.ui.core.js" "../vendor/bower/jquery.ui/ui/jquery.ui.widget.js" "../vendor/bower/jquery.ui/ui/jquery.ui.mouse.js" "../vendor/bower/jquery.ui/ui/jquery.ui.position.js" "../vendor/bower/jquery.ui/ui/jquery.ui.datepicker.js" "../vendor/bower/jquery.ui/ui/jquery.ui.resizable.js" "../vendor/bower/jquery.ui/ui/jquery.ui.sortable.js" "../vendor/bower/angular/angular.js" "../vendor/bower/angular-animate/angular-animate.js" # Template "template/*.html" # Test Code "../src/main.coffee" "../src/services/*.coffee" "../src/*.coffee" "../src/**/*.coffee" "../vendor/bower/angular-mocks/angular-mocks.js" "../test/vendor/browserTrigger.js" "../test/unit/*.spec.coffee" ] exclude: [ "../src/example_controller/*.coffee" ] reporters: ["progress"] logLevel: config.LOG_INFO browsers: ["PhantomJS"] preprocessors: "../**/*.coffee": ["coffee"] "**/*.html": ["ng-html2js"] plugins: ["karma-*"] if process.env.TRAVIS buildLabel = "TRAVIS ##{process.env.TRAVIS_BUILD_NUMBER} (#{process.env.TRAVIS_BUILD_ID})" config.sauceLabs.build = buildLabel config.sauceLabs.startConnect = false config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER config.transports = ["xhr-polling"] # Taken from AngularJS karma-shared.conf.js # Terrible hack to workaround inflexibility of log4js: # - ignore web-server's 404 warnings, log4js = require("../node_modules/karma/node_modules/log4js") layouts = require("../node_modules/karma/node_modules/log4js/lib/layouts") originalConfigure = log4js.configure log4js.configure = (log4jsConfig) -> consoleAppender = log4jsConfig.appenders.shift() originalResult = originalConfigure.call(log4js, log4jsConfig) layout = layouts.layout(consoleAppender.layout.type, consoleAppender.layout) log4js.addAppender (log) -> msg = log.data[0] # ignore web-server's 404s return if log.categoryName is "web-server" and log.level.levelStr is config.LOG_WARN console.log layout(log) originalResult
77375
module.exports = (config) -> config.set sauceLabs: startConnect: true testName: "<NAME>" customLaunchers: SL_Chrome: base: "SauceLabs" browserName: "chrome" SL_Firefox: base: 'SauceLabs', browserName: 'firefox', version: '26' SL_Safari: base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.9', version: '7' SL_IE_9: base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 2008', version: '9' SL_IE_10: base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 2012', version: '10' SL_IE_11: base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 8.1', version: '11' # base path, that will be used to resolve files and exclude basePath: "../example" frameworks: ["jasmine"] # list of files / patterns to load in the browser files: [ # Javascript "../vendor/bower/jquery/jquery.js" "../vendor/bower/underscore.string/lib/underscore.string.js" "../vendor/bower/jquery.ui/ui/jquery.ui.core.js" "../vendor/bower/jquery.ui/ui/jquery.ui.widget.js" "../vendor/bower/jquery.ui/ui/jquery.ui.mouse.js" "../vendor/bower/jquery.ui/ui/jquery.ui.position.js" "../vendor/bower/jquery.ui/ui/jquery.ui.datepicker.js" "../vendor/bower/jquery.ui/ui/jquery.ui.resizable.js" "../vendor/bower/jquery.ui/ui/jquery.ui.sortable.js" "../vendor/bower/angular/angular.js" "../vendor/bower/angular-animate/angular-animate.js" # Template "template/*.html" # Test Code "../src/main.coffee" "../src/services/*.coffee" "../src/*.coffee" "../src/**/*.coffee" "../vendor/bower/angular-mocks/angular-mocks.js" "../test/vendor/browserTrigger.js" "../test/unit/*.spec.coffee" ] exclude: [ "../src/example_controller/*.coffee" ] reporters: ["progress"] logLevel: config.LOG_INFO browsers: ["PhantomJS"] preprocessors: "../**/*.coffee": ["coffee"] "**/*.html": ["ng-html2js"] plugins: ["karma-*"] if process.env.TRAVIS buildLabel = "TRAVIS ##{process.env.TRAVIS_BUILD_NUMBER} (#{process.env.TRAVIS_BUILD_ID})" config.sauceLabs.build = buildLabel config.sauceLabs.startConnect = false config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER config.transports = ["xhr-polling"] # Taken from AngularJS karma-shared.conf.js # Terrible hack to workaround inflexibility of log4js: # - ignore web-server's 404 warnings, log4js = require("../node_modules/karma/node_modules/log4js") layouts = require("../node_modules/karma/node_modules/log4js/lib/layouts") originalConfigure = log4js.configure log4js.configure = (log4jsConfig) -> consoleAppender = log4jsConfig.appenders.shift() originalResult = originalConfigure.call(log4js, log4jsConfig) layout = layouts.layout(consoleAppender.layout.type, consoleAppender.layout) log4js.addAppender (log) -> msg = log.data[0] # ignore web-server's 404s return if log.categoryName is "web-server" and log.level.levelStr is config.LOG_WARN console.log layout(log) originalResult
true
module.exports = (config) -> config.set sauceLabs: startConnect: true testName: "PI:NAME:<NAME>END_PI" customLaunchers: SL_Chrome: base: "SauceLabs" browserName: "chrome" SL_Firefox: base: 'SauceLabs', browserName: 'firefox', version: '26' SL_Safari: base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.9', version: '7' SL_IE_9: base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 2008', version: '9' SL_IE_10: base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 2012', version: '10' SL_IE_11: base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 8.1', version: '11' # base path, that will be used to resolve files and exclude basePath: "../example" frameworks: ["jasmine"] # list of files / patterns to load in the browser files: [ # Javascript "../vendor/bower/jquery/jquery.js" "../vendor/bower/underscore.string/lib/underscore.string.js" "../vendor/bower/jquery.ui/ui/jquery.ui.core.js" "../vendor/bower/jquery.ui/ui/jquery.ui.widget.js" "../vendor/bower/jquery.ui/ui/jquery.ui.mouse.js" "../vendor/bower/jquery.ui/ui/jquery.ui.position.js" "../vendor/bower/jquery.ui/ui/jquery.ui.datepicker.js" "../vendor/bower/jquery.ui/ui/jquery.ui.resizable.js" "../vendor/bower/jquery.ui/ui/jquery.ui.sortable.js" "../vendor/bower/angular/angular.js" "../vendor/bower/angular-animate/angular-animate.js" # Template "template/*.html" # Test Code "../src/main.coffee" "../src/services/*.coffee" "../src/*.coffee" "../src/**/*.coffee" "../vendor/bower/angular-mocks/angular-mocks.js" "../test/vendor/browserTrigger.js" "../test/unit/*.spec.coffee" ] exclude: [ "../src/example_controller/*.coffee" ] reporters: ["progress"] logLevel: config.LOG_INFO browsers: ["PhantomJS"] preprocessors: "../**/*.coffee": ["coffee"] "**/*.html": ["ng-html2js"] plugins: ["karma-*"] if process.env.TRAVIS buildLabel = "TRAVIS ##{process.env.TRAVIS_BUILD_NUMBER} (#{process.env.TRAVIS_BUILD_ID})" config.sauceLabs.build = buildLabel config.sauceLabs.startConnect = false config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER config.transports = ["xhr-polling"] # Taken from AngularJS karma-shared.conf.js # Terrible hack to workaround inflexibility of log4js: # - ignore web-server's 404 warnings, log4js = require("../node_modules/karma/node_modules/log4js") layouts = require("../node_modules/karma/node_modules/log4js/lib/layouts") originalConfigure = log4js.configure log4js.configure = (log4jsConfig) -> consoleAppender = log4jsConfig.appenders.shift() originalResult = originalConfigure.call(log4js, log4jsConfig) layout = layouts.layout(consoleAppender.layout.type, consoleAppender.layout) log4js.addAppender (log) -> msg = log.data[0] # ignore web-server's 404s return if log.categoryName is "web-server" and log.level.levelStr is config.LOG_WARN console.log layout(log) originalResult
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9991505146026611, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-readint.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. # # * Tests to verify we're reading in signed integers correctly # # # * Test 8 bit signed integers # test8 = (clazz) -> data = new clazz(4) data[0] = 0x23 ASSERT.equal 0x23, data.readInt8(0) data[0] = 0xff ASSERT.equal -1, data.readInt8(0) data[0] = 0x87 data[1] = 0xab data[2] = 0x7c data[3] = 0xef ASSERT.equal -121, data.readInt8(0) ASSERT.equal -85, data.readInt8(1) ASSERT.equal 124, data.readInt8(2) ASSERT.equal -17, data.readInt8(3) return test16 = (clazz) -> buffer = new clazz(6) buffer[0] = 0x16 buffer[1] = 0x79 ASSERT.equal 0x1679, buffer.readInt16BE(0) ASSERT.equal 0x7916, buffer.readInt16LE(0) buffer[0] = 0xff buffer[1] = 0x80 ASSERT.equal -128, buffer.readInt16BE(0) ASSERT.equal -32513, buffer.readInt16LE(0) # test offset with weenix buffer[0] = 0x77 buffer[1] = 0x65 buffer[2] = 0x65 buffer[3] = 0x6e buffer[4] = 0x69 buffer[5] = 0x78 ASSERT.equal 0x7765, buffer.readInt16BE(0) ASSERT.equal 0x6565, buffer.readInt16BE(1) ASSERT.equal 0x656e, buffer.readInt16BE(2) ASSERT.equal 0x6e69, buffer.readInt16BE(3) ASSERT.equal 0x6978, buffer.readInt16BE(4) ASSERT.equal 0x6577, buffer.readInt16LE(0) ASSERT.equal 0x6565, buffer.readInt16LE(1) ASSERT.equal 0x6e65, buffer.readInt16LE(2) ASSERT.equal 0x696e, buffer.readInt16LE(3) ASSERT.equal 0x7869, buffer.readInt16LE(4) return test32 = (clazz) -> buffer = new clazz(6) buffer[0] = 0x43 buffer[1] = 0x53 buffer[2] = 0x16 buffer[3] = 0x79 ASSERT.equal 0x43531679, buffer.readInt32BE(0) ASSERT.equal 0x79165343, buffer.readInt32LE(0) buffer[0] = 0xff buffer[1] = 0xfe buffer[2] = 0xef buffer[3] = 0xfa ASSERT.equal -69638, buffer.readInt32BE(0) ASSERT.equal -84934913, buffer.readInt32LE(0) buffer[0] = 0x42 buffer[1] = 0xc3 buffer[2] = 0x95 buffer[3] = 0xa9 buffer[4] = 0x36 buffer[5] = 0x17 ASSERT.equal 0x42c395a9, buffer.readInt32BE(0) ASSERT.equal -1013601994, buffer.readInt32BE(1) ASSERT.equal -1784072681, buffer.readInt32BE(2) ASSERT.equal -1449802942, buffer.readInt32LE(0) ASSERT.equal 917083587, buffer.readInt32LE(1) ASSERT.equal 389458325, buffer.readInt32LE(2) return common = require("../common") ASSERT = require("assert") test8 Buffer test16 Buffer test32 Buffer
218363
# 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. # # * Tests to verify we're reading in signed integers correctly # # # * Test 8 bit signed integers # test8 = (clazz) -> data = new clazz(4) data[0] = 0x23 ASSERT.equal 0x23, data.readInt8(0) data[0] = 0xff ASSERT.equal -1, data.readInt8(0) data[0] = 0x87 data[1] = 0xab data[2] = 0x7c data[3] = 0xef ASSERT.equal -121, data.readInt8(0) ASSERT.equal -85, data.readInt8(1) ASSERT.equal 124, data.readInt8(2) ASSERT.equal -17, data.readInt8(3) return test16 = (clazz) -> buffer = new clazz(6) buffer[0] = 0x16 buffer[1] = 0x79 ASSERT.equal 0x1679, buffer.readInt16BE(0) ASSERT.equal 0x7916, buffer.readInt16LE(0) buffer[0] = 0xff buffer[1] = 0x80 ASSERT.equal -128, buffer.readInt16BE(0) ASSERT.equal -32513, buffer.readInt16LE(0) # test offset with weenix buffer[0] = 0x77 buffer[1] = 0x65 buffer[2] = 0x65 buffer[3] = 0x6e buffer[4] = 0x69 buffer[5] = 0x78 ASSERT.equal 0x7765, buffer.readInt16BE(0) ASSERT.equal 0x6565, buffer.readInt16BE(1) ASSERT.equal 0x656e, buffer.readInt16BE(2) ASSERT.equal 0x6e69, buffer.readInt16BE(3) ASSERT.equal 0x6978, buffer.readInt16BE(4) ASSERT.equal 0x6577, buffer.readInt16LE(0) ASSERT.equal 0x6565, buffer.readInt16LE(1) ASSERT.equal 0x6e65, buffer.readInt16LE(2) ASSERT.equal 0x696e, buffer.readInt16LE(3) ASSERT.equal 0x7869, buffer.readInt16LE(4) return test32 = (clazz) -> buffer = new clazz(6) buffer[0] = 0x43 buffer[1] = 0x53 buffer[2] = 0x16 buffer[3] = 0x79 ASSERT.equal 0x43531679, buffer.readInt32BE(0) ASSERT.equal 0x79165343, buffer.readInt32LE(0) buffer[0] = 0xff buffer[1] = 0xfe buffer[2] = 0xef buffer[3] = 0xfa ASSERT.equal -69638, buffer.readInt32BE(0) ASSERT.equal -84934913, buffer.readInt32LE(0) buffer[0] = 0x42 buffer[1] = 0xc3 buffer[2] = 0x95 buffer[3] = 0xa9 buffer[4] = 0x36 buffer[5] = 0x17 ASSERT.equal 0x42c395a9, buffer.readInt32BE(0) ASSERT.equal -1013601994, buffer.readInt32BE(1) ASSERT.equal -1784072681, buffer.readInt32BE(2) ASSERT.equal -1449802942, buffer.readInt32LE(0) ASSERT.equal 917083587, buffer.readInt32LE(1) ASSERT.equal 389458325, buffer.readInt32LE(2) return common = require("../common") ASSERT = require("assert") test8 Buffer test16 Buffer test32 Buffer
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. # # * Tests to verify we're reading in signed integers correctly # # # * Test 8 bit signed integers # test8 = (clazz) -> data = new clazz(4) data[0] = 0x23 ASSERT.equal 0x23, data.readInt8(0) data[0] = 0xff ASSERT.equal -1, data.readInt8(0) data[0] = 0x87 data[1] = 0xab data[2] = 0x7c data[3] = 0xef ASSERT.equal -121, data.readInt8(0) ASSERT.equal -85, data.readInt8(1) ASSERT.equal 124, data.readInt8(2) ASSERT.equal -17, data.readInt8(3) return test16 = (clazz) -> buffer = new clazz(6) buffer[0] = 0x16 buffer[1] = 0x79 ASSERT.equal 0x1679, buffer.readInt16BE(0) ASSERT.equal 0x7916, buffer.readInt16LE(0) buffer[0] = 0xff buffer[1] = 0x80 ASSERT.equal -128, buffer.readInt16BE(0) ASSERT.equal -32513, buffer.readInt16LE(0) # test offset with weenix buffer[0] = 0x77 buffer[1] = 0x65 buffer[2] = 0x65 buffer[3] = 0x6e buffer[4] = 0x69 buffer[5] = 0x78 ASSERT.equal 0x7765, buffer.readInt16BE(0) ASSERT.equal 0x6565, buffer.readInt16BE(1) ASSERT.equal 0x656e, buffer.readInt16BE(2) ASSERT.equal 0x6e69, buffer.readInt16BE(3) ASSERT.equal 0x6978, buffer.readInt16BE(4) ASSERT.equal 0x6577, buffer.readInt16LE(0) ASSERT.equal 0x6565, buffer.readInt16LE(1) ASSERT.equal 0x6e65, buffer.readInt16LE(2) ASSERT.equal 0x696e, buffer.readInt16LE(3) ASSERT.equal 0x7869, buffer.readInt16LE(4) return test32 = (clazz) -> buffer = new clazz(6) buffer[0] = 0x43 buffer[1] = 0x53 buffer[2] = 0x16 buffer[3] = 0x79 ASSERT.equal 0x43531679, buffer.readInt32BE(0) ASSERT.equal 0x79165343, buffer.readInt32LE(0) buffer[0] = 0xff buffer[1] = 0xfe buffer[2] = 0xef buffer[3] = 0xfa ASSERT.equal -69638, buffer.readInt32BE(0) ASSERT.equal -84934913, buffer.readInt32LE(0) buffer[0] = 0x42 buffer[1] = 0xc3 buffer[2] = 0x95 buffer[3] = 0xa9 buffer[4] = 0x36 buffer[5] = 0x17 ASSERT.equal 0x42c395a9, buffer.readInt32BE(0) ASSERT.equal -1013601994, buffer.readInt32BE(1) ASSERT.equal -1784072681, buffer.readInt32BE(2) ASSERT.equal -1449802942, buffer.readInt32LE(0) ASSERT.equal 917083587, buffer.readInt32LE(1) ASSERT.equal 389458325, buffer.readInt32LE(2) return common = require("../common") ASSERT = require("assert") test8 Buffer test16 Buffer test32 Buffer
[ { "context": "/bla', 'bla'\n testRoute '/user/:user', 'user/joe'\n testRoute '/user/:user', 'user/satriani'\n\n", "end": 1825, "score": 0.9544992446899414, "start": 1822, "tag": "USERNAME", "value": "joe" }, { "context": ", 'user/joe'\n testRoute '/user/:user', 'user/s...
este/router/router_test.coffee
vlkous/este-library
0
suite 'este.Router', -> Router = este.Router history = null gestureHandler = null router = null setup -> history = setToken: (token) -> dispatchHistoryNavigateEvent token, false dispose: -> setEnabled: -> addEventListener: -> gestureHandler = dispose: -> addEventListener: -> getElement: -> document.createElement 'div' router = new Router history, gestureHandler dispatchHistoryNavigateEvent = (token, isNavigation = true) -> goog.events.fireListeners history, 'navigate', false, type: 'navigate' token: token isNavigation: isNavigation dispatchGestureHandlerTapEvent = (target) -> goog.events.fireListeners gestureHandler, 'tap', false, type: 'tap' target: target preventDefault: -> suite 'constructor', -> test 'should work', -> assert.instanceOf router, este.Router suite 'start', -> test 'should call history.setEnabled with true', (done) -> history.setEnabled = (enabled) -> assert.isTrue enabled done() router.start() suite 'dispose', -> test 'should call history.dispose', (done) -> history.dispose = -> done() router.dispose() test 'should call gestureHandler.dispose', (done) -> gestureHandler.dispose = -> done() router.dispose() suite 'routing via history navigate event', -> suite 'show should work', -> testRoute = (path, token) -> test "path: '#{path}', token: '#{token}'", (done) -> router.add path, (params, isNavigation) -> assert.isTrue isNavigation done() router.start() dispatchHistoryNavigateEvent token testRoute '/foo', 'foo' testRoute '/bla', 'bla' testRoute '/user/:user', 'user/joe' testRoute '/user/:user', 'user/satriani' suite 'show should not be called with sensitive true', -> testRoute = (path, token) -> test "path: '#{path}' should match token: '#{token}'", (done) -> router.add path, (->), hide: -> done() , sensitive: true router.start() dispatchHistoryNavigateEvent token testRoute '/Foo', 'foo' testRoute '/Bla', 'bla' testRoute '/User/:user', 'user/joe' testRoute '/User/:user', 'user/satriani' suite 'hide should work', -> testRoute = (path, token) -> test "path: '#{path}' should match token: '#{token}'", (done) -> router.add path, (->), hide: -> done() router.start() dispatchHistoryNavigateEvent token testRoute '/foo', 'bla' testRoute '/bla', 'foo' testRoute '/user/:user', 'product/joe' testRoute '/user/:user', 'product/satriani' suite 'exception in callback', -> test 'should not break processing', -> count = 0 router.add '/foo', -> count++ throw Error 'Error' router.add '/foo', -> count++ router.start() dispatchHistoryNavigateEvent 'foo' assert.equal count, 2 suite 'routing via gestureHandler tap event', -> suite 'show should work', -> testRoute = (path, token) -> test "path: '#{path}', token: '#{token}'", (done) -> setTokenCalled = false fn = history.setToken history.setToken = -> setTokenCalled = true fn.apply @, arguments router.add path, (params, isNavigation) -> assert.isFalse isNavigation assert.isTrue setTokenCalled done() router.start() dispatchGestureHandlerTapEvent nodeType: 1 hasAttribute: -> getAttribute: (name) -> return token if name == 'href' testRoute '/foo', 'foo' testRoute '/bla', 'bla' testRoute '/user/:user', 'user/joe' testRoute '/user/:user', 'user/satriani' suite 'show should work, but should not call history.setToken', -> testRoute = (path, token) -> test "path: '#{path}', token: '#{token}'", (done) -> router.navigateImmediately = false setTokenCalled = false fn = history.setToken history.setToken = -> setTokenCalled = true fn.apply @, arguments router.add path, (params, isNavigation) -> assert.isFalse isNavigation assert.isFalse setTokenCalled done() router.start() dispatchGestureHandlerTapEvent nodeType: 1 hasAttribute: -> getAttribute: (name) -> return token if name == 'href' testRoute '/foo', 'foo' testRoute '/bla', 'bla' testRoute '/user/:user', 'user/joe' testRoute '/user/:user', 'user/satriani' suite 'show should work in parent', -> testRoute = (path, token) -> test "path: '#{path}', token: '#{token}'", (done) -> router.add path, -> done() router.start() dispatchGestureHandlerTapEvent nodeType: 1 hasAttribute: -> getAttribute: -> parentNode: nodeType: 1 hasAttribute: -> getAttribute: (name) -> return token if name == 'href' testRoute '/foo', 'foo' testRoute '/bla', 'bla' testRoute '/user/:user', 'user/joe' testRoute '/user/:user', 'user/satriani' suite 'hide should work', -> testRoute = (path, token) -> test "path: '#{path}' should match token: '#{token}'", (done) -> router.add path, (->), hide: -> done() router.start() dispatchGestureHandlerTapEvent nodeType: 1 hasAttribute: -> getAttribute: (name) -> return token if name == 'href' testRoute '/foo', 'bla' testRoute '/bla', 'foo' testRoute '/user/:user', 'product/joe' testRoute '/user/:user', 'product/satriani' suite 'remove route', -> test 'should work for string route', -> called = false router.add '/user/:user', (params) -> assert.equal params['user'], 'joe' called = true router.start() router.remove 'user/:user' dispatchHistoryNavigateEvent 'users/joe' assert.isFalse called suite 'navigate', -> test 'should call setToken on history object', (done) -> history.setToken = (token) -> assert.equal token, 'foo' done() router.navigate 'foo' suite 'pathNavigate user/:name, name: joe', -> test 'should call setToken on history object', (done) -> history.setToken = (token) -> assert.equal token, 'user/joe' done() router.start() router.add '/user/:name', -> router.pathNavigate 'user/:name', name: 'joe' test 'should call router show', -> called = false router.start() router.add '/user/:name', -> called = true router.pathNavigate 'user/:name', name: 'joe' assert.isTrue called suite 'pathNavigate user/:name, name: joe, true', -> test 'should call setToken on history object', (done) -> history.setToken = (token) -> assert.equal token, 'user/joe' done() router.start() router.add '/user/:name', -> router.pathNavigate 'user/:name', name: 'joe', true test 'should not call router show', -> called = false router.start() router.add '/user/:name', -> called = true router.pathNavigate 'user/:name', name: 'joe', true assert.isFalse called suite 'only first route from two or more matched', -> test 'should be processed', -> # arrange calls = '' router.add '/foo/bar', (-> calls += 1) router.add '/foo/*', (-> calls += 2), hide: -> calls += 3 router.start() # act dispatchHistoryNavigateEvent 'foo/bar' # assert assert.equal calls, 13
33814
suite 'este.Router', -> Router = este.Router history = null gestureHandler = null router = null setup -> history = setToken: (token) -> dispatchHistoryNavigateEvent token, false dispose: -> setEnabled: -> addEventListener: -> gestureHandler = dispose: -> addEventListener: -> getElement: -> document.createElement 'div' router = new Router history, gestureHandler dispatchHistoryNavigateEvent = (token, isNavigation = true) -> goog.events.fireListeners history, 'navigate', false, type: 'navigate' token: token isNavigation: isNavigation dispatchGestureHandlerTapEvent = (target) -> goog.events.fireListeners gestureHandler, 'tap', false, type: 'tap' target: target preventDefault: -> suite 'constructor', -> test 'should work', -> assert.instanceOf router, este.Router suite 'start', -> test 'should call history.setEnabled with true', (done) -> history.setEnabled = (enabled) -> assert.isTrue enabled done() router.start() suite 'dispose', -> test 'should call history.dispose', (done) -> history.dispose = -> done() router.dispose() test 'should call gestureHandler.dispose', (done) -> gestureHandler.dispose = -> done() router.dispose() suite 'routing via history navigate event', -> suite 'show should work', -> testRoute = (path, token) -> test "path: '#{path}', token: '#{token}'", (done) -> router.add path, (params, isNavigation) -> assert.isTrue isNavigation done() router.start() dispatchHistoryNavigateEvent token testRoute '/foo', 'foo' testRoute '/bla', 'bla' testRoute '/user/:user', 'user/joe' testRoute '/user/:user', 'user/satriani' suite 'show should not be called with sensitive true', -> testRoute = (path, token) -> test "path: '#{path}' should match token: '#{token}'", (done) -> router.add path, (->), hide: -> done() , sensitive: true router.start() dispatchHistoryNavigateEvent token testRoute '/Foo', 'foo' testRoute '/Bla', 'bla' testRoute '/User/:user', 'user/joe' testRoute '/User/:user', 'user/satriani' suite 'hide should work', -> testRoute = (path, token) -> test "path: '#{path}' should match token: '#{token}'", (done) -> router.add path, (->), hide: -> done() router.start() dispatchHistoryNavigateEvent token testRoute '/foo', 'bla' testRoute '/bla', 'foo' testRoute '/user/:user', 'product/joe' testRoute '/user/:user', 'product/satriani' suite 'exception in callback', -> test 'should not break processing', -> count = 0 router.add '/foo', -> count++ throw Error 'Error' router.add '/foo', -> count++ router.start() dispatchHistoryNavigateEvent 'foo' assert.equal count, 2 suite 'routing via gestureHandler tap event', -> suite 'show should work', -> testRoute = (path, token) -> test "path: '#{path}', token: '#{token}'", (done) -> setTokenCalled = false fn = history.setToken history.setToken = -> setTokenCalled = true fn.apply @, arguments router.add path, (params, isNavigation) -> assert.isFalse isNavigation assert.isTrue setTokenCalled done() router.start() dispatchGestureHandlerTapEvent nodeType: 1 hasAttribute: -> getAttribute: (name) -> return token if name == 'href' testRoute '/foo', 'foo' testRoute '/bla', 'bla' testRoute '/user/:user', 'user/joe' testRoute '/user/:user', 'user/satriani' suite 'show should work, but should not call history.setToken', -> testRoute = (path, token) -> test "path: '#{path}', token: '#{token}'", (done) -> router.navigateImmediately = false setTokenCalled = false fn = history.setToken history.setToken = -> setTokenCalled = true fn.apply @, arguments router.add path, (params, isNavigation) -> assert.isFalse isNavigation assert.isFalse setTokenCalled done() router.start() dispatchGestureHandlerTapEvent nodeType: 1 hasAttribute: -> getAttribute: (name) -> return token if name == 'href' testRoute '/foo', 'foo' testRoute '/bla', 'bla' testRoute '/user/:user', 'user/joe' testRoute '/user/:user', 'user/satriani' suite 'show should work in parent', -> testRoute = (path, token) -> test "path: '#{path}', token: '#{token}'", (done) -> router.add path, -> done() router.start() dispatchGestureHandlerTapEvent nodeType: 1 hasAttribute: -> getAttribute: -> parentNode: nodeType: 1 hasAttribute: -> getAttribute: (name) -> return token if name == 'href' testRoute '/foo', 'foo' testRoute '/bla', 'bla' testRoute '/user/:user', 'user/joe' testRoute '/user/:user', 'user/satriani' suite 'hide should work', -> testRoute = (path, token) -> test "path: '#{path}' should match token: '#{token}'", (done) -> router.add path, (->), hide: -> done() router.start() dispatchGestureHandlerTapEvent nodeType: 1 hasAttribute: -> getAttribute: (name) -> return token if name == 'href' testRoute '/foo', 'bla' testRoute '/bla', 'foo' testRoute '/user/:user', 'product/joe' testRoute '/user/:user', 'product/satriani' suite 'remove route', -> test 'should work for string route', -> called = false router.add '/user/:user', (params) -> assert.equal params['user'], 'joe' called = true router.start() router.remove 'user/:user' dispatchHistoryNavigateEvent 'users/joe' assert.isFalse called suite 'navigate', -> test 'should call setToken on history object', (done) -> history.setToken = (token) -> assert.equal token, 'foo' done() router.navigate 'foo' suite 'pathNavigate user/:name, name: <NAME>', -> test 'should call setToken on history object', (done) -> history.setToken = (token) -> assert.equal token, 'user/<NAME>' done() router.start() router.add '/user/:name', -> router.pathNavigate 'user/:name', name: '<NAME>' test 'should call router show', -> called = false router.start() router.add '/user/:name', -> called = true router.pathNavigate 'user/:name', name: '<NAME>' assert.isTrue called suite 'pathNavigate user/:name, name: <NAME>, true', -> test 'should call setToken on history object', (done) -> history.setToken = (token) -> assert.equal token, 'user/<NAME>' done() router.start() router.add '/user/:name', -> router.pathNavigate 'user/:name', name: '<NAME>', true test 'should not call router show', -> called = false router.start() router.add '/user/:name', -> called = true router.pathNavigate 'user/:name', name: '<NAME>', true assert.isFalse called suite 'only first route from two or more matched', -> test 'should be processed', -> # arrange calls = '' router.add '/foo/bar', (-> calls += 1) router.add '/foo/*', (-> calls += 2), hide: -> calls += 3 router.start() # act dispatchHistoryNavigateEvent 'foo/bar' # assert assert.equal calls, 13
true
suite 'este.Router', -> Router = este.Router history = null gestureHandler = null router = null setup -> history = setToken: (token) -> dispatchHistoryNavigateEvent token, false dispose: -> setEnabled: -> addEventListener: -> gestureHandler = dispose: -> addEventListener: -> getElement: -> document.createElement 'div' router = new Router history, gestureHandler dispatchHistoryNavigateEvent = (token, isNavigation = true) -> goog.events.fireListeners history, 'navigate', false, type: 'navigate' token: token isNavigation: isNavigation dispatchGestureHandlerTapEvent = (target) -> goog.events.fireListeners gestureHandler, 'tap', false, type: 'tap' target: target preventDefault: -> suite 'constructor', -> test 'should work', -> assert.instanceOf router, este.Router suite 'start', -> test 'should call history.setEnabled with true', (done) -> history.setEnabled = (enabled) -> assert.isTrue enabled done() router.start() suite 'dispose', -> test 'should call history.dispose', (done) -> history.dispose = -> done() router.dispose() test 'should call gestureHandler.dispose', (done) -> gestureHandler.dispose = -> done() router.dispose() suite 'routing via history navigate event', -> suite 'show should work', -> testRoute = (path, token) -> test "path: '#{path}', token: '#{token}'", (done) -> router.add path, (params, isNavigation) -> assert.isTrue isNavigation done() router.start() dispatchHistoryNavigateEvent token testRoute '/foo', 'foo' testRoute '/bla', 'bla' testRoute '/user/:user', 'user/joe' testRoute '/user/:user', 'user/satriani' suite 'show should not be called with sensitive true', -> testRoute = (path, token) -> test "path: '#{path}' should match token: '#{token}'", (done) -> router.add path, (->), hide: -> done() , sensitive: true router.start() dispatchHistoryNavigateEvent token testRoute '/Foo', 'foo' testRoute '/Bla', 'bla' testRoute '/User/:user', 'user/joe' testRoute '/User/:user', 'user/satriani' suite 'hide should work', -> testRoute = (path, token) -> test "path: '#{path}' should match token: '#{token}'", (done) -> router.add path, (->), hide: -> done() router.start() dispatchHistoryNavigateEvent token testRoute '/foo', 'bla' testRoute '/bla', 'foo' testRoute '/user/:user', 'product/joe' testRoute '/user/:user', 'product/satriani' suite 'exception in callback', -> test 'should not break processing', -> count = 0 router.add '/foo', -> count++ throw Error 'Error' router.add '/foo', -> count++ router.start() dispatchHistoryNavigateEvent 'foo' assert.equal count, 2 suite 'routing via gestureHandler tap event', -> suite 'show should work', -> testRoute = (path, token) -> test "path: '#{path}', token: '#{token}'", (done) -> setTokenCalled = false fn = history.setToken history.setToken = -> setTokenCalled = true fn.apply @, arguments router.add path, (params, isNavigation) -> assert.isFalse isNavigation assert.isTrue setTokenCalled done() router.start() dispatchGestureHandlerTapEvent nodeType: 1 hasAttribute: -> getAttribute: (name) -> return token if name == 'href' testRoute '/foo', 'foo' testRoute '/bla', 'bla' testRoute '/user/:user', 'user/joe' testRoute '/user/:user', 'user/satriani' suite 'show should work, but should not call history.setToken', -> testRoute = (path, token) -> test "path: '#{path}', token: '#{token}'", (done) -> router.navigateImmediately = false setTokenCalled = false fn = history.setToken history.setToken = -> setTokenCalled = true fn.apply @, arguments router.add path, (params, isNavigation) -> assert.isFalse isNavigation assert.isFalse setTokenCalled done() router.start() dispatchGestureHandlerTapEvent nodeType: 1 hasAttribute: -> getAttribute: (name) -> return token if name == 'href' testRoute '/foo', 'foo' testRoute '/bla', 'bla' testRoute '/user/:user', 'user/joe' testRoute '/user/:user', 'user/satriani' suite 'show should work in parent', -> testRoute = (path, token) -> test "path: '#{path}', token: '#{token}'", (done) -> router.add path, -> done() router.start() dispatchGestureHandlerTapEvent nodeType: 1 hasAttribute: -> getAttribute: -> parentNode: nodeType: 1 hasAttribute: -> getAttribute: (name) -> return token if name == 'href' testRoute '/foo', 'foo' testRoute '/bla', 'bla' testRoute '/user/:user', 'user/joe' testRoute '/user/:user', 'user/satriani' suite 'hide should work', -> testRoute = (path, token) -> test "path: '#{path}' should match token: '#{token}'", (done) -> router.add path, (->), hide: -> done() router.start() dispatchGestureHandlerTapEvent nodeType: 1 hasAttribute: -> getAttribute: (name) -> return token if name == 'href' testRoute '/foo', 'bla' testRoute '/bla', 'foo' testRoute '/user/:user', 'product/joe' testRoute '/user/:user', 'product/satriani' suite 'remove route', -> test 'should work for string route', -> called = false router.add '/user/:user', (params) -> assert.equal params['user'], 'joe' called = true router.start() router.remove 'user/:user' dispatchHistoryNavigateEvent 'users/joe' assert.isFalse called suite 'navigate', -> test 'should call setToken on history object', (done) -> history.setToken = (token) -> assert.equal token, 'foo' done() router.navigate 'foo' suite 'pathNavigate user/:name, name: PI:NAME:<NAME>END_PI', -> test 'should call setToken on history object', (done) -> history.setToken = (token) -> assert.equal token, 'user/PI:PASSWORD:<NAME>END_PI' done() router.start() router.add '/user/:name', -> router.pathNavigate 'user/:name', name: 'PI:NAME:<NAME>END_PI' test 'should call router show', -> called = false router.start() router.add '/user/:name', -> called = true router.pathNavigate 'user/:name', name: 'PI:NAME:<NAME>END_PI' assert.isTrue called suite 'pathNavigate user/:name, name: PI:NAME:<NAME>END_PI, true', -> test 'should call setToken on history object', (done) -> history.setToken = (token) -> assert.equal token, 'user/PI:PASSWORD:<NAME>END_PI' done() router.start() router.add '/user/:name', -> router.pathNavigate 'user/:name', name: 'PI:NAME:<NAME>END_PI', true test 'should not call router show', -> called = false router.start() router.add '/user/:name', -> called = true router.pathNavigate 'user/:name', name: 'PI:NAME:<NAME>END_PI', true assert.isFalse called suite 'only first route from two or more matched', -> test 'should be processed', -> # arrange calls = '' router.add '/foo/bar', (-> calls += 1) router.add '/foo/*', (-> calls += 2), hide: -> calls += 3 router.start() # act dispatchHistoryNavigateEvent 'foo/bar' # assert assert.equal calls, 13
[ { "context": "lms by release date\", t:\"Oldest\", b:\"Latest\", a:[\"Citizen Kane\", \"James Bond: Dr. No\", \"The Good, the Bad and th", "end": 2578, "score": 0.9997458457946777, "start": 2566, "tag": "NAME", "value": "Citizen Kane" }, { "context": "ate\", t:\"Oldest\", b:\"Latest\...
util.common.coffee
Nouder123/WhoKnows
0
Db = require 'db' Plugin = require 'plugin' {tr} = require 'i18n' Rand = require 'rand' exports.debug = debug = -> false # Determines duration of the round started at 'currentTime' # This comes from the Ranking Game plugin exports.getRoundDuration = (currentTime) -> return false if !currentTime duration = 6*3600 # six hours while 22 <= (hrs = (new Date((currentTime+duration)*1000)).getHours()) or hrs <= 9 duration += 6*3600 return duration exports.getQuestion = (roundId) -> id = Db.shared.peek 'rounds', roundId, 'qid' return questions()[id].q exports.getOrderTitles = (roundId) -> id = Db.shared.peek 'rounds', roundId, 'qid' q = questions()[id] return [q.t, q.b] # we show key applied to the possible answers exports.getOptions = (roundId) -> a = questions()[Db.shared.peek 'rounds', roundId, 'qid'].a k = Db.shared.peek 'rounds', roundId, 'key' if debug() then log "getOptions; k:", k, "q:", a return [a[k[0]], a[k[1]], a[k[2]], a[k[3]]] # the solution is index of options in key exports.getSolution = (roundId) -> k = Db.shared.peek 'rounds', roundId, 'key' o = Db.shared.peek 'rounds', roundId, 'options' r = [] for i in [0..3] r[i] = k.indexOf(o[i]) if debug() then log "getSolution", roundId, k, o, ": ", r return r # the key is a random order of [0..3] in options exports.generateKey = (o) -> # o for options a = [0,1,2,3] s = [] for x in [1..4] rnd = Math.floor(Math.random()*a.length) s.push +(a.splice(rnd,1)) r = [o[s[0]], o[s[1]], o[s[2]], o[s[3]]] if debug() then log "generateKey:", o, s, r return r exports.makeRndOptions = (qId) -> # provide this in the 'correct' order. The client will rearrange them at random. a = questions()[qId].a available = [0..a.length-1] r = [] for i in [1..4] r.push +available.splice(Math.floor(Math.random()*available.length), 1) r.sort() # always in acending order (for that is the correct order) if debug() then log "makeRndOptions, available:", a.length-1, "options:", r return r exports.getWinner = (roundId) -> Db.shared.peek 'rounds', roundId, 'winner' exports.getVotes = (roundId, userId) -> votes = Db.shared.get('rounds', roundId, 'votes', userId)||[] r = [] for k,v of votes if v is true r.push [k,0] else if v > 0 r.push [k,"+1"] else r.push [k,"-1"] return r exports.questions = questions = -> [ # WARNING: indices are used, so don't remove items from this array (and add new questions at the end) # [0]: question, [1-x]: the answers in the correct order {q:"Order Films by release date", t:"Oldest", b:"Latest", a:["Citizen Kane", "James Bond: Dr. No", "The Good, the Bad and the Ugly", "The Godfather", "Jaws", "Star Wars: A New Hope", "ET", "Jurassic Park", "Schindler\'s List"]} # 1984, 1963, 1968, 1972, 1975, 1977, 1982, 1993, 1994 {q:"Order buildings by height", t:"Highest", b:"Lowest", a:["Burj Khalifa", "Petronas Twin Towers", "Empire State Building", "Eiffel Tower", "Great Pyramid of Giza", "Big Ben", "Statue of Liberty", "Sydney Opera House", "Leaning Tower of Pisa"]} #828, 452, 381, 300, 139, 96, 93, 65, 56 {q:"Order wonders by construction date", t:"Oldest", b:"Newest", a:["Great Pyramid of Giza", "Great Wall of China", "Petra", "Colosseum", "Chichen Itza", "Machu Picchu", "Taj Mahal", "Christ the Redeemer"]} {q:"Order TV series on broadcast date", t:"Oldest", b:"Newest", a:["Star Trek: The Original Series", "The Bold and the Beautiful", "The Simpsons", "The X-Files", "South Park", "The Big Bang Theory", "Scrubs", "Futurama", "A Game of Thrones"]} # 1966, 1987, 1989, 1998, 2000, 2004, 2007, 2010, 2011 {q:"Order movies by IMDb rating", t:"Highest rated", b:"Lowest rated", a:["The Shawshank Redemption", "The Godfather", "The Dark Knight", "Pulp Fiction", "The Lord of the Rings: The Fellowship of the Ring", "Citizen Kane", "Toy Story", "Life of Brian", "Kill Bill"]} {q:"Order Disney films on release date", t: "Oldest", b:"Latest", a:["Snow White and the Seven Dwarfs", "Bambi", "Alice in Wonderland", "One Hundred and One Dalmatians", "The Aristocats", "The Little Mermaid", "Aladdin", "The Lion King", "The Princess and the Frog"]} {q:"Order Pixar films on release date", t:"Oldest", b:"Latest", a:["Toy Story", "A Bug's Life", "Monsters, Inc.", "Finding Nemo", "The Incredibles", "WALL-E", "Up", "Brave"]} {q:"Order Presidents of the United States Chronologically", t:"First", b:"Last", a:["George Washington", "Abraham Lincoln", "Franklin D. Roosevelt", "John F. Kennedy", "Richard Nixon", "Bill Clinton", "George W Bush (jr.)", "Barack Obama"]} {q:"Order countries by population", t:"Highest population", b:"Lowest population", a:["China", "India", "United States", "Brazil", "Japan", "Germany", "Iran", "Canada", "Iceland"]} {q:"Order weight per liter", t:"Lightest", b:"Heaviest", a:["Petrol", "Alcohol", "Olive oil", "Diesel", "Sunflower oil", "Water", "Beer", "Milk", "Sea water", "Citric acid"]} {q:"Order creation chronologically according to the Bible", t:"First", b:"Last", a:["Earth", "Water", "Land", "Sun", "Birds", "Man"]} {q:"Order these balls by size", t:"Smallest", b:"Biggest", a:["Table tennis ball", "Golf ball", "Pool ball", "Tennis ball", "Baseball ball", "Soccer ball", "Basketball ball"]} {q:"Order by invention date", t:"First", b:"Last", a:["Stone tools", "The wheel", "The alphabet", "Coins", "Windmill", "Woodblock printing", "Toilet Paper", "Gunpowder", "Soap", "Telescope", "Steam Engine", "Light Bulb"]} # WARNING: always add new questions to the end of this array ] # questions that are deemed to difficult: # ["Order Star Wars movies by release date", "A New Hope", "The Empire Strikes Back", "Return of the Jedi", "The Phantom Menace", "Attack of the Clones", "Revenge of the Sith", "The Force Awakens"] # ["Order by Electromagnetic Frequency", "Radio waves", "Microwave radiation", "Infrared radiation", "Green light", "Blue light", "Ultraviolet radiation", "X-ray radiation", "Gamma radiation"] # distance earth # distance space # size space # wk soccer wins exports.inverseCheck = -> [5,0,-3,"butt",-4,"miter",-5,4,4,2,0.019589437957492035,0.019589437957492035,2,2,0,0.0018773653552219825,2,2,0,0,4,2,1.0666666513406717,1.0666666513406717,2,2,-398.48159,-658.25586,5,0,-2,1,-6,1,7,0,10,2,398.48159,658.25586,11,2,398.48159,705.93359,11,2,446.33901,705.93359,11,2,446.33901,658.25586,11,2,398.48159,658.25586,12,0,10,2,437.2101,668.33789,11,2,440.01088,671.13672,11,2,416.01088,695.13672,11,2,404.81166,683.9375,11,2,407.61049,681.13672,11,2,416.01088,689.53711,11,2,437.2101,668.33789,12,0,8,1,"nonzero",6,0,6,0]
17217
Db = require 'db' Plugin = require 'plugin' {tr} = require 'i18n' Rand = require 'rand' exports.debug = debug = -> false # Determines duration of the round started at 'currentTime' # This comes from the Ranking Game plugin exports.getRoundDuration = (currentTime) -> return false if !currentTime duration = 6*3600 # six hours while 22 <= (hrs = (new Date((currentTime+duration)*1000)).getHours()) or hrs <= 9 duration += 6*3600 return duration exports.getQuestion = (roundId) -> id = Db.shared.peek 'rounds', roundId, 'qid' return questions()[id].q exports.getOrderTitles = (roundId) -> id = Db.shared.peek 'rounds', roundId, 'qid' q = questions()[id] return [q.t, q.b] # we show key applied to the possible answers exports.getOptions = (roundId) -> a = questions()[Db.shared.peek 'rounds', roundId, 'qid'].a k = Db.shared.peek 'rounds', roundId, 'key' if debug() then log "getOptions; k:", k, "q:", a return [a[k[0]], a[k[1]], a[k[2]], a[k[3]]] # the solution is index of options in key exports.getSolution = (roundId) -> k = Db.shared.peek 'rounds', roundId, 'key' o = Db.shared.peek 'rounds', roundId, 'options' r = [] for i in [0..3] r[i] = k.indexOf(o[i]) if debug() then log "getSolution", roundId, k, o, ": ", r return r # the key is a random order of [0..3] in options exports.generateKey = (o) -> # o for options a = [0,1,2,3] s = [] for x in [1..4] rnd = Math.floor(Math.random()*a.length) s.push +(a.splice(rnd,1)) r = [o[s[0]], o[s[1]], o[s[2]], o[s[3]]] if debug() then log "generateKey:", o, s, r return r exports.makeRndOptions = (qId) -> # provide this in the 'correct' order. The client will rearrange them at random. a = questions()[qId].a available = [0..a.length-1] r = [] for i in [1..4] r.push +available.splice(Math.floor(Math.random()*available.length), 1) r.sort() # always in acending order (for that is the correct order) if debug() then log "makeRndOptions, available:", a.length-1, "options:", r return r exports.getWinner = (roundId) -> Db.shared.peek 'rounds', roundId, 'winner' exports.getVotes = (roundId, userId) -> votes = Db.shared.get('rounds', roundId, 'votes', userId)||[] r = [] for k,v of votes if v is true r.push [k,0] else if v > 0 r.push [k,"+1"] else r.push [k,"-1"] return r exports.questions = questions = -> [ # WARNING: indices are used, so don't remove items from this array (and add new questions at the end) # [0]: question, [1-x]: the answers in the correct order {q:"Order Films by release date", t:"Oldest", b:"Latest", a:["<NAME>", "<NAME>: Dr. No", "The Good, the Bad and the Ugly", "The Godfather", "Jaws", "Star Wars: A New Hope", "ET", "Jurassic Park", "Schindler\'s List"]} # 1984, 1963, 1968, 1972, 1975, 1977, 1982, 1993, 1994 {q:"Order buildings by height", t:"Highest", b:"Lowest", a:["<NAME>", "Petronas Twin T<NAME>ers", "Empire State Building", "Eiffel Tower", "Great Pyramid of Giza", "Big Ben", "Statue of Liberty", "Sydney Opera House", "Leaning Tower of Pisa"]} #828, 452, 381, 300, 139, 96, 93, 65, 56 {q:"Order wonders by construction date", t:"Oldest", b:"Newest", a:["Great Pyramid of Giza", "Great Wall of China", "Petra", "Colosseum", "<NAME>", "<NAME>", "<NAME>", "Christ the <NAME>"]} {q:"Order TV series on broadcast date", t:"Oldest", b:"Newest", a:["Star Trek: The Original Series", "The Bold and the Beautiful", "The Simpsons", "The X-Files", "South Park", "The Big Bang Theory", "Scrubs", "Futurama", "A Game of Thrones"]} # 1966, 1987, 1989, 1998, 2000, 2004, 2007, 2010, 2011 {q:"Order movies by IMDb rating", t:"Highest rated", b:"Lowest rated", a:["The Shawshank Redemption", "The Godfather", "The Dark Knight", "Pulp Fiction", "The Lord of the Rings: The Fellowship of the Ring", "Citizen Kane", "Toy Story", "Life of Brian", "Kill Bill"]} {q:"Order Disney films on release date", t: "Oldest", b:"Latest", a:["Snow White and the Seven Dwarfs", "Bambi", "Alice in Wonderland", "One Hundred and One Dalmatians", "The Aristocats", "The Little Mermaid", "Aladdin", "The Lion King", "The Princess and the Frog"]} {q:"Order Pixar films on release date", t:"Oldest", b:"Latest", a:["Toy Story", "A Bug's Life", "Monsters, Inc.", "Finding Nemo", "The Incredibles", "WALL-E", "Up", "Brave"]} {q:"Order Presidents of the United States Chronologically", t:"First", b:"Last", a:["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME> (jr.)", "<NAME>"]} {q:"Order countries by population", t:"Highest population", b:"Lowest population", a:["China", "India", "United States", "Brazil", "Japan", "Germany", "Iran", "Canada", "Iceland"]} {q:"Order weight per liter", t:"Lightest", b:"Heaviest", a:["Petrol", "Alcohol", "Olive oil", "Diesel", "Sunflower oil", "Water", "Beer", "Milk", "Sea water", "Citric acid"]} {q:"Order creation chronologically according to the Bible", t:"First", b:"Last", a:["Earth", "Water", "Land", "Sun", "Birds", "Man"]} {q:"Order these balls by size", t:"Smallest", b:"Biggest", a:["Table tennis ball", "Golf ball", "Pool ball", "Tennis ball", "Baseball ball", "Soccer ball", "Basketball ball"]} {q:"Order by invention date", t:"First", b:"Last", a:["Stone tools", "The wheel", "The alphabet", "Coins", "Windmill", "Woodblock printing", "Toilet Paper", "Gunpowder", "Soap", "Telescope", "Steam Engine", "Light Bulb"]} # WARNING: always add new questions to the end of this array ] # questions that are deemed to difficult: # ["Order Star Wars movies by release date", "A New Hope", "The Empire Strikes Back", "Return of the Jedi", "The Phantom Menace", "Attack of the Clones", "Revenge of the Sith", "The Force Awakens"] # ["Order by Electromagnetic Frequency", "Radio waves", "Microwave radiation", "Infrared radiation", "Green light", "Blue light", "Ultraviolet radiation", "X-ray radiation", "Gamma radiation"] # distance earth # distance space # size space # wk soccer wins exports.inverseCheck = -> [5,0,-3,"butt",-4,"miter",-5,4,4,2,0.019589437957492035,0.019589437957492035,2,2,0,0.0018773653552219825,2,2,0,0,4,2,1.0666666513406717,1.0666666513406717,2,2,-398.48159,-658.25586,5,0,-2,1,-6,1,7,0,10,2,398.48159,658.25586,11,2,398.48159,705.93359,11,2,446.33901,705.93359,11,2,446.33901,658.25586,11,2,398.48159,658.25586,12,0,10,2,437.2101,668.33789,11,2,440.01088,671.13672,11,2,416.01088,695.13672,11,2,404.81166,683.9375,11,2,407.61049,681.13672,11,2,416.01088,689.53711,11,2,437.2101,668.33789,12,0,8,1,"nonzero",6,0,6,0]
true
Db = require 'db' Plugin = require 'plugin' {tr} = require 'i18n' Rand = require 'rand' exports.debug = debug = -> false # Determines duration of the round started at 'currentTime' # This comes from the Ranking Game plugin exports.getRoundDuration = (currentTime) -> return false if !currentTime duration = 6*3600 # six hours while 22 <= (hrs = (new Date((currentTime+duration)*1000)).getHours()) or hrs <= 9 duration += 6*3600 return duration exports.getQuestion = (roundId) -> id = Db.shared.peek 'rounds', roundId, 'qid' return questions()[id].q exports.getOrderTitles = (roundId) -> id = Db.shared.peek 'rounds', roundId, 'qid' q = questions()[id] return [q.t, q.b] # we show key applied to the possible answers exports.getOptions = (roundId) -> a = questions()[Db.shared.peek 'rounds', roundId, 'qid'].a k = Db.shared.peek 'rounds', roundId, 'key' if debug() then log "getOptions; k:", k, "q:", a return [a[k[0]], a[k[1]], a[k[2]], a[k[3]]] # the solution is index of options in key exports.getSolution = (roundId) -> k = Db.shared.peek 'rounds', roundId, 'key' o = Db.shared.peek 'rounds', roundId, 'options' r = [] for i in [0..3] r[i] = k.indexOf(o[i]) if debug() then log "getSolution", roundId, k, o, ": ", r return r # the key is a random order of [0..3] in options exports.generateKey = (o) -> # o for options a = [0,1,2,3] s = [] for x in [1..4] rnd = Math.floor(Math.random()*a.length) s.push +(a.splice(rnd,1)) r = [o[s[0]], o[s[1]], o[s[2]], o[s[3]]] if debug() then log "generateKey:", o, s, r return r exports.makeRndOptions = (qId) -> # provide this in the 'correct' order. The client will rearrange them at random. a = questions()[qId].a available = [0..a.length-1] r = [] for i in [1..4] r.push +available.splice(Math.floor(Math.random()*available.length), 1) r.sort() # always in acending order (for that is the correct order) if debug() then log "makeRndOptions, available:", a.length-1, "options:", r return r exports.getWinner = (roundId) -> Db.shared.peek 'rounds', roundId, 'winner' exports.getVotes = (roundId, userId) -> votes = Db.shared.get('rounds', roundId, 'votes', userId)||[] r = [] for k,v of votes if v is true r.push [k,0] else if v > 0 r.push [k,"+1"] else r.push [k,"-1"] return r exports.questions = questions = -> [ # WARNING: indices are used, so don't remove items from this array (and add new questions at the end) # [0]: question, [1-x]: the answers in the correct order {q:"Order Films by release date", t:"Oldest", b:"Latest", a:["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI: Dr. No", "The Good, the Bad and the Ugly", "The Godfather", "Jaws", "Star Wars: A New Hope", "ET", "Jurassic Park", "Schindler\'s List"]} # 1984, 1963, 1968, 1972, 1975, 1977, 1982, 1993, 1994 {q:"Order buildings by height", t:"Highest", b:"Lowest", a:["PI:NAME:<NAME>END_PI", "Petronas Twin TPI:NAME:<NAME>END_PIers", "Empire State Building", "Eiffel Tower", "Great Pyramid of Giza", "Big Ben", "Statue of Liberty", "Sydney Opera House", "Leaning Tower of Pisa"]} #828, 452, 381, 300, 139, 96, 93, 65, 56 {q:"Order wonders by construction date", t:"Oldest", b:"Newest", a:["Great Pyramid of Giza", "Great Wall of China", "Petra", "Colosseum", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "Christ the PI:NAME:<NAME>END_PI"]} {q:"Order TV series on broadcast date", t:"Oldest", b:"Newest", a:["Star Trek: The Original Series", "The Bold and the Beautiful", "The Simpsons", "The X-Files", "South Park", "The Big Bang Theory", "Scrubs", "Futurama", "A Game of Thrones"]} # 1966, 1987, 1989, 1998, 2000, 2004, 2007, 2010, 2011 {q:"Order movies by IMDb rating", t:"Highest rated", b:"Lowest rated", a:["The Shawshank Redemption", "The Godfather", "The Dark Knight", "Pulp Fiction", "The Lord of the Rings: The Fellowship of the Ring", "Citizen Kane", "Toy Story", "Life of Brian", "Kill Bill"]} {q:"Order Disney films on release date", t: "Oldest", b:"Latest", a:["Snow White and the Seven Dwarfs", "Bambi", "Alice in Wonderland", "One Hundred and One Dalmatians", "The Aristocats", "The Little Mermaid", "Aladdin", "The Lion King", "The Princess and the Frog"]} {q:"Order Pixar films on release date", t:"Oldest", b:"Latest", a:["Toy Story", "A Bug's Life", "Monsters, Inc.", "Finding Nemo", "The Incredibles", "WALL-E", "Up", "Brave"]} {q:"Order Presidents of the United States Chronologically", t:"First", b:"Last", a:["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI (jr.)", "PI:NAME:<NAME>END_PI"]} {q:"Order countries by population", t:"Highest population", b:"Lowest population", a:["China", "India", "United States", "Brazil", "Japan", "Germany", "Iran", "Canada", "Iceland"]} {q:"Order weight per liter", t:"Lightest", b:"Heaviest", a:["Petrol", "Alcohol", "Olive oil", "Diesel", "Sunflower oil", "Water", "Beer", "Milk", "Sea water", "Citric acid"]} {q:"Order creation chronologically according to the Bible", t:"First", b:"Last", a:["Earth", "Water", "Land", "Sun", "Birds", "Man"]} {q:"Order these balls by size", t:"Smallest", b:"Biggest", a:["Table tennis ball", "Golf ball", "Pool ball", "Tennis ball", "Baseball ball", "Soccer ball", "Basketball ball"]} {q:"Order by invention date", t:"First", b:"Last", a:["Stone tools", "The wheel", "The alphabet", "Coins", "Windmill", "Woodblock printing", "Toilet Paper", "Gunpowder", "Soap", "Telescope", "Steam Engine", "Light Bulb"]} # WARNING: always add new questions to the end of this array ] # questions that are deemed to difficult: # ["Order Star Wars movies by release date", "A New Hope", "The Empire Strikes Back", "Return of the Jedi", "The Phantom Menace", "Attack of the Clones", "Revenge of the Sith", "The Force Awakens"] # ["Order by Electromagnetic Frequency", "Radio waves", "Microwave radiation", "Infrared radiation", "Green light", "Blue light", "Ultraviolet radiation", "X-ray radiation", "Gamma radiation"] # distance earth # distance space # size space # wk soccer wins exports.inverseCheck = -> [5,0,-3,"butt",-4,"miter",-5,4,4,2,0.019589437957492035,0.019589437957492035,2,2,0,0.0018773653552219825,2,2,0,0,4,2,1.0666666513406717,1.0666666513406717,2,2,-398.48159,-658.25586,5,0,-2,1,-6,1,7,0,10,2,398.48159,658.25586,11,2,398.48159,705.93359,11,2,446.33901,705.93359,11,2,446.33901,658.25586,11,2,398.48159,658.25586,12,0,10,2,437.2101,668.33789,11,2,440.01088,671.13672,11,2,416.01088,695.13672,11,2,404.81166,683.9375,11,2,407.61049,681.13672,11,2,416.01088,689.53711,11,2,437.2101,668.33789,12,0,8,1,"nonzero",6,0,6,0]
[ { "context": "google-analytics'\nnew GoogleAnalytics\n account: 'UA-53428944-3'\n domain: 'chicagowildlifewatch.org'\n\napp = {}\na", "end": 1479, "score": 0.99798983335495, "start": 1466, "tag": "KEY", "value": "UA-53428944-3" } ]
app/main.coffee
zooniverse/Snapshot-Chicago
2
translate = require 't7e' enUs = require './translations/en_us' translate.load enUs $ = window.jQuery require 'spine' window.slider = require './lib/jquery.slider.min' Navigation = require './controllers/navigation' Route = require 'spine/lib/route' AboutPage = require './controllers/about_page' HomePage = require './controllers/home_page' EducationPage = require './controllers/education_page' Classifier = require './controllers/classifier' FilterPage = require './controllers/filter_page' PressPage = require './controllers/press_page' Profile = require './controllers/profile' Api = require 'zooniverse/lib/api' Project = require 'zooniverse/models/project' seasons = require './lib/seasons' TopBar = require 'zooniverse/controllers/top-bar' Footer = require 'zooniverse/controllers/footer' Notifier = require './lib/notifier' User = require 'zooniverse/models/user' googleAnalytics = require 'zooniverse/lib/google-analytics' {Stack} = require 'spine/lib/manager' BrowserDialog = require 'zooniverse/controllers/browser-dialog' BrowserDialog.check() t7e = require 't7e' enUs = require './translations/en_us' LanguageManager = require 'zooniverse/lib/language-manager' languageManager = new LanguageManager translations: en: label: 'English', strings: enUs languageManager.on 'change-language', (e, code, strings) -> t7e.load strings t7e.refresh() GoogleAnalytics = require 'zooniverse/lib/google-analytics' new GoogleAnalytics account: 'UA-53428944-3' domain: 'chicagowildlifewatch.org' app = {} api = if window.location.hostname is 'www.chicagowildlifewatch.org' new zooniverse.Api project: 'chicago', host: 'https://www.chicagowildlifewatch.org', path: '/_ouroboros_api/proxy' else new zooniverse.Api project: 'chicago' #TODO rewrite this logic for sorted seasons # Api.get '/projects/serengeti', (project) -> # sortedSeasons = for season, {_id: id, total, complete} of project.seasons # total ?= 0 # complete ?= 0 # {season, id, total, complete} # sortedSeasons.sort (a, b) -> # a.season > b.season # seasons.push sortedSeasons... app.stack = new Stack className: "main #{Stack::className}" controllers: home: HomePage about: AboutPage classify: Classifier profile: Profile education: EducationPage filter: FilterPage press: PressPage routes: '/': 'home' '/about': 'about' '/classify': 'classify' '/profile': 'profile' '/education': 'education' '/filter': 'filter' '/press': 'press' default: 'home' Route.setup() User.fetch() Notifier.init() window.addEventListener 'hashchange' , -> Notifier.hide() app.topBar = new TopBar app.footer = new Footer navigation = new Navigation app.navigation = navigation app.navigation.el.appendTo 'body' app.stack.el.appendTo 'body' app.topBar.el.appendTo 'body' siteFooter = $('<div class="site-footer"></div>').append app.footer.el siteFooter.appendTo 'body' window.app = app module.exports = window.app
109929
translate = require 't7e' enUs = require './translations/en_us' translate.load enUs $ = window.jQuery require 'spine' window.slider = require './lib/jquery.slider.min' Navigation = require './controllers/navigation' Route = require 'spine/lib/route' AboutPage = require './controllers/about_page' HomePage = require './controllers/home_page' EducationPage = require './controllers/education_page' Classifier = require './controllers/classifier' FilterPage = require './controllers/filter_page' PressPage = require './controllers/press_page' Profile = require './controllers/profile' Api = require 'zooniverse/lib/api' Project = require 'zooniverse/models/project' seasons = require './lib/seasons' TopBar = require 'zooniverse/controllers/top-bar' Footer = require 'zooniverse/controllers/footer' Notifier = require './lib/notifier' User = require 'zooniverse/models/user' googleAnalytics = require 'zooniverse/lib/google-analytics' {Stack} = require 'spine/lib/manager' BrowserDialog = require 'zooniverse/controllers/browser-dialog' BrowserDialog.check() t7e = require 't7e' enUs = require './translations/en_us' LanguageManager = require 'zooniverse/lib/language-manager' languageManager = new LanguageManager translations: en: label: 'English', strings: enUs languageManager.on 'change-language', (e, code, strings) -> t7e.load strings t7e.refresh() GoogleAnalytics = require 'zooniverse/lib/google-analytics' new GoogleAnalytics account: '<KEY>' domain: 'chicagowildlifewatch.org' app = {} api = if window.location.hostname is 'www.chicagowildlifewatch.org' new zooniverse.Api project: 'chicago', host: 'https://www.chicagowildlifewatch.org', path: '/_ouroboros_api/proxy' else new zooniverse.Api project: 'chicago' #TODO rewrite this logic for sorted seasons # Api.get '/projects/serengeti', (project) -> # sortedSeasons = for season, {_id: id, total, complete} of project.seasons # total ?= 0 # complete ?= 0 # {season, id, total, complete} # sortedSeasons.sort (a, b) -> # a.season > b.season # seasons.push sortedSeasons... app.stack = new Stack className: "main #{Stack::className}" controllers: home: HomePage about: AboutPage classify: Classifier profile: Profile education: EducationPage filter: FilterPage press: PressPage routes: '/': 'home' '/about': 'about' '/classify': 'classify' '/profile': 'profile' '/education': 'education' '/filter': 'filter' '/press': 'press' default: 'home' Route.setup() User.fetch() Notifier.init() window.addEventListener 'hashchange' , -> Notifier.hide() app.topBar = new TopBar app.footer = new Footer navigation = new Navigation app.navigation = navigation app.navigation.el.appendTo 'body' app.stack.el.appendTo 'body' app.topBar.el.appendTo 'body' siteFooter = $('<div class="site-footer"></div>').append app.footer.el siteFooter.appendTo 'body' window.app = app module.exports = window.app
true
translate = require 't7e' enUs = require './translations/en_us' translate.load enUs $ = window.jQuery require 'spine' window.slider = require './lib/jquery.slider.min' Navigation = require './controllers/navigation' Route = require 'spine/lib/route' AboutPage = require './controllers/about_page' HomePage = require './controllers/home_page' EducationPage = require './controllers/education_page' Classifier = require './controllers/classifier' FilterPage = require './controllers/filter_page' PressPage = require './controllers/press_page' Profile = require './controllers/profile' Api = require 'zooniverse/lib/api' Project = require 'zooniverse/models/project' seasons = require './lib/seasons' TopBar = require 'zooniverse/controllers/top-bar' Footer = require 'zooniverse/controllers/footer' Notifier = require './lib/notifier' User = require 'zooniverse/models/user' googleAnalytics = require 'zooniverse/lib/google-analytics' {Stack} = require 'spine/lib/manager' BrowserDialog = require 'zooniverse/controllers/browser-dialog' BrowserDialog.check() t7e = require 't7e' enUs = require './translations/en_us' LanguageManager = require 'zooniverse/lib/language-manager' languageManager = new LanguageManager translations: en: label: 'English', strings: enUs languageManager.on 'change-language', (e, code, strings) -> t7e.load strings t7e.refresh() GoogleAnalytics = require 'zooniverse/lib/google-analytics' new GoogleAnalytics account: 'PI:KEY:<KEY>END_PI' domain: 'chicagowildlifewatch.org' app = {} api = if window.location.hostname is 'www.chicagowildlifewatch.org' new zooniverse.Api project: 'chicago', host: 'https://www.chicagowildlifewatch.org', path: '/_ouroboros_api/proxy' else new zooniverse.Api project: 'chicago' #TODO rewrite this logic for sorted seasons # Api.get '/projects/serengeti', (project) -> # sortedSeasons = for season, {_id: id, total, complete} of project.seasons # total ?= 0 # complete ?= 0 # {season, id, total, complete} # sortedSeasons.sort (a, b) -> # a.season > b.season # seasons.push sortedSeasons... app.stack = new Stack className: "main #{Stack::className}" controllers: home: HomePage about: AboutPage classify: Classifier profile: Profile education: EducationPage filter: FilterPage press: PressPage routes: '/': 'home' '/about': 'about' '/classify': 'classify' '/profile': 'profile' '/education': 'education' '/filter': 'filter' '/press': 'press' default: 'home' Route.setup() User.fetch() Notifier.init() window.addEventListener 'hashchange' , -> Notifier.hide() app.topBar = new TopBar app.footer = new Footer navigation = new Navigation app.navigation = navigation app.navigation.el.appendTo 'body' app.stack.el.appendTo 'body' app.topBar.el.appendTo 'body' siteFooter = $('<div class="site-footer"></div>').append app.footer.el siteFooter.appendTo 'body' window.app = app module.exports = window.app
[ { "context": " body: content or payload.body\n authorName: authorName\n creator: req.integration._robotId\n tea", "end": 2460, "score": 0.6426838636398315, "start": 2450, "tag": "NAME", "value": "authorName" } ]
talk-api2x/server/services/robot.coffee
ikingye/talk-os
3,084
Promise = require 'bluebird' Err = require 'err1st' _ = require 'lodash' serviceLoader = require 'talk-services' limbo = require 'limbo' logger = require 'graceful-logger' app = require '../server' {socket} = require '../components' { UserModel TeamModel MessageModel IntegrationModel NotificationModel } = limbo.use 'talk' $service = serviceLoader.load 'robot' _postMessage = ({message, integration}) -> service = this return unless integration.url msg = message.toJSON() msg.event = 'message.create' msg.token = integration.token if integration.token service.httpPost integration.url, msg, retryTimes: 3 .then (body = {}) -> return unless body.text or body.content or body.body replyMessage = new MessageModel body: body.content or body.body authorName: body.authorName creator: integration._robotId displayType: body.displayType if body.text attachment = category: 'quote' color: body.color data: body replyMessage.attachments = [attachment] # Append default fields switch when message.room replyMessage.room = message.room when message.story replyMessage.story = message.story when message.to replyMessage.to = message.creator else throw new Err 'FIELD_MISSING', 'room story to' replyMessage.team = message.team replyMessage.$save() .then (message) -> # Reset errorTimes return message unless integration.errorTimes > 0 integration.errorTimes = 0 integration.lastErrorInfo = undefined integration.errorInfo = undefined integration.$save().then -> message .catch (err) -> integration.errorTimes += 1 integration.lastErrorInfo = err.message integration.errorInfo = err.message if integration.errorTimes > 5 integration.$save() _receiveWebhook = (req, res) -> return unless req.integration?._robotId req.set '_sessionUserId', "#{req.integration._robotId}" req.set '_teamId', "#{req.integration._teamId}", true msgController = app.controller 'message' $permission = Promise.promisify(msgController.call).call msgController, 'accessibleMessage', req, res $message = Promise.all [$permission] .spread -> payload = _.assign {} , req.query or {} , req.body or {} {content, authorName, title, text, redirectUrl, imageUrl} = payload message = body: content or payload.body authorName: authorName creator: req.integration._robotId team: req.integration._teamId switch when payload._roomId message.room = payload._roomId when payload._toId message.to = payload._toId when payload._storyId message.story = payload._storyId else throw new Err('PARAMS_MISSING', '_toId _roomId _storyId') if title or text or redirectUrl or imageUrl message.attachments = [ category: 'quote' color: payload.color data: title: title text: text redirectUrl: redirectUrl imageUrl: imageUrl ] message ###* * Create a new robot and invite him to this team * Fork current robot as the bundle user of this integration * @param {Request} req with integration * @return {Promise} ### _createRobot = ({integration}) -> service = this robot = new UserModel name: integration.title avatarUrl: integration.iconUrl description: integration.description isRobot: true $robot = robot.$save() $team = TeamModel.findOneAsync _id: integration._teamId .then (team) -> throw new Err('OBJECT_MISSING', "Team #{integration._teamId}") unless team team $addMember = Promise.all [$robot, $team] .spread (robot, team) -> integration.robot = robot team.addMemberAsync robot $broadcast = Promise.all [$robot, $team, $addMember] .spread (robot, team) -> robot.team = team robot._teamId = team._id socket.broadcast "team:#{team._id}", "team:join", robot ###* * Update robot's infomation * @param {Request} req with integration * @return {Promise} robot ### _updateRobot = (req) -> {integration} = req return unless integration._robotId $robot = UserModel.findOneAsync _id: integration._robotId .then (robot) -> return unless robot robot.name = req.get 'title' if req.get 'title' robot.avatarUrl = req.get 'iconUrl' if req.get 'iconUrl' robot.description = req.get 'description' if req.get 'description' robot.updatedAt = new Date robot.$save() ###* * Remove this robot from team * @param {Request} req with integration * @return {Promise} ### _removeRobot = ({integration}) -> return unless integration._robotId $removeRobots = TeamModel.removeMemberAsync integration._teamId, integration._robotId .then -> data = _teamId: integration._teamId _userId: integration._robotId socket.broadcast "team:#{integration._teamId}", "team:leave", data $removeNotifications = NotificationModel.removeByOptionsAsync target: integration._robotId, team: integration._teamId Promise.all [$removeRobots, $removeNotifications] $service.then (service) -> service.registerEvent 'message.create', _postMessage service.registerEvent 'service.webhook', _receiveWebhook service.registerEvent 'before.integration.create', _createRobot service.registerEvent 'before.integration.update', _updateRobot service.registerEvent 'before.integration.remove', _removeRobot # Register hook after create message app.controller 'message', -> @after 'sendMsgToRobot', only: 'create', parallel: true @action 'sendMsgToRobot', (req, res, message) -> # Send dms to robot if message.to?.isRobot $integrations = IntegrationModel.findOneAsync team: message._teamId robot: message.to._id errorInfo: null .then (integration) -> if integration then [integration] else [] # Check mentions in channel else if (message.room or message.story) and message.mentions?.length $integrations = UserModel.findAsync _id: $in: message.mentions isRobot: true , '_id' .then (robots = []) -> _robotIds = robots.map (robot) -> "#{robot._id}" return [] unless _robotIds?.length IntegrationModel.findAsync team: message._teamId robot: $in: _robotIds errorInfo: null # Do nothing else return Promise.all [$service, $integrations] .spread (service, integrations) -> return unless service and integrations?.length Promise.map integrations, (integration) -> _req = _.clone req _req.integration = integration _req.message = message service.receiveEvent 'message.create', _req .catch (err) -> logger.warn err.stack # Register hook after remove team member app.controller 'team', -> @after 'removeRobotIntegration', only: 'removeMember', parallel: true @action 'removeRobotIntegration', (req, res, result) -> {_userId} = req.get() return unless _userId $integration = IntegrationModel.findOneAsync robot: _userId .then (integration) -> return unless integration integration.$remove().then (integration) -> _integration = _.omit(integration.toJSON(), 'token', 'refreshToken') res.broadcast "team:#{integration._teamId}", "integration:remove", _integration .catch (err) -> logger.warn err.stack
214138
Promise = require 'bluebird' Err = require 'err1st' _ = require 'lodash' serviceLoader = require 'talk-services' limbo = require 'limbo' logger = require 'graceful-logger' app = require '../server' {socket} = require '../components' { UserModel TeamModel MessageModel IntegrationModel NotificationModel } = limbo.use 'talk' $service = serviceLoader.load 'robot' _postMessage = ({message, integration}) -> service = this return unless integration.url msg = message.toJSON() msg.event = 'message.create' msg.token = integration.token if integration.token service.httpPost integration.url, msg, retryTimes: 3 .then (body = {}) -> return unless body.text or body.content or body.body replyMessage = new MessageModel body: body.content or body.body authorName: body.authorName creator: integration._robotId displayType: body.displayType if body.text attachment = category: 'quote' color: body.color data: body replyMessage.attachments = [attachment] # Append default fields switch when message.room replyMessage.room = message.room when message.story replyMessage.story = message.story when message.to replyMessage.to = message.creator else throw new Err 'FIELD_MISSING', 'room story to' replyMessage.team = message.team replyMessage.$save() .then (message) -> # Reset errorTimes return message unless integration.errorTimes > 0 integration.errorTimes = 0 integration.lastErrorInfo = undefined integration.errorInfo = undefined integration.$save().then -> message .catch (err) -> integration.errorTimes += 1 integration.lastErrorInfo = err.message integration.errorInfo = err.message if integration.errorTimes > 5 integration.$save() _receiveWebhook = (req, res) -> return unless req.integration?._robotId req.set '_sessionUserId', "#{req.integration._robotId}" req.set '_teamId', "#{req.integration._teamId}", true msgController = app.controller 'message' $permission = Promise.promisify(msgController.call).call msgController, 'accessibleMessage', req, res $message = Promise.all [$permission] .spread -> payload = _.assign {} , req.query or {} , req.body or {} {content, authorName, title, text, redirectUrl, imageUrl} = payload message = body: content or payload.body authorName: <NAME> creator: req.integration._robotId team: req.integration._teamId switch when payload._roomId message.room = payload._roomId when payload._toId message.to = payload._toId when payload._storyId message.story = payload._storyId else throw new Err('PARAMS_MISSING', '_toId _roomId _storyId') if title or text or redirectUrl or imageUrl message.attachments = [ category: 'quote' color: payload.color data: title: title text: text redirectUrl: redirectUrl imageUrl: imageUrl ] message ###* * Create a new robot and invite him to this team * Fork current robot as the bundle user of this integration * @param {Request} req with integration * @return {Promise} ### _createRobot = ({integration}) -> service = this robot = new UserModel name: integration.title avatarUrl: integration.iconUrl description: integration.description isRobot: true $robot = robot.$save() $team = TeamModel.findOneAsync _id: integration._teamId .then (team) -> throw new Err('OBJECT_MISSING', "Team #{integration._teamId}") unless team team $addMember = Promise.all [$robot, $team] .spread (robot, team) -> integration.robot = robot team.addMemberAsync robot $broadcast = Promise.all [$robot, $team, $addMember] .spread (robot, team) -> robot.team = team robot._teamId = team._id socket.broadcast "team:#{team._id}", "team:join", robot ###* * Update robot's infomation * @param {Request} req with integration * @return {Promise} robot ### _updateRobot = (req) -> {integration} = req return unless integration._robotId $robot = UserModel.findOneAsync _id: integration._robotId .then (robot) -> return unless robot robot.name = req.get 'title' if req.get 'title' robot.avatarUrl = req.get 'iconUrl' if req.get 'iconUrl' robot.description = req.get 'description' if req.get 'description' robot.updatedAt = new Date robot.$save() ###* * Remove this robot from team * @param {Request} req with integration * @return {Promise} ### _removeRobot = ({integration}) -> return unless integration._robotId $removeRobots = TeamModel.removeMemberAsync integration._teamId, integration._robotId .then -> data = _teamId: integration._teamId _userId: integration._robotId socket.broadcast "team:#{integration._teamId}", "team:leave", data $removeNotifications = NotificationModel.removeByOptionsAsync target: integration._robotId, team: integration._teamId Promise.all [$removeRobots, $removeNotifications] $service.then (service) -> service.registerEvent 'message.create', _postMessage service.registerEvent 'service.webhook', _receiveWebhook service.registerEvent 'before.integration.create', _createRobot service.registerEvent 'before.integration.update', _updateRobot service.registerEvent 'before.integration.remove', _removeRobot # Register hook after create message app.controller 'message', -> @after 'sendMsgToRobot', only: 'create', parallel: true @action 'sendMsgToRobot', (req, res, message) -> # Send dms to robot if message.to?.isRobot $integrations = IntegrationModel.findOneAsync team: message._teamId robot: message.to._id errorInfo: null .then (integration) -> if integration then [integration] else [] # Check mentions in channel else if (message.room or message.story) and message.mentions?.length $integrations = UserModel.findAsync _id: $in: message.mentions isRobot: true , '_id' .then (robots = []) -> _robotIds = robots.map (robot) -> "#{robot._id}" return [] unless _robotIds?.length IntegrationModel.findAsync team: message._teamId robot: $in: _robotIds errorInfo: null # Do nothing else return Promise.all [$service, $integrations] .spread (service, integrations) -> return unless service and integrations?.length Promise.map integrations, (integration) -> _req = _.clone req _req.integration = integration _req.message = message service.receiveEvent 'message.create', _req .catch (err) -> logger.warn err.stack # Register hook after remove team member app.controller 'team', -> @after 'removeRobotIntegration', only: 'removeMember', parallel: true @action 'removeRobotIntegration', (req, res, result) -> {_userId} = req.get() return unless _userId $integration = IntegrationModel.findOneAsync robot: _userId .then (integration) -> return unless integration integration.$remove().then (integration) -> _integration = _.omit(integration.toJSON(), 'token', 'refreshToken') res.broadcast "team:#{integration._teamId}", "integration:remove", _integration .catch (err) -> logger.warn err.stack
true
Promise = require 'bluebird' Err = require 'err1st' _ = require 'lodash' serviceLoader = require 'talk-services' limbo = require 'limbo' logger = require 'graceful-logger' app = require '../server' {socket} = require '../components' { UserModel TeamModel MessageModel IntegrationModel NotificationModel } = limbo.use 'talk' $service = serviceLoader.load 'robot' _postMessage = ({message, integration}) -> service = this return unless integration.url msg = message.toJSON() msg.event = 'message.create' msg.token = integration.token if integration.token service.httpPost integration.url, msg, retryTimes: 3 .then (body = {}) -> return unless body.text or body.content or body.body replyMessage = new MessageModel body: body.content or body.body authorName: body.authorName creator: integration._robotId displayType: body.displayType if body.text attachment = category: 'quote' color: body.color data: body replyMessage.attachments = [attachment] # Append default fields switch when message.room replyMessage.room = message.room when message.story replyMessage.story = message.story when message.to replyMessage.to = message.creator else throw new Err 'FIELD_MISSING', 'room story to' replyMessage.team = message.team replyMessage.$save() .then (message) -> # Reset errorTimes return message unless integration.errorTimes > 0 integration.errorTimes = 0 integration.lastErrorInfo = undefined integration.errorInfo = undefined integration.$save().then -> message .catch (err) -> integration.errorTimes += 1 integration.lastErrorInfo = err.message integration.errorInfo = err.message if integration.errorTimes > 5 integration.$save() _receiveWebhook = (req, res) -> return unless req.integration?._robotId req.set '_sessionUserId', "#{req.integration._robotId}" req.set '_teamId', "#{req.integration._teamId}", true msgController = app.controller 'message' $permission = Promise.promisify(msgController.call).call msgController, 'accessibleMessage', req, res $message = Promise.all [$permission] .spread -> payload = _.assign {} , req.query or {} , req.body or {} {content, authorName, title, text, redirectUrl, imageUrl} = payload message = body: content or payload.body authorName: PI:NAME:<NAME>END_PI creator: req.integration._robotId team: req.integration._teamId switch when payload._roomId message.room = payload._roomId when payload._toId message.to = payload._toId when payload._storyId message.story = payload._storyId else throw new Err('PARAMS_MISSING', '_toId _roomId _storyId') if title or text or redirectUrl or imageUrl message.attachments = [ category: 'quote' color: payload.color data: title: title text: text redirectUrl: redirectUrl imageUrl: imageUrl ] message ###* * Create a new robot and invite him to this team * Fork current robot as the bundle user of this integration * @param {Request} req with integration * @return {Promise} ### _createRobot = ({integration}) -> service = this robot = new UserModel name: integration.title avatarUrl: integration.iconUrl description: integration.description isRobot: true $robot = robot.$save() $team = TeamModel.findOneAsync _id: integration._teamId .then (team) -> throw new Err('OBJECT_MISSING', "Team #{integration._teamId}") unless team team $addMember = Promise.all [$robot, $team] .spread (robot, team) -> integration.robot = robot team.addMemberAsync robot $broadcast = Promise.all [$robot, $team, $addMember] .spread (robot, team) -> robot.team = team robot._teamId = team._id socket.broadcast "team:#{team._id}", "team:join", robot ###* * Update robot's infomation * @param {Request} req with integration * @return {Promise} robot ### _updateRobot = (req) -> {integration} = req return unless integration._robotId $robot = UserModel.findOneAsync _id: integration._robotId .then (robot) -> return unless robot robot.name = req.get 'title' if req.get 'title' robot.avatarUrl = req.get 'iconUrl' if req.get 'iconUrl' robot.description = req.get 'description' if req.get 'description' robot.updatedAt = new Date robot.$save() ###* * Remove this robot from team * @param {Request} req with integration * @return {Promise} ### _removeRobot = ({integration}) -> return unless integration._robotId $removeRobots = TeamModel.removeMemberAsync integration._teamId, integration._robotId .then -> data = _teamId: integration._teamId _userId: integration._robotId socket.broadcast "team:#{integration._teamId}", "team:leave", data $removeNotifications = NotificationModel.removeByOptionsAsync target: integration._robotId, team: integration._teamId Promise.all [$removeRobots, $removeNotifications] $service.then (service) -> service.registerEvent 'message.create', _postMessage service.registerEvent 'service.webhook', _receiveWebhook service.registerEvent 'before.integration.create', _createRobot service.registerEvent 'before.integration.update', _updateRobot service.registerEvent 'before.integration.remove', _removeRobot # Register hook after create message app.controller 'message', -> @after 'sendMsgToRobot', only: 'create', parallel: true @action 'sendMsgToRobot', (req, res, message) -> # Send dms to robot if message.to?.isRobot $integrations = IntegrationModel.findOneAsync team: message._teamId robot: message.to._id errorInfo: null .then (integration) -> if integration then [integration] else [] # Check mentions in channel else if (message.room or message.story) and message.mentions?.length $integrations = UserModel.findAsync _id: $in: message.mentions isRobot: true , '_id' .then (robots = []) -> _robotIds = robots.map (robot) -> "#{robot._id}" return [] unless _robotIds?.length IntegrationModel.findAsync team: message._teamId robot: $in: _robotIds errorInfo: null # Do nothing else return Promise.all [$service, $integrations] .spread (service, integrations) -> return unless service and integrations?.length Promise.map integrations, (integration) -> _req = _.clone req _req.integration = integration _req.message = message service.receiveEvent 'message.create', _req .catch (err) -> logger.warn err.stack # Register hook after remove team member app.controller 'team', -> @after 'removeRobotIntegration', only: 'removeMember', parallel: true @action 'removeRobotIntegration', (req, res, result) -> {_userId} = req.get() return unless _userId $integration = IntegrationModel.findOneAsync robot: _userId .then (integration) -> return unless integration integration.$remove().then (integration) -> _integration = _.omit(integration.toJSON(), 'token', 'refreshToken') res.broadcast "team:#{integration._teamId}", "integration:remove", _integration .catch (err) -> logger.warn err.stack
[ { "context": "ge in backend\n#\n# Nodize CMS\n# https://github.com/nodize/nodizecms\n#\n# Original page design :\n# IonizeCMS ", "end": 73, "score": 0.9993898868560791, "start": 67, "tag": "USERNAME", "value": "nodize" }, { "context": " # img '.pr5', src: 'http://1...
modules/backend/inline_views/view_articleList.coffee
nodize/nodizecms
32
# Article list page in backend # # Nodize CMS # https://github.com/nodize/nodizecms # # Original page design : # IonizeCMS (http://www.ionizecms.com), # (c) Partikule (http://www.partikule.net) # # CoffeeKup conversion & adaptation : # Hypee (http://hypee.com) # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # @include = -> # # Article list & types & categories edition # @view backend_articleList: -> html -> # Filters form : # - Pages # - Search field (title, content, etc.) div '#maincolumn', -> h2 '#main-title.main.articles', 'Articles' # 'Tabs' div '#articlesTab.mainTabs', -> ul '.tab-menu', -> # li -> # a -> # span 'Articles' li -> a -> span 'Categories' li -> a -> span 'Types' div class:'clear' # 'Articles list' div '#articlesTabContent', -> # div '.tabcontent', -> # 'Article list filtering' # form '#filterArticles', -> # label '.left', title: 'Filter articles (not fully implemented)', 'Filter' # input '#contains.inputtext.w160 left', type: 'text' # a id: 'cleanFilter', class: 'icon clearfield left ml5' # table '#articlesTable.list', -> # thead -> # tr -> # th 'Title' # th axis: 'string', 'Pages' # th axis: 'string', style: 'width:30px;', 'Content' # th '.right', style: 'width:70px;', 'Actions' # tbody -> # tr '.article1', -> # td '.title', style: 'overflow:hidden;', -> # div style: 'overflow:hidden;', -> # span '.toggler.left', rel: 'content1', -> # a class: 'left article', rel: '0.1', -> # span class:'flag flag0' # text '404' # div '#content1.content', -> # div '.text', -> # div '.mr10.left langcontent dl', style: 'width:90%;', -> # img '.pr5', src: 'http://192.168.1.162/themes/admin/images/world_flags/flag_en.gif' # div -> # p 'The content you asked was not found !' # td -> # img '.help', src: 'http://192.168.1.162/themes/admin/images/icon_16_alert.png', title: 'Orphan article. Not linked to any page.' # td -> # img '.pr5', src: 'http://192.168.1.162/themes/admin/images/world_flags/flag_en.gif' # comment '<td><img class="pr5" src="http://192.168.1.162/themes/admin/images/world_flags/flag_en.gif" /></td>' # td -> # a class: 'icon right delete', rel: '1' # a class: 'icon right duplicate mr5', rel: '1|404' # a class: 'icon right edit mr5', rel: '1', title: '404' # --------------------------- 'Categories' div '.tabcontent', -> div '.tabsidecolumn', -> h3 'New category' form '#newCategoryForm', name: 'newCategoryForm', action: '/admin/category/save', -> # 'Name' dl '.small', -> dt -> label for: 'name', 'Name' dd -> input '#name.inputtext.required', name: 'name', type: 'text', value: '' fieldset '#blocks', -> # 'Category Lang Tabs' div '#categoryTab.mainTabs', -> ul '.tab-menu', -> for lang in Static_langs_records li '.tab_category', rel: lang.lang, -> a -> span -> lang.name div class:'clear' # 'Category Content' div '#categoryTabContent', -> for lang in Static_langs_records div '.tabcontentcat', -> # 'title' dl '.small', -> dt -> label for: "title_#{lang.lang}", 'Title' dd -> input "#title_#{lang.lang}.inputtext", name: "title_#{lang.lang}", type: 'text', value: '' # 'subtitle' dl '.small', -> dt -> label for: "subtitle_#{lang.lang}", 'Subtitle' dd -> input "#subtitle_#{lang.lang}.inputtext", name: "subtitle_#{lang.lang}", type: 'text', value: '' # 'description' dl '.small', -> dt -> label for: "descriptionCategory#{lang.lang}", 'Description' dd -> textarea "#descriptionCategory#{lang.lang}.tinyCategory", name: "description_#{lang.lang}", rel: lang.lang # 'save button' dl '.small', -> dt '&#160;' dd -> button '#bSaveNewCategory.button.yes', type: 'button', 'Save' div '#categoriesContainer.tabcolumn.pt15', '' # ------------------------------------------------- Types div '.tabcontent', -> # 'New type' div '.tabsidecolumn', -> h3 'New type' form '#newTypeForm', name: 'newTypeForm', action: "/admin/article_type\/\/save", -> # 'Name' dl '.small', -> dt -> label for: 'type', 'Type' dd -> input '#type.inputtext', name: 'type', type: 'text', value: '' # 'Flag' dl '.small', -> dt -> label for: 'flag0', title: 'An internal marked, just to be organized.', 'Flag' dd -> label class:'flag flag0', -> input '#flag0.inputradio', name: 'type_flag', type: 'radio', value: '0' label '.flag.flag1', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '1' label '.flag.flag2', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '2' label '.flag.flag3', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '3' label '.flag.flag4', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '4' label '.flag.flag5', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '5' label '.flag.flag6', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '6' # 'Description' dl '.small', -> dt -> label for: 'descriptionType', 'Description' dd -> textarea '#descriptionType.tinyType', name: 'description' # 'save button' dl '.small', -> dt '&#160;' dd -> button '#bSaveNewType.button.yes', type: 'button', 'Save' # 'Existing types' div id:'articleTypesContainer', class:'tabcolumn pt15' # 'Articles Markers' coffeescript -> # # Make each article draggable # # $$("#articlesTable .article").each (item, idx) -> # ION.addDragDrop item, ".dropArticleInPage,.dropArticleAsLink,.folder", "ION.dropArticleInPage,ION.dropArticleAsLink,ION.dropArticleInPage" # # Adds Sortable function to the user list table # # new SortableTable("articlesTable", # sortOn: 0 # sortBy: "ASC" # ) # ION.initLabelHelpLinks "#articlesTable" # ION.initLabelHelpLinks "#filterArticles" # # Categories list # ION.HTML admin_url + "category\/\/get_list", "", update: "categoriesContainer" # # New category Form submit # $("bSaveNewCategory").addEvent "click", (e) -> e.stop() ION.sendData admin_url + "category\/\/save", $("newCategoryForm") # # New category tabs (langs) # new TabSwapper( tabsContainer: "categoryTab" sectionsContainer: "categoryTabContent" selectedClass: "selected" deselectedClass: "" tabs: "li" clickers: "li a" sections: "div.tabcontentcat" cookieName: "categoryTab" ) # # TinyEditors # Must be called after tabs init. # ION.initTinyEditors ".tab_category", "#categoryTabContent .tinyCategory", "small" # # Type list # ION.HTML admin_url + "article_type\/\/get_list", "", update: "articleTypesContainer" # # New Type Form submit # $("bSaveNewType").addEvent "click", (e) -> e.stop() ION.sendData admin_url + "article_type\/\/save", $("newTypeForm") # # Articles Tabs # new TabSwapper( tabsContainer: "articlesTab" sectionsContainer: "articlesTabContent" selectedClass: "selected" deselectedClass: "" tabs: "li" clickers: "li a" sections: "div.tabcontent" cookieName: "articlesTab" ) # # Table action icons # confirmDeleteMessage = Lang.get("ionize_confirm_element_delete") url = admin_url + "article/delete/" $$("#articlesTable .delete").each (item) -> ION.initRequestEvent item, url + item.getProperty("rel"), {}, message: confirmDeleteMessage $$("#articlesTable .duplicate").each (item) -> rel = item.getProperty("rel").split("|") id = rel[0] url = rel[1] item.addEvent "click", (e) -> e.stop() ION.formWindow "DuplicateArticle", "newArticleForm", "ionize_title_duplicate_article", "article/duplicate/" + id + "/" + url, width: 520 height: 280 $$("#articlesTable .edit").each (item) -> id_article = item.getProperty("rel") title = item.getProperty("title") item.addEvent "click", (e) -> e.stop() MUI.Content.update element: $("mainPanel") loadMethod: "xhr" url: admin_url + "article/edit/0." + id_article title: Lang.get("ionize_title_edit_article") + " : " + title # # Content togglers # calculateTableLineSizes = -> $$("#articlesTable tbody tr td.title").each (el) -> c = el.getFirst(".content") toggler = el.getElement(".toggler") text = c.getFirst() s = text.getDimensions() if s.height > 0 toggler.store "max", s.height + 10 if toggler.hasClass("expand") el.setStyles height: 20 + s.height + "px" c.setStyles height: s.height + "px" else toggler.store "max", s.height window.removeEvent "resize", calculateTableLineSizes window.addEvent "resize", -> calculateTableLineSizes() window.fireEvent "resize" $$("#articlesTable tbody tr td .toggler").each (el) -> el.fx = new Fx.Morph($(el.getProperty("rel")), duration: 200 transition: Fx.Transitions.Sine.easeOut ) el.fx2 = new Fx.Morph($(el.getParent("td")), duration: 200 transition: Fx.Transitions.Sine.easeOut ) $(el.getProperty("rel")).setStyles height: "0px" toggleArticle = (e) -> # this.fx.toggle(); e.stop() @toggleClass "expand" max = @retrieve("max") from = 0 to = max if @hasClass("expand") is 0 from = max to = 0 @getParent("tr").removeClass "highlight" else @getParent("tr").addClass "highlight" @fx.start height: [ from, to ] @fx2.start height: [ from + 20, to + 20 ] $$("#articlesTable tbody tr td .toggler").addEvent "click", toggleArticle $$("#articlesTable tbody tr td.title").addEvent "click", (e) -> @getElement(".toggler").fireEvent "click", e $$("#articlesTable tbody tr td .content").addEvent "click", (e) -> @getParent("td").getElement(".toggler").fireEvent "click", e # # Filtering # filterArticles = (search) -> reg = new RegExp("<span class=\"highlight\"[^><]*>|<.span[^><]*>", "g") search = RegExp(search, "gi") $$("#articlesTable .text").each (el) -> c = el.get("html") tr = el.getParent("tr") m = c.match(search) if m tr.setStyles "background-color": "#FDFCED" h = c h = h.replace(reg, "") m.each (item) -> h = h.replace(item, "<span class=\"highlight\">" + item + "</span>") el.set "html", h tr.setStyle "visibility", "visible" else tr.removeProperty "style" h = c.replace(reg, "") el.set "html", h # $("contains").addEvent "keyup", (e) -> # e.stop() # search = @value # if search.length > 2 # $clear @timeoutID if @timeoutID # @timeoutID = filterArticles.delay(500, this, search) # $("cleanFilter").addEvent "click", (e) -> # reg = new RegExp("<span class=\"highlight\"[^><]*>|<.span[^><]*>", "g") # $("contains").setProperty("value", "").set "text", "" # $$("#articlesTable tr").each (el) -> # el.removeProperty "style" # $$("#articlesTable .text").each (el) -> # c = el.get("html") # c = c.replace(reg, "") # el.set "html", c ION.initToolbox "articles_toolbox"
176317
# Article list page in backend # # Nodize CMS # https://github.com/nodize/nodizecms # # Original page design : # IonizeCMS (http://www.ionizecms.com), # (c) Partikule (http://www.partikule.net) # # CoffeeKup conversion & adaptation : # Hypee (http://hypee.com) # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # @include = -> # # Article list & types & categories edition # @view backend_articleList: -> html -> # Filters form : # - Pages # - Search field (title, content, etc.) div '#maincolumn', -> h2 '#main-title.main.articles', 'Articles' # 'Tabs' div '#articlesTab.mainTabs', -> ul '.tab-menu', -> # li -> # a -> # span 'Articles' li -> a -> span 'Categories' li -> a -> span 'Types' div class:'clear' # 'Articles list' div '#articlesTabContent', -> # div '.tabcontent', -> # 'Article list filtering' # form '#filterArticles', -> # label '.left', title: 'Filter articles (not fully implemented)', 'Filter' # input '#contains.inputtext.w160 left', type: 'text' # a id: 'cleanFilter', class: 'icon clearfield left ml5' # table '#articlesTable.list', -> # thead -> # tr -> # th 'Title' # th axis: 'string', 'Pages' # th axis: 'string', style: 'width:30px;', 'Content' # th '.right', style: 'width:70px;', 'Actions' # tbody -> # tr '.article1', -> # td '.title', style: 'overflow:hidden;', -> # div style: 'overflow:hidden;', -> # span '.toggler.left', rel: 'content1', -> # a class: 'left article', rel: '0.1', -> # span class:'flag flag0' # text '404' # div '#content1.content', -> # div '.text', -> # div '.mr10.left langcontent dl', style: 'width:90%;', -> # img '.pr5', src: 'http://192.168.1.162/themes/admin/images/world_flags/flag_en.gif' # div -> # p 'The content you asked was not found !' # td -> # img '.help', src: 'http://1192.168.3.112/themes/admin/images/icon_16_alert.png', title: 'Orphan article. Not linked to any page.' # td -> # img '.pr5', src: 'http://192.168.1.162/themes/admin/images/world_flags/flag_en.gif' # comment '<td><img class="pr5" src="http://192.168.1.162/themes/admin/images/world_flags/flag_en.gif" /></td>' # td -> # a class: 'icon right delete', rel: '1' # a class: 'icon right duplicate mr5', rel: '1|404' # a class: 'icon right edit mr5', rel: '1', title: '404' # --------------------------- 'Categories' div '.tabcontent', -> div '.tabsidecolumn', -> h3 'New category' form '#newCategoryForm', name: 'newCategoryForm', action: '/admin/category/save', -> # 'Name' dl '.small', -> dt -> label for: 'name', 'Name' dd -> input '#name.inputtext.required', name: 'name', type: 'text', value: '' fieldset '#blocks', -> # 'Category Lang Tabs' div '#categoryTab.mainTabs', -> ul '.tab-menu', -> for lang in Static_langs_records li '.tab_category', rel: lang.lang, -> a -> span -> lang.name div class:'clear' # 'Category Content' div '#categoryTabContent', -> for lang in Static_langs_records div '.tabcontentcat', -> # 'title' dl '.small', -> dt -> label for: "title_#{lang.lang}", 'Title' dd -> input "#title_#{lang.lang}.inputtext", name: "title_#{lang.lang}", type: 'text', value: '' # 'subtitle' dl '.small', -> dt -> label for: "subtitle_#{lang.lang}", 'Subtitle' dd -> input "#subtitle_#{lang.lang}.inputtext", name: "subtitle_#{lang.lang}", type: 'text', value: '' # 'description' dl '.small', -> dt -> label for: "descriptionCategory#{lang.lang}", 'Description' dd -> textarea "#descriptionCategory#{lang.lang}.tinyCategory", name: "description_#{lang.lang}", rel: lang.lang # 'save button' dl '.small', -> dt '&#160;' dd -> button '#bSaveNewCategory.button.yes', type: 'button', 'Save' div '#categoriesContainer.tabcolumn.pt15', '' # ------------------------------------------------- Types div '.tabcontent', -> # 'New type' div '.tabsidecolumn', -> h3 'New type' form '#newTypeForm', name: 'newTypeForm', action: "/admin/article_type\/\/save", -> # 'Name' dl '.small', -> dt -> label for: 'type', 'Type' dd -> input '#type.inputtext', name: 'type', type: 'text', value: '' # 'Flag' dl '.small', -> dt -> label for: 'flag0', title: 'An internal marked, just to be organized.', 'Flag' dd -> label class:'flag flag0', -> input '#flag0.inputradio', name: 'type_flag', type: 'radio', value: '0' label '.flag.flag1', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '1' label '.flag.flag2', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '2' label '.flag.flag3', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '3' label '.flag.flag4', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '4' label '.flag.flag5', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '5' label '.flag.flag6', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '6' # 'Description' dl '.small', -> dt -> label for: 'descriptionType', 'Description' dd -> textarea '#descriptionType.tinyType', name: 'description' # 'save button' dl '.small', -> dt '&#160;' dd -> button '#bSaveNewType.button.yes', type: 'button', 'Save' # 'Existing types' div id:'articleTypesContainer', class:'tabcolumn pt15' # 'Articles Markers' coffeescript -> # # Make each article draggable # # $$("#articlesTable .article").each (item, idx) -> # ION.addDragDrop item, ".dropArticleInPage,.dropArticleAsLink,.folder", "ION.dropArticleInPage,ION.dropArticleAsLink,ION.dropArticleInPage" # # Adds Sortable function to the user list table # # new SortableTable("articlesTable", # sortOn: 0 # sortBy: "ASC" # ) # ION.initLabelHelpLinks "#articlesTable" # ION.initLabelHelpLinks "#filterArticles" # # Categories list # ION.HTML admin_url + "category\/\/get_list", "", update: "categoriesContainer" # # New category Form submit # $("bSaveNewCategory").addEvent "click", (e) -> e.stop() ION.sendData admin_url + "category\/\/save", $("newCategoryForm") # # New category tabs (langs) # new TabSwapper( tabsContainer: "categoryTab" sectionsContainer: "categoryTabContent" selectedClass: "selected" deselectedClass: "" tabs: "li" clickers: "li a" sections: "div.tabcontentcat" cookieName: "categoryTab" ) # # TinyEditors # Must be called after tabs init. # ION.initTinyEditors ".tab_category", "#categoryTabContent .tinyCategory", "small" # # Type list # ION.HTML admin_url + "article_type\/\/get_list", "", update: "articleTypesContainer" # # New Type Form submit # $("bSaveNewType").addEvent "click", (e) -> e.stop() ION.sendData admin_url + "article_type\/\/save", $("newTypeForm") # # Articles Tabs # new TabSwapper( tabsContainer: "articlesTab" sectionsContainer: "articlesTabContent" selectedClass: "selected" deselectedClass: "" tabs: "li" clickers: "li a" sections: "div.tabcontent" cookieName: "articlesTab" ) # # Table action icons # confirmDeleteMessage = Lang.get("ionize_confirm_element_delete") url = admin_url + "article/delete/" $$("#articlesTable .delete").each (item) -> ION.initRequestEvent item, url + item.getProperty("rel"), {}, message: confirmDeleteMessage $$("#articlesTable .duplicate").each (item) -> rel = item.getProperty("rel").split("|") id = rel[0] url = rel[1] item.addEvent "click", (e) -> e.stop() ION.formWindow "DuplicateArticle", "newArticleForm", "ionize_title_duplicate_article", "article/duplicate/" + id + "/" + url, width: 520 height: 280 $$("#articlesTable .edit").each (item) -> id_article = item.getProperty("rel") title = item.getProperty("title") item.addEvent "click", (e) -> e.stop() MUI.Content.update element: $("mainPanel") loadMethod: "xhr" url: admin_url + "article/edit/0." + id_article title: Lang.get("ionize_title_edit_article") + " : " + title # # Content togglers # calculateTableLineSizes = -> $$("#articlesTable tbody tr td.title").each (el) -> c = el.getFirst(".content") toggler = el.getElement(".toggler") text = c.getFirst() s = text.getDimensions() if s.height > 0 toggler.store "max", s.height + 10 if toggler.hasClass("expand") el.setStyles height: 20 + s.height + "px" c.setStyles height: s.height + "px" else toggler.store "max", s.height window.removeEvent "resize", calculateTableLineSizes window.addEvent "resize", -> calculateTableLineSizes() window.fireEvent "resize" $$("#articlesTable tbody tr td .toggler").each (el) -> el.fx = new Fx.Morph($(el.getProperty("rel")), duration: 200 transition: Fx.Transitions.Sine.easeOut ) el.fx2 = new Fx.Morph($(el.getParent("td")), duration: 200 transition: Fx.Transitions.Sine.easeOut ) $(el.getProperty("rel")).setStyles height: "0px" toggleArticle = (e) -> # this.fx.toggle(); e.stop() @toggleClass "expand" max = @retrieve("max") from = 0 to = max if @hasClass("expand") is 0 from = max to = 0 @getParent("tr").removeClass "highlight" else @getParent("tr").addClass "highlight" @fx.start height: [ from, to ] @fx2.start height: [ from + 20, to + 20 ] $$("#articlesTable tbody tr td .toggler").addEvent "click", toggleArticle $$("#articlesTable tbody tr td.title").addEvent "click", (e) -> @getElement(".toggler").fireEvent "click", e $$("#articlesTable tbody tr td .content").addEvent "click", (e) -> @getParent("td").getElement(".toggler").fireEvent "click", e # # Filtering # filterArticles = (search) -> reg = new RegExp("<span class=\"highlight\"[^><]*>|<.span[^><]*>", "g") search = RegExp(search, "gi") $$("#articlesTable .text").each (el) -> c = el.get("html") tr = el.getParent("tr") m = c.match(search) if m tr.setStyles "background-color": "#FDFCED" h = c h = h.replace(reg, "") m.each (item) -> h = h.replace(item, "<span class=\"highlight\">" + item + "</span>") el.set "html", h tr.setStyle "visibility", "visible" else tr.removeProperty "style" h = c.replace(reg, "") el.set "html", h # $("contains").addEvent "keyup", (e) -> # e.stop() # search = @value # if search.length > 2 # $clear @timeoutID if @timeoutID # @timeoutID = filterArticles.delay(500, this, search) # $("cleanFilter").addEvent "click", (e) -> # reg = new RegExp("<span class=\"highlight\"[^><]*>|<.span[^><]*>", "g") # $("contains").setProperty("value", "").set "text", "" # $$("#articlesTable tr").each (el) -> # el.removeProperty "style" # $$("#articlesTable .text").each (el) -> # c = el.get("html") # c = c.replace(reg, "") # el.set "html", c ION.initToolbox "articles_toolbox"
true
# Article list page in backend # # Nodize CMS # https://github.com/nodize/nodizecms # # Original page design : # IonizeCMS (http://www.ionizecms.com), # (c) Partikule (http://www.partikule.net) # # CoffeeKup conversion & adaptation : # Hypee (http://hypee.com) # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # @include = -> # # Article list & types & categories edition # @view backend_articleList: -> html -> # Filters form : # - Pages # - Search field (title, content, etc.) div '#maincolumn', -> h2 '#main-title.main.articles', 'Articles' # 'Tabs' div '#articlesTab.mainTabs', -> ul '.tab-menu', -> # li -> # a -> # span 'Articles' li -> a -> span 'Categories' li -> a -> span 'Types' div class:'clear' # 'Articles list' div '#articlesTabContent', -> # div '.tabcontent', -> # 'Article list filtering' # form '#filterArticles', -> # label '.left', title: 'Filter articles (not fully implemented)', 'Filter' # input '#contains.inputtext.w160 left', type: 'text' # a id: 'cleanFilter', class: 'icon clearfield left ml5' # table '#articlesTable.list', -> # thead -> # tr -> # th 'Title' # th axis: 'string', 'Pages' # th axis: 'string', style: 'width:30px;', 'Content' # th '.right', style: 'width:70px;', 'Actions' # tbody -> # tr '.article1', -> # td '.title', style: 'overflow:hidden;', -> # div style: 'overflow:hidden;', -> # span '.toggler.left', rel: 'content1', -> # a class: 'left article', rel: '0.1', -> # span class:'flag flag0' # text '404' # div '#content1.content', -> # div '.text', -> # div '.mr10.left langcontent dl', style: 'width:90%;', -> # img '.pr5', src: 'http://192.168.1.162/themes/admin/images/world_flags/flag_en.gif' # div -> # p 'The content you asked was not found !' # td -> # img '.help', src: 'http://1PI:IP_ADDRESS:192.168.3.11END_PI2/themes/admin/images/icon_16_alert.png', title: 'Orphan article. Not linked to any page.' # td -> # img '.pr5', src: 'http://192.168.1.162/themes/admin/images/world_flags/flag_en.gif' # comment '<td><img class="pr5" src="http://192.168.1.162/themes/admin/images/world_flags/flag_en.gif" /></td>' # td -> # a class: 'icon right delete', rel: '1' # a class: 'icon right duplicate mr5', rel: '1|404' # a class: 'icon right edit mr5', rel: '1', title: '404' # --------------------------- 'Categories' div '.tabcontent', -> div '.tabsidecolumn', -> h3 'New category' form '#newCategoryForm', name: 'newCategoryForm', action: '/admin/category/save', -> # 'Name' dl '.small', -> dt -> label for: 'name', 'Name' dd -> input '#name.inputtext.required', name: 'name', type: 'text', value: '' fieldset '#blocks', -> # 'Category Lang Tabs' div '#categoryTab.mainTabs', -> ul '.tab-menu', -> for lang in Static_langs_records li '.tab_category', rel: lang.lang, -> a -> span -> lang.name div class:'clear' # 'Category Content' div '#categoryTabContent', -> for lang in Static_langs_records div '.tabcontentcat', -> # 'title' dl '.small', -> dt -> label for: "title_#{lang.lang}", 'Title' dd -> input "#title_#{lang.lang}.inputtext", name: "title_#{lang.lang}", type: 'text', value: '' # 'subtitle' dl '.small', -> dt -> label for: "subtitle_#{lang.lang}", 'Subtitle' dd -> input "#subtitle_#{lang.lang}.inputtext", name: "subtitle_#{lang.lang}", type: 'text', value: '' # 'description' dl '.small', -> dt -> label for: "descriptionCategory#{lang.lang}", 'Description' dd -> textarea "#descriptionCategory#{lang.lang}.tinyCategory", name: "description_#{lang.lang}", rel: lang.lang # 'save button' dl '.small', -> dt '&#160;' dd -> button '#bSaveNewCategory.button.yes', type: 'button', 'Save' div '#categoriesContainer.tabcolumn.pt15', '' # ------------------------------------------------- Types div '.tabcontent', -> # 'New type' div '.tabsidecolumn', -> h3 'New type' form '#newTypeForm', name: 'newTypeForm', action: "/admin/article_type\/\/save", -> # 'Name' dl '.small', -> dt -> label for: 'type', 'Type' dd -> input '#type.inputtext', name: 'type', type: 'text', value: '' # 'Flag' dl '.small', -> dt -> label for: 'flag0', title: 'An internal marked, just to be organized.', 'Flag' dd -> label class:'flag flag0', -> input '#flag0.inputradio', name: 'type_flag', type: 'radio', value: '0' label '.flag.flag1', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '1' label '.flag.flag2', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '2' label '.flag.flag3', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '3' label '.flag.flag4', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '4' label '.flag.flag5', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '5' label '.flag.flag6', -> input '.inputradio', name: 'type_flag', type: 'radio', value: '6' # 'Description' dl '.small', -> dt -> label for: 'descriptionType', 'Description' dd -> textarea '#descriptionType.tinyType', name: 'description' # 'save button' dl '.small', -> dt '&#160;' dd -> button '#bSaveNewType.button.yes', type: 'button', 'Save' # 'Existing types' div id:'articleTypesContainer', class:'tabcolumn pt15' # 'Articles Markers' coffeescript -> # # Make each article draggable # # $$("#articlesTable .article").each (item, idx) -> # ION.addDragDrop item, ".dropArticleInPage,.dropArticleAsLink,.folder", "ION.dropArticleInPage,ION.dropArticleAsLink,ION.dropArticleInPage" # # Adds Sortable function to the user list table # # new SortableTable("articlesTable", # sortOn: 0 # sortBy: "ASC" # ) # ION.initLabelHelpLinks "#articlesTable" # ION.initLabelHelpLinks "#filterArticles" # # Categories list # ION.HTML admin_url + "category\/\/get_list", "", update: "categoriesContainer" # # New category Form submit # $("bSaveNewCategory").addEvent "click", (e) -> e.stop() ION.sendData admin_url + "category\/\/save", $("newCategoryForm") # # New category tabs (langs) # new TabSwapper( tabsContainer: "categoryTab" sectionsContainer: "categoryTabContent" selectedClass: "selected" deselectedClass: "" tabs: "li" clickers: "li a" sections: "div.tabcontentcat" cookieName: "categoryTab" ) # # TinyEditors # Must be called after tabs init. # ION.initTinyEditors ".tab_category", "#categoryTabContent .tinyCategory", "small" # # Type list # ION.HTML admin_url + "article_type\/\/get_list", "", update: "articleTypesContainer" # # New Type Form submit # $("bSaveNewType").addEvent "click", (e) -> e.stop() ION.sendData admin_url + "article_type\/\/save", $("newTypeForm") # # Articles Tabs # new TabSwapper( tabsContainer: "articlesTab" sectionsContainer: "articlesTabContent" selectedClass: "selected" deselectedClass: "" tabs: "li" clickers: "li a" sections: "div.tabcontent" cookieName: "articlesTab" ) # # Table action icons # confirmDeleteMessage = Lang.get("ionize_confirm_element_delete") url = admin_url + "article/delete/" $$("#articlesTable .delete").each (item) -> ION.initRequestEvent item, url + item.getProperty("rel"), {}, message: confirmDeleteMessage $$("#articlesTable .duplicate").each (item) -> rel = item.getProperty("rel").split("|") id = rel[0] url = rel[1] item.addEvent "click", (e) -> e.stop() ION.formWindow "DuplicateArticle", "newArticleForm", "ionize_title_duplicate_article", "article/duplicate/" + id + "/" + url, width: 520 height: 280 $$("#articlesTable .edit").each (item) -> id_article = item.getProperty("rel") title = item.getProperty("title") item.addEvent "click", (e) -> e.stop() MUI.Content.update element: $("mainPanel") loadMethod: "xhr" url: admin_url + "article/edit/0." + id_article title: Lang.get("ionize_title_edit_article") + " : " + title # # Content togglers # calculateTableLineSizes = -> $$("#articlesTable tbody tr td.title").each (el) -> c = el.getFirst(".content") toggler = el.getElement(".toggler") text = c.getFirst() s = text.getDimensions() if s.height > 0 toggler.store "max", s.height + 10 if toggler.hasClass("expand") el.setStyles height: 20 + s.height + "px" c.setStyles height: s.height + "px" else toggler.store "max", s.height window.removeEvent "resize", calculateTableLineSizes window.addEvent "resize", -> calculateTableLineSizes() window.fireEvent "resize" $$("#articlesTable tbody tr td .toggler").each (el) -> el.fx = new Fx.Morph($(el.getProperty("rel")), duration: 200 transition: Fx.Transitions.Sine.easeOut ) el.fx2 = new Fx.Morph($(el.getParent("td")), duration: 200 transition: Fx.Transitions.Sine.easeOut ) $(el.getProperty("rel")).setStyles height: "0px" toggleArticle = (e) -> # this.fx.toggle(); e.stop() @toggleClass "expand" max = @retrieve("max") from = 0 to = max if @hasClass("expand") is 0 from = max to = 0 @getParent("tr").removeClass "highlight" else @getParent("tr").addClass "highlight" @fx.start height: [ from, to ] @fx2.start height: [ from + 20, to + 20 ] $$("#articlesTable tbody tr td .toggler").addEvent "click", toggleArticle $$("#articlesTable tbody tr td.title").addEvent "click", (e) -> @getElement(".toggler").fireEvent "click", e $$("#articlesTable tbody tr td .content").addEvent "click", (e) -> @getParent("td").getElement(".toggler").fireEvent "click", e # # Filtering # filterArticles = (search) -> reg = new RegExp("<span class=\"highlight\"[^><]*>|<.span[^><]*>", "g") search = RegExp(search, "gi") $$("#articlesTable .text").each (el) -> c = el.get("html") tr = el.getParent("tr") m = c.match(search) if m tr.setStyles "background-color": "#FDFCED" h = c h = h.replace(reg, "") m.each (item) -> h = h.replace(item, "<span class=\"highlight\">" + item + "</span>") el.set "html", h tr.setStyle "visibility", "visible" else tr.removeProperty "style" h = c.replace(reg, "") el.set "html", h # $("contains").addEvent "keyup", (e) -> # e.stop() # search = @value # if search.length > 2 # $clear @timeoutID if @timeoutID # @timeoutID = filterArticles.delay(500, this, search) # $("cleanFilter").addEvent "click", (e) -> # reg = new RegExp("<span class=\"highlight\"[^><]*>|<.span[^><]*>", "g") # $("contains").setProperty("value", "").set "text", "" # $$("#articlesTable tr").each (el) -> # el.removeProperty "style" # $$("#articlesTable .text").each (el) -> # c = el.get("html") # c = c.replace(reg, "") # el.set "html", c ION.initToolbox "articles_toolbox"
[ { "context": "key: 'table-psv'\n\npatterns: [\n\n # Matches PSV tables.\n #\n # Ex", "end": 15, "score": 0.9693195223808289, "start": 6, "tag": "KEY", "value": "table-psv" } ]
grammars/repositories/tables/psv-table-grammar.cson
andrewcarver/atom-language-asciidoc
45
key: 'table-psv' patterns: [ # Matches PSV tables. # # Examples: # # |=== # |1 >s|2 |3 |4 # ^|5 2.2+^.^|6 .3+<.>m|7 # ^|8 # |9 2+>|10 # |=== # name: 'markup.table.asciidoc' begin: '^(\\|===)$' beginCaptures: 0: name: 'markup.table.delimiter.asciidoc' contentName: 'markup.table.content.asciidoc' patterns: [ comment: 'cell separator and attributes' match: '(^|[^\\p{Blank}\\\\]*)(?<!\\\\)(\\|)' captures: 1: name: 'markup.meta.attribute-list.asciidoc' 2: name: 'markup.table.cell.delimiter.asciidoc' , include: '#tables-includes' ] end: '^(\\1)$' endCaptures: 0: name: 'markup.table.delimiter.asciidoc' ]
125638
key: '<KEY>' patterns: [ # Matches PSV tables. # # Examples: # # |=== # |1 >s|2 |3 |4 # ^|5 2.2+^.^|6 .3+<.>m|7 # ^|8 # |9 2+>|10 # |=== # name: 'markup.table.asciidoc' begin: '^(\\|===)$' beginCaptures: 0: name: 'markup.table.delimiter.asciidoc' contentName: 'markup.table.content.asciidoc' patterns: [ comment: 'cell separator and attributes' match: '(^|[^\\p{Blank}\\\\]*)(?<!\\\\)(\\|)' captures: 1: name: 'markup.meta.attribute-list.asciidoc' 2: name: 'markup.table.cell.delimiter.asciidoc' , include: '#tables-includes' ] end: '^(\\1)$' endCaptures: 0: name: 'markup.table.delimiter.asciidoc' ]
true
key: 'PI:KEY:<KEY>END_PI' patterns: [ # Matches PSV tables. # # Examples: # # |=== # |1 >s|2 |3 |4 # ^|5 2.2+^.^|6 .3+<.>m|7 # ^|8 # |9 2+>|10 # |=== # name: 'markup.table.asciidoc' begin: '^(\\|===)$' beginCaptures: 0: name: 'markup.table.delimiter.asciidoc' contentName: 'markup.table.content.asciidoc' patterns: [ comment: 'cell separator and attributes' match: '(^|[^\\p{Blank}\\\\]*)(?<!\\\\)(\\|)' captures: 1: name: 'markup.meta.attribute-list.asciidoc' 2: name: 'markup.table.cell.delimiter.asciidoc' , include: '#tables-includes' ] end: '^(\\1)$' endCaptures: 0: name: 'markup.table.delimiter.asciidoc' ]
[ { "context": "# @Author: Guan Gui <guiguan>\n# @Date: 2016-01-21T00:44:50+11:00\n# ", "end": 19, "score": 0.9998207688331604, "start": 11, "tag": "NAME", "value": "Guan Gui" }, { "context": "# @Author: Guan Gui <guiguan>\n# @Date: 2016-01-21T00:44:50+11:00\n# @Email: ", "end...
menus/file-header.cson
Shinrai/file-header
38
# @Author: Guan Gui <guiguan> # @Date: 2016-01-21T00:44:50+11:00 # @Email: root@guiguan.net # @Last modified by: guiguan # @Last modified time: 2016-05-09T08:55:14+08:00 # See https://atom.io/docs/latest/hacking-atom-package-word-count#menus for more details 'context-menu': 'atom-text-editor': [ 'label': 'File Header' 'submenu': [ { 'label': 'Add Header' 'command': 'file-header:add' }, { 'label': 'Update Header' 'command': 'file-header:update' }, { 'label': 'Disable Auto Update' 'command': 'file-header:toggleAutoUpdateEnabledStatus' } ] ] 'menu': [ { 'label': 'Packages' 'submenu': [ 'label': 'File Header' 'submenu': [ { 'label': 'Add Header' 'command': 'file-header:add' }, { 'label': 'Update Header' 'command': 'file-header:update' }, { 'label': 'Disable Auto Update' 'command': 'file-header:toggleAutoUpdateEnabledStatus' } ] ] } ]
174701
# @Author: <NAME> <guiguan> # @Date: 2016-01-21T00:44:50+11:00 # @Email: <EMAIL> # @Last modified by: guiguan # @Last modified time: 2016-05-09T08:55:14+08:00 # See https://atom.io/docs/latest/hacking-atom-package-word-count#menus for more details 'context-menu': 'atom-text-editor': [ 'label': 'File Header' 'submenu': [ { 'label': 'Add Header' 'command': 'file-header:add' }, { 'label': 'Update Header' 'command': 'file-header:update' }, { 'label': 'Disable Auto Update' 'command': 'file-header:toggleAutoUpdateEnabledStatus' } ] ] 'menu': [ { 'label': 'Packages' 'submenu': [ 'label': 'File Header' 'submenu': [ { 'label': 'Add Header' 'command': 'file-header:add' }, { 'label': 'Update Header' 'command': 'file-header:update' }, { 'label': 'Disable Auto Update' 'command': 'file-header:toggleAutoUpdateEnabledStatus' } ] ] } ]
true
# @Author: PI:NAME:<NAME>END_PI <guiguan> # @Date: 2016-01-21T00:44:50+11:00 # @Email: PI:EMAIL:<EMAIL>END_PI # @Last modified by: guiguan # @Last modified time: 2016-05-09T08:55:14+08:00 # See https://atom.io/docs/latest/hacking-atom-package-word-count#menus for more details 'context-menu': 'atom-text-editor': [ 'label': 'File Header' 'submenu': [ { 'label': 'Add Header' 'command': 'file-header:add' }, { 'label': 'Update Header' 'command': 'file-header:update' }, { 'label': 'Disable Auto Update' 'command': 'file-header:toggleAutoUpdateEnabledStatus' } ] ] 'menu': [ { 'label': 'Packages' 'submenu': [ 'label': 'File Header' 'submenu': [ { 'label': 'Add Header' 'command': 'file-header:add' }, { 'label': 'Update Header' 'command': 'file-header:update' }, { 'label': 'Disable Auto Update' 'command': 'file-header:toggleAutoUpdateEnabledStatus' } ] ] } ]
[ { "context": "orms jQuery UI editors 1.0.0\n\n Copyright (c) 2016 Tomasz Jakub Rup\n\n https://github.com/tomi77/backbone-forms-jquer", "end": 83, "score": 0.9998806118965149, "start": 67, "tag": "NAME", "value": "Tomasz Jakub Rup" }, { "context": "t (c) 2016 Tomasz Jakub Rup\n\n ...
src/index.coffee
tomi77/backbone-forms-jquery-ui
0
### Backbone-Forms jQuery UI editors 1.0.0 Copyright (c) 2016 Tomasz Jakub Rup https://github.com/tomi77/backbone-forms-jquery-ui Released under the MIT license ### require './autocomplete' require './checkbox' require './checkboxes' require './datepicker' require './radio' require './selectmenu' require './slider' require './spinner'
143526
### Backbone-Forms jQuery UI editors 1.0.0 Copyright (c) 2016 <NAME> https://github.com/tomi77/backbone-forms-jquery-ui Released under the MIT license ### require './autocomplete' require './checkbox' require './checkboxes' require './datepicker' require './radio' require './selectmenu' require './slider' require './spinner'
true
### Backbone-Forms jQuery UI editors 1.0.0 Copyright (c) 2016 PI:NAME:<NAME>END_PI https://github.com/tomi77/backbone-forms-jquery-ui Released under the MIT license ### require './autocomplete' require './checkbox' require './checkboxes' require './datepicker' require './radio' require './selectmenu' require './slider' require './spinner'
[ { "context": " extensions unit tests\n#\n# Copyright (C) 2011-2013 Nikolay Nemshilov\n#\nLovely = require('lovely')\n{Test, assert} = Lov", "end": 82, "score": 0.9998896718025208, "start": 65, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/lang/test/function_test.coffee
lovely-io/lovely.io-stl
2
# # The string extensions unit tests # # Copyright (C) 2011-2013 Nikolay Nemshilov # Lovely = require('lovely') {Test, assert} = Lovely eval(Test.build) describe "Function extensions", -> describe "#bind(scope[, arg, ...])", -> it "should make a proxy function that will call the original in given scope", -> scope = null original = -> scope = @; return "value" object = {} proxy = original.bind(object) assert.notStrictEqual object, proxy assert.equal "value", proxy() assert.strictEqual object, scope it "should bypass any arguments into the original function", -> args = null original = -> args = Lovely.A(arguments) proxy = original.bind({}) assert.deepEqual [1,2,3], proxy(1,2,3) it "should left curry any binded arguments", -> args = null original = -> args = Lovely.A(arguments) proxy = original.bind({}, 1, 2) assert.deepEqual [1,2,3], proxy(3) describe "#curry(arg[, arg, ...])", -> it "should create a new proxy function that will call the original", -> called = false original = -> called = true; "result" proxy = original.curry(1,2,3) assert.notStrictEqual original, proxy assert.equal "result", proxy() assert.isTrue called it "should left-curry additional arguments", -> args = null original = -> args = Lovely.A(arguments) proxy = original.curry(1,2) assert.deepEqual [1,2,3], proxy(3) describe "#rcurry(arg[, arg, ..])", -> it "should create a new proxy function that will call the original", -> called = false original = -> called = true; "result" proxy = original.rcurry(1,2,3) assert.notStrictEqual original, proxy assert.equal "result", proxy() assert.isTrue called it "should left-curry additional arguments", -> args = null original = -> args = Lovely.A(arguments) proxy = original.rcurry(1,2) assert.deepEqual [3,1,2], proxy(3) describe "#delay(ms, [, arg, ...])", -> it "should initialize a delayed call", -> stash = global.setTimeout args = null global.setTimeout = -> args = Lovely.A(arguments); 12345 original = -> marker = original.delay(1000) assert.equal args[1], 1000 assert.instanceOf args[0], Function assert.instanceOf marker, Number assert.equal marker, 12345 assert.instanceOf marker.cancel, Function global.setTimeout = stash describe "#periodical(ms, [, arg, ...])", -> it "should initialize periodical calls", -> stash = global.setInterval args = null global.setInterval = -> args = Lovely.A(arguments); 12345 original = -> marker = original.periodical(1000) assert.equal args[1], 1000 assert.instanceOf args[0], Function assert.instanceOf marker, Number assert.equal marker, 12345 assert.instanceOf marker.stop, Function global.setInterval = stash
54892
# # The string extensions unit tests # # Copyright (C) 2011-2013 <NAME> # Lovely = require('lovely') {Test, assert} = Lovely eval(Test.build) describe "Function extensions", -> describe "#bind(scope[, arg, ...])", -> it "should make a proxy function that will call the original in given scope", -> scope = null original = -> scope = @; return "value" object = {} proxy = original.bind(object) assert.notStrictEqual object, proxy assert.equal "value", proxy() assert.strictEqual object, scope it "should bypass any arguments into the original function", -> args = null original = -> args = Lovely.A(arguments) proxy = original.bind({}) assert.deepEqual [1,2,3], proxy(1,2,3) it "should left curry any binded arguments", -> args = null original = -> args = Lovely.A(arguments) proxy = original.bind({}, 1, 2) assert.deepEqual [1,2,3], proxy(3) describe "#curry(arg[, arg, ...])", -> it "should create a new proxy function that will call the original", -> called = false original = -> called = true; "result" proxy = original.curry(1,2,3) assert.notStrictEqual original, proxy assert.equal "result", proxy() assert.isTrue called it "should left-curry additional arguments", -> args = null original = -> args = Lovely.A(arguments) proxy = original.curry(1,2) assert.deepEqual [1,2,3], proxy(3) describe "#rcurry(arg[, arg, ..])", -> it "should create a new proxy function that will call the original", -> called = false original = -> called = true; "result" proxy = original.rcurry(1,2,3) assert.notStrictEqual original, proxy assert.equal "result", proxy() assert.isTrue called it "should left-curry additional arguments", -> args = null original = -> args = Lovely.A(arguments) proxy = original.rcurry(1,2) assert.deepEqual [3,1,2], proxy(3) describe "#delay(ms, [, arg, ...])", -> it "should initialize a delayed call", -> stash = global.setTimeout args = null global.setTimeout = -> args = Lovely.A(arguments); 12345 original = -> marker = original.delay(1000) assert.equal args[1], 1000 assert.instanceOf args[0], Function assert.instanceOf marker, Number assert.equal marker, 12345 assert.instanceOf marker.cancel, Function global.setTimeout = stash describe "#periodical(ms, [, arg, ...])", -> it "should initialize periodical calls", -> stash = global.setInterval args = null global.setInterval = -> args = Lovely.A(arguments); 12345 original = -> marker = original.periodical(1000) assert.equal args[1], 1000 assert.instanceOf args[0], Function assert.instanceOf marker, Number assert.equal marker, 12345 assert.instanceOf marker.stop, Function global.setInterval = stash
true
# # The string extensions unit tests # # Copyright (C) 2011-2013 PI:NAME:<NAME>END_PI # Lovely = require('lovely') {Test, assert} = Lovely eval(Test.build) describe "Function extensions", -> describe "#bind(scope[, arg, ...])", -> it "should make a proxy function that will call the original in given scope", -> scope = null original = -> scope = @; return "value" object = {} proxy = original.bind(object) assert.notStrictEqual object, proxy assert.equal "value", proxy() assert.strictEqual object, scope it "should bypass any arguments into the original function", -> args = null original = -> args = Lovely.A(arguments) proxy = original.bind({}) assert.deepEqual [1,2,3], proxy(1,2,3) it "should left curry any binded arguments", -> args = null original = -> args = Lovely.A(arguments) proxy = original.bind({}, 1, 2) assert.deepEqual [1,2,3], proxy(3) describe "#curry(arg[, arg, ...])", -> it "should create a new proxy function that will call the original", -> called = false original = -> called = true; "result" proxy = original.curry(1,2,3) assert.notStrictEqual original, proxy assert.equal "result", proxy() assert.isTrue called it "should left-curry additional arguments", -> args = null original = -> args = Lovely.A(arguments) proxy = original.curry(1,2) assert.deepEqual [1,2,3], proxy(3) describe "#rcurry(arg[, arg, ..])", -> it "should create a new proxy function that will call the original", -> called = false original = -> called = true; "result" proxy = original.rcurry(1,2,3) assert.notStrictEqual original, proxy assert.equal "result", proxy() assert.isTrue called it "should left-curry additional arguments", -> args = null original = -> args = Lovely.A(arguments) proxy = original.rcurry(1,2) assert.deepEqual [3,1,2], proxy(3) describe "#delay(ms, [, arg, ...])", -> it "should initialize a delayed call", -> stash = global.setTimeout args = null global.setTimeout = -> args = Lovely.A(arguments); 12345 original = -> marker = original.delay(1000) assert.equal args[1], 1000 assert.instanceOf args[0], Function assert.instanceOf marker, Number assert.equal marker, 12345 assert.instanceOf marker.cancel, Function global.setTimeout = stash describe "#periodical(ms, [, arg, ...])", -> it "should initialize periodical calls", -> stash = global.setInterval args = null global.setInterval = -> args = Lovely.A(arguments); 12345 original = -> marker = original.periodical(1000) assert.equal args[1], 1000 assert.instanceOf args[0], Function assert.instanceOf marker, Number assert.equal marker, 12345 assert.instanceOf marker.stop, Function global.setInterval = stash
[ { "context": "sociationCursorUser extends Tower.Model\n @field 'username'\n\n @hasMany 'associationCursorTests'\n\n @validat", "end": 2229, "score": 0.9983112812042236, "start": 2221, "tag": "USERNAME", "value": "username" }, { "context": " @hasMany 'associationCursorTests'\n\n @...
test/cases/model/shared/relation/associationCursorTest.coffee
jivagoalves/tower
1
# It seems there can be distinct optimizations for client/server association persistence. # For the server, the "context" need to be scoped to the current request, you have to save the models in callbacks. # One workaround may be to do things like App.User.env(@).where..., where `env` is the controller, so you're # creating a cursor mapped to the current request. This way you can create an identity-map/cache of records on a per-request basis. # Otherwise, you have to do what rails does and have the AutosaveAssociations callbacks. # On the client, however, it may be better to do something like what ember-data is doing with a global transaction. # When any of the models change, they are added to a global bucket, then at some point they are all synced. # There would be some complications with hasMany through records b/c of ids using that approach, but # it would mean that whenever you call `record.save()`, it doesn't have to go through all those callbacks; it # would only have to do what happens in the `set` method for associations, such as `_setHasManyAssociation`, which # just nullifies/sets ids on the associated models - and then the global transaction would sync them all in a simple way, # just calling save/destroy on each. For now though, we can do this in phases: # 1. get it working on client/server the way rails does it with autosave associations. # 2. try out a global transaction on the client and see if that simplifies things. # If so, remove the autosave stuff on the client and build something custom. # 3. try the `env` thing in the controller, so you're creating an identity map in the controllers # on a per-request basis. This will pave the way for creating "database transactions" (or getting # as close as possible to them with mongodb). We may find this may work like the client-side global transaction. class App.AssociationCursorTest extends Tower.Model @hasMany 'associationCursorPosts' @hasOne 'associationCursorAddress' @belongsTo 'associationCursorUser' class App.AssociationCursorPost extends Tower.Model @field 'title' @belongsTo 'associationCursorTest' @validates 'title', presence: true class App.AssociationCursorUser extends Tower.Model @field 'username' @hasMany 'associationCursorTests' @validates 'username', presence: true class App.AssociationCursorAddress extends Tower.Model @field 'city' @field 'state' @belongsTo 'associationCursorTest' @validates 'city', 'state', presence: true describe "Tower.ModelRelation (association cursor)", -> record = null cursor = null association = null key = null describe 'new owner', -> describe 'hasMany', -> beforeEach -> record = App.AssociationCursorTest.build() cursor = record.getAssociationCursor('associationCursorPosts') association = record.constructor.relations()['associationCursorPosts'] test 'getAssociation', -> assert.isTrue record.getAssociationScope('associationCursorPosts') instanceof Tower.ModelScope, "record.getAssociationScope('associationCursorPosts') instanceof Tower.ModelScope" assert.isTrue record.getAssociationScope('associationCursorPosts').cursor.isHasMany, 'cursor.isHasMany' assert.isTrue record.getAssociationCursor('associationCursorPosts').isHasMany, 'getAssociationCursor("associationCursorPosts").isHasMany' test 'setHasManyAssociation', -> assert.equal cursor.get('content').length, 0 # pass single item record._setHasManyAssociation('associationCursorPosts', App.AssociationCursorPost.build(), association) assert.equal cursor.get('content').length, 1 # pass single item in array record._setHasManyAssociation('associationCursorPosts', [App.AssociationCursorPost.build()], association) assert.equal cursor.get('content').length, 1 # pass multiple items in array record._setHasManyAssociation('associationCursorPosts', [App.AssociationCursorPost.build(), App.AssociationCursorPost.build()], association) assert.equal cursor.get('content').length, 2 test '_associatedRecordsToValidateOrSave(cursor, isNew: true, autosave: false)', -> assert.equal record._associatedRecordsToValidateOrSave(cursor, true).length, 0 record._setHasManyAssociation('associationCursorPosts', App.AssociationCursorPost.build(), association) assert.equal record._associatedRecordsToValidateOrSave(cursor, true).length, 1 test '_associatedRecordsToValidateOrSave(cursor, isNew: false, autosave: true) should return records where record._changedForAutosave() is true', -> newRecord = App.AssociationCursorPost.build() existingRecord = App.AssociationCursorPost.build() existingRecord.setProperties(isNew: false, isDirty: false, id: 10) record._setHasManyAssociation('associationCursorPosts', [newRecord, existingRecord], association) assert.equal record._associatedRecordsToValidateOrSave(cursor, false, true).length, 1 test '_associatedRecordsToValidateOrSave(cursor, isNew: false, autosave: false) should return new records', -> newRecord = App.AssociationCursorPost.build() existingRecord = App.AssociationCursorPost.build() existingRecord.setProperties(isNew: false) record._setHasManyAssociation('associationCursorPosts', [newRecord, existingRecord], association) assert.equal record._associatedRecordsToValidateOrSave(cursor, false, false).length, 1 test '_validateCollectionAssociation', -> record._setHasManyAssociation('associationCursorPosts', [App.AssociationCursorPost.build()], association) assert.isFalse record._validateCollectionAssociation(association), 'record._validateCollectionAssociation(association)' # @todo what should the error message be? assert.deepEqual record.get('errors'), {associationCursorPosts: ['Invalid']} record.set('errors', {}) # don't know how to clear the errors in this case yet record._setHasManyAssociation('associationCursorPosts', App.AssociationCursorPost.build(title: 'A Title!'), association) assert.isTrue record._validateCollectionAssociation(association), 'record._validateCollectionAssociation(association)' test 'set', -> record.set('associationCursorPosts', App.AssociationCursorPost.build(title: 'A Title!')) assert.isTrue record._validateCollectionAssociation(association), 'record._validateCollectionAssociation(association)' test '_saveCollectionAssociation', (done) -> record.save => child = App.AssociationCursorPost.build(title: 'A Title!') record.set('associationCursorPosts', child) record._saveCollectionAssociation association, => assert.equal child.get('associationCursorTest').get('id').toString(), record.get('id').toString() done() test 'save', (done) -> child = App.AssociationCursorPost.build(title: 'A Title!') record.set('associationCursorPosts', child) record.save => assert.ok record.get('id') assert.equal child.get('associationCursorTestId').toString(), record.get('id').toString() done() test 'replace', (done) -> child1 = App.AssociationCursorPost.build(title: 'First Title!') record.updateAttributes associationCursorPosts: [child1], => firstId = child1.get('associationCursorTestId').toString() assert.ok firstId, '1' child2 = App.AssociationCursorPost.build(title: 'Second Title!') record.updateAttributes associationCursorPosts: [child2], => secondId = child2.get('associationCursorTestId') assert.ok secondId, '2' assert.equal firstId.toString(), secondId.toString(), '3' # @todo assert.isUndefined child1.get('associationCursorTestId'), '4' assert.equal child2.get('associationCursorTestId').toString(), record.get('id').toString(), '5' record.get('associationCursorPosts').all (error, count) => assert.equal count.length, 1, '6' done() test 'nullify', (done) -> child1 = App.AssociationCursorPost.build(title: 'First Title!') record.updateAttributes associationCursorPosts: [child1], => record.updateAttributes associationCursorPosts: [], => assert.isUndefined child1.get('associationCursorTestId') record.get('associationCursorPosts').all (error, count) => assert.equal count.length, 0 done() describe 'belongsTo', -> beforeEach -> record = App.AssociationCursorTest.build() cursor = record.getAssociationCursor('associationCursorUser') association = record.constructor.relations()['associationCursorUser'] afterEach -> #association.autosave = undefined test 'getAssociation', -> assert.isTrue record.getAssociationScope('associationCursorUser') instanceof Tower.ModelScope, "record.getAssociationScope('associationCursorUser') instanceof Tower.ModelScope" assert.isTrue record.getAssociationScope('associationCursorUser').cursor.isBelongsTo, 'cursor.isBelongsTo' assert.isTrue record.getAssociationCursor('associationCursorUser').isBelongsTo, 'getAssociationCursor("associationCursorUser").isBelongsTo' test 'setBelongsToAssociation', -> assert.equal cursor.get('content').length, 0 # pass single item record._setBelongsToAssociation('associationCursorUser', App.AssociationCursorUser.build(), association) assert.equal cursor.get('content').length, 1 test '_validateSingleAssociation', -> record._setBelongsToAssociation('associationCursorUser', App.AssociationCursorUser.build(), association) assert.isFalse record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' assert.deepEqual record.get('errors'), {associationCursorUser: ['Invalid']} record.set('errors', {}) # don't know how to clear the errors in this case yet record._setBelongsToAssociation('associationCursorUser', App.AssociationCursorUser.build(username: 'fred'), association) assert.isTrue record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' test 'set', -> record.set('associationCursorUser', App.AssociationCursorUser.build(username: 'fred')) assert.isTrue record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' test '_saveBelongsToAssociation', (done) -> record.set('associationCursorUser', App.AssociationCursorUser.build(username: 'fred')) record._saveBelongsToAssociation association, => assert.ok record.get('associationCursorUser').get('id') done() test 'save', (done) -> record.set('associationCursorUser', App.AssociationCursorUser.build(username: 'john')) record.save => assert.ok record.get('id') assert.equal record.get('associationCursorUser').get('id').toString(), record.get('associationCursorUserId').toString() done() test 'replace', (done) -> record.updateAttributes associationCursorUser: App.AssociationCursorUser.build(username: 'john'), => firstId = record.get('associationCursorUserId') assert.ok firstId record.updateAttributes associationCursorUser: App.AssociationCursorUser.build(username: 'john'), => secondId = record.get('associationCursorUserId') assert.ok secondId assert.notEqual firstId.toString(), secondId.toString() done() test 'nullify', (done) -> record.updateAttributes associationCursorUser: App.AssociationCursorUser.build(username: 'john'), => record.updateAttributes associationCursorUser: null, => assert.isUndefined record.get('associationCursorUserId') done() describe 'hasOne', -> beforeEach -> record = App.AssociationCursorTest.build() key = 'associationCursorAddress' cursor = record.getAssociationCursor(key) association = record.constructor.relations()[key] test 'getAssociation', -> assert.isTrue record.getAssociationScope(key) instanceof Tower.ModelScope, "record.getAssociationScope(key) instanceof Tower.ModelScope" assert.isTrue record.getAssociationScope(key).cursor.isHasOne, 'cursor.isHasOne' assert.isTrue record.getAssociationCursor(key).isHasOne, 'getAssociationCursor("associationCursorUser").isHasOne' test 'setHasOneAssociation', -> assert.equal cursor.get('content').length, 0 # pass single item record._setHasOneAssociation(key, App.AssociationCursorAddress.build(), association) assert.equal cursor.get('content').length, 1 test '_validateSingleAssociation', -> record._setHasOneAssociation(key, App.AssociationCursorAddress.build(), association) assert.isFalse record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' assert.deepEqual record.get('errors'), {associationCursorAddress: ['Invalid']} record.set('errors', {}) # don't know how to clear the errors in this case yet record._setHasOneAssociation(key, App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA'), association) assert.isTrue record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' test 'set', -> record.set(key, App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA')) assert.isTrue record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' test '_saveHasOneAssociation', (done) -> record.save => child = App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA') record.set(key, child) record._saveHasOneAssociation association, => assert.equal child.get('associationCursorTestId').toString(), record.get('id').toString() done() test 'save', (done) -> child = App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA') record.set(key, child) record.save => assert.ok record.get('id') assert.equal child.get('associationCursorTestId').toString(), record.get('id').toString() done() test 'setting multiple times when parent is persistent', (done) -> record.save => App.AssociationCursorAddress.create city: 'San Francisco', state: 'CA', (error, child1) => child2 = App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA') record.set(key, child1) record.set(key, child2) assert.isUndefined record.getAssociationCursor(key)._markedForDestruction done() test 'setting multiple times when parent is persistent and relationship already existed', (done) -> child1 = App.AssociationCursorAddress.build city: 'San Francisco', state: 'CA' record.updateAttributes associationCursorAddress: child1, => child2 = App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA') record.set(key, child1) record.set(key, child2) assert.equal record.getAssociationCursor(key)._markedForDestruction, child1 done()
213850
# It seems there can be distinct optimizations for client/server association persistence. # For the server, the "context" need to be scoped to the current request, you have to save the models in callbacks. # One workaround may be to do things like App.User.env(@).where..., where `env` is the controller, so you're # creating a cursor mapped to the current request. This way you can create an identity-map/cache of records on a per-request basis. # Otherwise, you have to do what rails does and have the AutosaveAssociations callbacks. # On the client, however, it may be better to do something like what ember-data is doing with a global transaction. # When any of the models change, they are added to a global bucket, then at some point they are all synced. # There would be some complications with hasMany through records b/c of ids using that approach, but # it would mean that whenever you call `record.save()`, it doesn't have to go through all those callbacks; it # would only have to do what happens in the `set` method for associations, such as `_setHasManyAssociation`, which # just nullifies/sets ids on the associated models - and then the global transaction would sync them all in a simple way, # just calling save/destroy on each. For now though, we can do this in phases: # 1. get it working on client/server the way rails does it with autosave associations. # 2. try out a global transaction on the client and see if that simplifies things. # If so, remove the autosave stuff on the client and build something custom. # 3. try the `env` thing in the controller, so you're creating an identity map in the controllers # on a per-request basis. This will pave the way for creating "database transactions" (or getting # as close as possible to them with mongodb). We may find this may work like the client-side global transaction. class App.AssociationCursorTest extends Tower.Model @hasMany 'associationCursorPosts' @hasOne 'associationCursorAddress' @belongsTo 'associationCursorUser' class App.AssociationCursorPost extends Tower.Model @field 'title' @belongsTo 'associationCursorTest' @validates 'title', presence: true class App.AssociationCursorUser extends Tower.Model @field 'username' @hasMany 'associationCursorTests' @validates 'username', presence: true class App.AssociationCursorAddress extends Tower.Model @field 'city' @field 'state' @belongsTo 'associationCursorTest' @validates 'city', 'state', presence: true describe "Tower.ModelRelation (association cursor)", -> record = null cursor = null association = null key = null describe 'new owner', -> describe 'hasMany', -> beforeEach -> record = App.AssociationCursorTest.build() cursor = record.getAssociationCursor('associationCursorPosts') association = record.constructor.relations()['associationCursorPosts'] test 'getAssociation', -> assert.isTrue record.getAssociationScope('associationCursorPosts') instanceof Tower.ModelScope, "record.getAssociationScope('associationCursorPosts') instanceof Tower.ModelScope" assert.isTrue record.getAssociationScope('associationCursorPosts').cursor.isHasMany, 'cursor.isHasMany' assert.isTrue record.getAssociationCursor('associationCursorPosts').isHasMany, 'getAssociationCursor("associationCursorPosts").isHasMany' test 'setHasManyAssociation', -> assert.equal cursor.get('content').length, 0 # pass single item record._setHasManyAssociation('associationCursorPosts', App.AssociationCursorPost.build(), association) assert.equal cursor.get('content').length, 1 # pass single item in array record._setHasManyAssociation('associationCursorPosts', [App.AssociationCursorPost.build()], association) assert.equal cursor.get('content').length, 1 # pass multiple items in array record._setHasManyAssociation('associationCursorPosts', [App.AssociationCursorPost.build(), App.AssociationCursorPost.build()], association) assert.equal cursor.get('content').length, 2 test '_associatedRecordsToValidateOrSave(cursor, isNew: true, autosave: false)', -> assert.equal record._associatedRecordsToValidateOrSave(cursor, true).length, 0 record._setHasManyAssociation('associationCursorPosts', App.AssociationCursorPost.build(), association) assert.equal record._associatedRecordsToValidateOrSave(cursor, true).length, 1 test '_associatedRecordsToValidateOrSave(cursor, isNew: false, autosave: true) should return records where record._changedForAutosave() is true', -> newRecord = App.AssociationCursorPost.build() existingRecord = App.AssociationCursorPost.build() existingRecord.setProperties(isNew: false, isDirty: false, id: 10) record._setHasManyAssociation('associationCursorPosts', [newRecord, existingRecord], association) assert.equal record._associatedRecordsToValidateOrSave(cursor, false, true).length, 1 test '_associatedRecordsToValidateOrSave(cursor, isNew: false, autosave: false) should return new records', -> newRecord = App.AssociationCursorPost.build() existingRecord = App.AssociationCursorPost.build() existingRecord.setProperties(isNew: false) record._setHasManyAssociation('associationCursorPosts', [newRecord, existingRecord], association) assert.equal record._associatedRecordsToValidateOrSave(cursor, false, false).length, 1 test '_validateCollectionAssociation', -> record._setHasManyAssociation('associationCursorPosts', [App.AssociationCursorPost.build()], association) assert.isFalse record._validateCollectionAssociation(association), 'record._validateCollectionAssociation(association)' # @todo what should the error message be? assert.deepEqual record.get('errors'), {associationCursorPosts: ['Invalid']} record.set('errors', {}) # don't know how to clear the errors in this case yet record._setHasManyAssociation('associationCursorPosts', App.AssociationCursorPost.build(title: 'A Title!'), association) assert.isTrue record._validateCollectionAssociation(association), 'record._validateCollectionAssociation(association)' test 'set', -> record.set('associationCursorPosts', App.AssociationCursorPost.build(title: 'A Title!')) assert.isTrue record._validateCollectionAssociation(association), 'record._validateCollectionAssociation(association)' test '_saveCollectionAssociation', (done) -> record.save => child = App.AssociationCursorPost.build(title: 'A Title!') record.set('associationCursorPosts', child) record._saveCollectionAssociation association, => assert.equal child.get('associationCursorTest').get('id').toString(), record.get('id').toString() done() test 'save', (done) -> child = App.AssociationCursorPost.build(title: 'A Title!') record.set('associationCursorPosts', child) record.save => assert.ok record.get('id') assert.equal child.get('associationCursorTestId').toString(), record.get('id').toString() done() test 'replace', (done) -> child1 = App.AssociationCursorPost.build(title: 'First Title!') record.updateAttributes associationCursorPosts: [child1], => firstId = child1.get('associationCursorTestId').toString() assert.ok firstId, '1' child2 = App.AssociationCursorPost.build(title: 'Second Title!') record.updateAttributes associationCursorPosts: [child2], => secondId = child2.get('associationCursorTestId') assert.ok secondId, '2' assert.equal firstId.toString(), secondId.toString(), '3' # @todo assert.isUndefined child1.get('associationCursorTestId'), '4' assert.equal child2.get('associationCursorTestId').toString(), record.get('id').toString(), '5' record.get('associationCursorPosts').all (error, count) => assert.equal count.length, 1, '6' done() test 'nullify', (done) -> child1 = App.AssociationCursorPost.build(title: 'First Title!') record.updateAttributes associationCursorPosts: [child1], => record.updateAttributes associationCursorPosts: [], => assert.isUndefined child1.get('associationCursorTestId') record.get('associationCursorPosts').all (error, count) => assert.equal count.length, 0 done() describe 'belongsTo', -> beforeEach -> record = App.AssociationCursorTest.build() cursor = record.getAssociationCursor('associationCursorUser') association = record.constructor.relations()['associationCursorUser'] afterEach -> #association.autosave = undefined test 'getAssociation', -> assert.isTrue record.getAssociationScope('associationCursorUser') instanceof Tower.ModelScope, "record.getAssociationScope('associationCursorUser') instanceof Tower.ModelScope" assert.isTrue record.getAssociationScope('associationCursorUser').cursor.isBelongsTo, 'cursor.isBelongsTo' assert.isTrue record.getAssociationCursor('associationCursorUser').isBelongsTo, 'getAssociationCursor("associationCursorUser").isBelongsTo' test 'setBelongsToAssociation', -> assert.equal cursor.get('content').length, 0 # pass single item record._setBelongsToAssociation('associationCursorUser', App.AssociationCursorUser.build(), association) assert.equal cursor.get('content').length, 1 test '_validateSingleAssociation', -> record._setBelongsToAssociation('associationCursorUser', App.AssociationCursorUser.build(), association) assert.isFalse record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' assert.deepEqual record.get('errors'), {associationCursorUser: ['Invalid']} record.set('errors', {}) # don't know how to clear the errors in this case yet record._setBelongsToAssociation('associationCursorUser', App.AssociationCursorUser.build(username: 'fred'), association) assert.isTrue record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' test 'set', -> record.set('associationCursorUser', App.AssociationCursorUser.build(username: 'fred')) assert.isTrue record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' test '_saveBelongsToAssociation', (done) -> record.set('associationCursorUser', App.AssociationCursorUser.build(username: 'fred')) record._saveBelongsToAssociation association, => assert.ok record.get('associationCursorUser').get('id') done() test 'save', (done) -> record.set('associationCursorUser', App.AssociationCursorUser.build(username: 'john')) record.save => assert.ok record.get('id') assert.equal record.get('associationCursorUser').get('id').toString(), record.get('associationCursorUserId').toString() done() test 'replace', (done) -> record.updateAttributes associationCursorUser: App.AssociationCursorUser.build(username: 'john'), => firstId = record.get('associationCursorUserId') assert.ok firstId record.updateAttributes associationCursorUser: App.AssociationCursorUser.build(username: 'john'), => secondId = record.get('associationCursorUserId') assert.ok secondId assert.notEqual firstId.toString(), secondId.toString() done() test 'nullify', (done) -> record.updateAttributes associationCursorUser: App.AssociationCursorUser.build(username: 'john'), => record.updateAttributes associationCursorUser: null, => assert.isUndefined record.get('associationCursorUserId') done() describe 'hasOne', -> beforeEach -> record = App.AssociationCursorTest.build() key = 'association<KEY>' cursor = record.getAssociationCursor(key) association = record.constructor.relations()[key] test 'getAssociation', -> assert.isTrue record.getAssociationScope(key) instanceof Tower.ModelScope, "record.getAssociationScope(key) instanceof Tower.ModelScope" assert.isTrue record.getAssociationScope(key).cursor.isHasOne, 'cursor.isHasOne' assert.isTrue record.getAssociationCursor(key).isHasOne, 'getAssociationCursor("associationCursorUser").isHasOne' test 'setHasOneAssociation', -> assert.equal cursor.get('content').length, 0 # pass single item record._setHasOneAssociation(key, App.AssociationCursorAddress.build(), association) assert.equal cursor.get('content').length, 1 test '_validateSingleAssociation', -> record._setHasOneAssociation(key, App.AssociationCursorAddress.build(), association) assert.isFalse record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' assert.deepEqual record.get('errors'), {associationCursorAddress: ['Invalid']} record.set('errors', {}) # don't know how to clear the errors in this case yet record._setHasOneAssociation(key, App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA'), association) assert.isTrue record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' test 'set', -> record.set(key, App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA')) assert.isTrue record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' test '_saveHasOneAssociation', (done) -> record.save => child = App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA') record.set(key, child) record._saveHasOneAssociation association, => assert.equal child.get('associationCursorTestId').toString(), record.get('id').toString() done() test 'save', (done) -> child = App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA') record.set(key, child) record.save => assert.ok record.get('id') assert.equal child.get('associationCursorTestId').toString(), record.get('id').toString() done() test 'setting multiple times when parent is persistent', (done) -> record.save => App.AssociationCursorAddress.create city: 'San Francisco', state: 'CA', (error, child1) => child2 = App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA') record.set(key, child1) record.set(key, child2) assert.isUndefined record.getAssociationCursor(key)._markedForDestruction done() test 'setting multiple times when parent is persistent and relationship already existed', (done) -> child1 = App.AssociationCursorAddress.build city: 'San Francisco', state: 'CA' record.updateAttributes associationCursorAddress: child1, => child2 = App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA') record.set(key, child1) record.set(key, child2) assert.equal record.getAssociationCursor(key)._markedForDestruction, child1 done()
true
# It seems there can be distinct optimizations for client/server association persistence. # For the server, the "context" need to be scoped to the current request, you have to save the models in callbacks. # One workaround may be to do things like App.User.env(@).where..., where `env` is the controller, so you're # creating a cursor mapped to the current request. This way you can create an identity-map/cache of records on a per-request basis. # Otherwise, you have to do what rails does and have the AutosaveAssociations callbacks. # On the client, however, it may be better to do something like what ember-data is doing with a global transaction. # When any of the models change, they are added to a global bucket, then at some point they are all synced. # There would be some complications with hasMany through records b/c of ids using that approach, but # it would mean that whenever you call `record.save()`, it doesn't have to go through all those callbacks; it # would only have to do what happens in the `set` method for associations, such as `_setHasManyAssociation`, which # just nullifies/sets ids on the associated models - and then the global transaction would sync them all in a simple way, # just calling save/destroy on each. For now though, we can do this in phases: # 1. get it working on client/server the way rails does it with autosave associations. # 2. try out a global transaction on the client and see if that simplifies things. # If so, remove the autosave stuff on the client and build something custom. # 3. try the `env` thing in the controller, so you're creating an identity map in the controllers # on a per-request basis. This will pave the way for creating "database transactions" (or getting # as close as possible to them with mongodb). We may find this may work like the client-side global transaction. class App.AssociationCursorTest extends Tower.Model @hasMany 'associationCursorPosts' @hasOne 'associationCursorAddress' @belongsTo 'associationCursorUser' class App.AssociationCursorPost extends Tower.Model @field 'title' @belongsTo 'associationCursorTest' @validates 'title', presence: true class App.AssociationCursorUser extends Tower.Model @field 'username' @hasMany 'associationCursorTests' @validates 'username', presence: true class App.AssociationCursorAddress extends Tower.Model @field 'city' @field 'state' @belongsTo 'associationCursorTest' @validates 'city', 'state', presence: true describe "Tower.ModelRelation (association cursor)", -> record = null cursor = null association = null key = null describe 'new owner', -> describe 'hasMany', -> beforeEach -> record = App.AssociationCursorTest.build() cursor = record.getAssociationCursor('associationCursorPosts') association = record.constructor.relations()['associationCursorPosts'] test 'getAssociation', -> assert.isTrue record.getAssociationScope('associationCursorPosts') instanceof Tower.ModelScope, "record.getAssociationScope('associationCursorPosts') instanceof Tower.ModelScope" assert.isTrue record.getAssociationScope('associationCursorPosts').cursor.isHasMany, 'cursor.isHasMany' assert.isTrue record.getAssociationCursor('associationCursorPosts').isHasMany, 'getAssociationCursor("associationCursorPosts").isHasMany' test 'setHasManyAssociation', -> assert.equal cursor.get('content').length, 0 # pass single item record._setHasManyAssociation('associationCursorPosts', App.AssociationCursorPost.build(), association) assert.equal cursor.get('content').length, 1 # pass single item in array record._setHasManyAssociation('associationCursorPosts', [App.AssociationCursorPost.build()], association) assert.equal cursor.get('content').length, 1 # pass multiple items in array record._setHasManyAssociation('associationCursorPosts', [App.AssociationCursorPost.build(), App.AssociationCursorPost.build()], association) assert.equal cursor.get('content').length, 2 test '_associatedRecordsToValidateOrSave(cursor, isNew: true, autosave: false)', -> assert.equal record._associatedRecordsToValidateOrSave(cursor, true).length, 0 record._setHasManyAssociation('associationCursorPosts', App.AssociationCursorPost.build(), association) assert.equal record._associatedRecordsToValidateOrSave(cursor, true).length, 1 test '_associatedRecordsToValidateOrSave(cursor, isNew: false, autosave: true) should return records where record._changedForAutosave() is true', -> newRecord = App.AssociationCursorPost.build() existingRecord = App.AssociationCursorPost.build() existingRecord.setProperties(isNew: false, isDirty: false, id: 10) record._setHasManyAssociation('associationCursorPosts', [newRecord, existingRecord], association) assert.equal record._associatedRecordsToValidateOrSave(cursor, false, true).length, 1 test '_associatedRecordsToValidateOrSave(cursor, isNew: false, autosave: false) should return new records', -> newRecord = App.AssociationCursorPost.build() existingRecord = App.AssociationCursorPost.build() existingRecord.setProperties(isNew: false) record._setHasManyAssociation('associationCursorPosts', [newRecord, existingRecord], association) assert.equal record._associatedRecordsToValidateOrSave(cursor, false, false).length, 1 test '_validateCollectionAssociation', -> record._setHasManyAssociation('associationCursorPosts', [App.AssociationCursorPost.build()], association) assert.isFalse record._validateCollectionAssociation(association), 'record._validateCollectionAssociation(association)' # @todo what should the error message be? assert.deepEqual record.get('errors'), {associationCursorPosts: ['Invalid']} record.set('errors', {}) # don't know how to clear the errors in this case yet record._setHasManyAssociation('associationCursorPosts', App.AssociationCursorPost.build(title: 'A Title!'), association) assert.isTrue record._validateCollectionAssociation(association), 'record._validateCollectionAssociation(association)' test 'set', -> record.set('associationCursorPosts', App.AssociationCursorPost.build(title: 'A Title!')) assert.isTrue record._validateCollectionAssociation(association), 'record._validateCollectionAssociation(association)' test '_saveCollectionAssociation', (done) -> record.save => child = App.AssociationCursorPost.build(title: 'A Title!') record.set('associationCursorPosts', child) record._saveCollectionAssociation association, => assert.equal child.get('associationCursorTest').get('id').toString(), record.get('id').toString() done() test 'save', (done) -> child = App.AssociationCursorPost.build(title: 'A Title!') record.set('associationCursorPosts', child) record.save => assert.ok record.get('id') assert.equal child.get('associationCursorTestId').toString(), record.get('id').toString() done() test 'replace', (done) -> child1 = App.AssociationCursorPost.build(title: 'First Title!') record.updateAttributes associationCursorPosts: [child1], => firstId = child1.get('associationCursorTestId').toString() assert.ok firstId, '1' child2 = App.AssociationCursorPost.build(title: 'Second Title!') record.updateAttributes associationCursorPosts: [child2], => secondId = child2.get('associationCursorTestId') assert.ok secondId, '2' assert.equal firstId.toString(), secondId.toString(), '3' # @todo assert.isUndefined child1.get('associationCursorTestId'), '4' assert.equal child2.get('associationCursorTestId').toString(), record.get('id').toString(), '5' record.get('associationCursorPosts').all (error, count) => assert.equal count.length, 1, '6' done() test 'nullify', (done) -> child1 = App.AssociationCursorPost.build(title: 'First Title!') record.updateAttributes associationCursorPosts: [child1], => record.updateAttributes associationCursorPosts: [], => assert.isUndefined child1.get('associationCursorTestId') record.get('associationCursorPosts').all (error, count) => assert.equal count.length, 0 done() describe 'belongsTo', -> beforeEach -> record = App.AssociationCursorTest.build() cursor = record.getAssociationCursor('associationCursorUser') association = record.constructor.relations()['associationCursorUser'] afterEach -> #association.autosave = undefined test 'getAssociation', -> assert.isTrue record.getAssociationScope('associationCursorUser') instanceof Tower.ModelScope, "record.getAssociationScope('associationCursorUser') instanceof Tower.ModelScope" assert.isTrue record.getAssociationScope('associationCursorUser').cursor.isBelongsTo, 'cursor.isBelongsTo' assert.isTrue record.getAssociationCursor('associationCursorUser').isBelongsTo, 'getAssociationCursor("associationCursorUser").isBelongsTo' test 'setBelongsToAssociation', -> assert.equal cursor.get('content').length, 0 # pass single item record._setBelongsToAssociation('associationCursorUser', App.AssociationCursorUser.build(), association) assert.equal cursor.get('content').length, 1 test '_validateSingleAssociation', -> record._setBelongsToAssociation('associationCursorUser', App.AssociationCursorUser.build(), association) assert.isFalse record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' assert.deepEqual record.get('errors'), {associationCursorUser: ['Invalid']} record.set('errors', {}) # don't know how to clear the errors in this case yet record._setBelongsToAssociation('associationCursorUser', App.AssociationCursorUser.build(username: 'fred'), association) assert.isTrue record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' test 'set', -> record.set('associationCursorUser', App.AssociationCursorUser.build(username: 'fred')) assert.isTrue record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' test '_saveBelongsToAssociation', (done) -> record.set('associationCursorUser', App.AssociationCursorUser.build(username: 'fred')) record._saveBelongsToAssociation association, => assert.ok record.get('associationCursorUser').get('id') done() test 'save', (done) -> record.set('associationCursorUser', App.AssociationCursorUser.build(username: 'john')) record.save => assert.ok record.get('id') assert.equal record.get('associationCursorUser').get('id').toString(), record.get('associationCursorUserId').toString() done() test 'replace', (done) -> record.updateAttributes associationCursorUser: App.AssociationCursorUser.build(username: 'john'), => firstId = record.get('associationCursorUserId') assert.ok firstId record.updateAttributes associationCursorUser: App.AssociationCursorUser.build(username: 'john'), => secondId = record.get('associationCursorUserId') assert.ok secondId assert.notEqual firstId.toString(), secondId.toString() done() test 'nullify', (done) -> record.updateAttributes associationCursorUser: App.AssociationCursorUser.build(username: 'john'), => record.updateAttributes associationCursorUser: null, => assert.isUndefined record.get('associationCursorUserId') done() describe 'hasOne', -> beforeEach -> record = App.AssociationCursorTest.build() key = 'associationPI:KEY:<KEY>END_PI' cursor = record.getAssociationCursor(key) association = record.constructor.relations()[key] test 'getAssociation', -> assert.isTrue record.getAssociationScope(key) instanceof Tower.ModelScope, "record.getAssociationScope(key) instanceof Tower.ModelScope" assert.isTrue record.getAssociationScope(key).cursor.isHasOne, 'cursor.isHasOne' assert.isTrue record.getAssociationCursor(key).isHasOne, 'getAssociationCursor("associationCursorUser").isHasOne' test 'setHasOneAssociation', -> assert.equal cursor.get('content').length, 0 # pass single item record._setHasOneAssociation(key, App.AssociationCursorAddress.build(), association) assert.equal cursor.get('content').length, 1 test '_validateSingleAssociation', -> record._setHasOneAssociation(key, App.AssociationCursorAddress.build(), association) assert.isFalse record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' assert.deepEqual record.get('errors'), {associationCursorAddress: ['Invalid']} record.set('errors', {}) # don't know how to clear the errors in this case yet record._setHasOneAssociation(key, App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA'), association) assert.isTrue record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' test 'set', -> record.set(key, App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA')) assert.isTrue record._validateSingleAssociation(association), 'record._validateSingleAssociation(association)' test '_saveHasOneAssociation', (done) -> record.save => child = App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA') record.set(key, child) record._saveHasOneAssociation association, => assert.equal child.get('associationCursorTestId').toString(), record.get('id').toString() done() test 'save', (done) -> child = App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA') record.set(key, child) record.save => assert.ok record.get('id') assert.equal child.get('associationCursorTestId').toString(), record.get('id').toString() done() test 'setting multiple times when parent is persistent', (done) -> record.save => App.AssociationCursorAddress.create city: 'San Francisco', state: 'CA', (error, child1) => child2 = App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA') record.set(key, child1) record.set(key, child2) assert.isUndefined record.getAssociationCursor(key)._markedForDestruction done() test 'setting multiple times when parent is persistent and relationship already existed', (done) -> child1 = App.AssociationCursorAddress.build city: 'San Francisco', state: 'CA' record.updateAttributes associationCursorAddress: child1, => child2 = App.AssociationCursorAddress.build(city: 'San Francisco', state: 'CA') record.set(key, child1) record.set(key, child2) assert.equal record.getAssociationCursor(key)._markedForDestruction, child1 done()
[ { "context": "(data, success, failure) ->\n success?(userid: 'alice')\n $promise:\n finally: sandbox.stub()\n r", "end": 148, "score": 0.9949009418487549, "start": 143, "tag": "USERNAME", "value": "alice" }, { "context": "\n data:\n errors:\n username...
src/sidebar/components/test/login-form-test.coffee
legendary614/annotator
2
{inject, module} = angular.mock sandbox = sinon.sandbox.create() class MockSession login: (data, success, failure) -> success?(userid: 'alice') $promise: finally: sandbox.stub() register: (data, callback, errback) -> errback data: errors: username: 'taken' reason: 'registration error' $promise: finally: sandbox.stub() mockFlash = info: sandbox.spy() mockFormRespond = sandbox.spy() mockAnalytics = { track: sandbox.stub(), events: require('../../analytics')().events, } describe 'loginForm.Controller', -> $scope = null $timeout = null auth = null session = null $controller = null before -> angular.module('h', []) .controller('loginFormController', require('../login-form').controller) beforeEach module('h') beforeEach module ($provide) -> $provide.value '$timeout', sandbox.spy() $provide.value 'analytics', mockAnalytics $provide.value 'flash', mockFlash $provide.value 'session', new MockSession() $provide.value 'formRespond', mockFormRespond $provide.value 'serviceUrl', sandbox.spy() return beforeEach inject (_$controller_, $rootScope, _$timeout_, _session_) -> $scope = $rootScope.$new() $timeout = _$timeout_ $controller = _$controller_ auth = $controller 'loginFormController', {$scope} session = _session_ sandbox.spy session, 'login' afterEach -> sandbox.restore() mockAnalytics.track.reset() describe '#submit()', -> it 'should call session methods on submit', -> auth.submit $name: 'login' $valid: true $setValidity: sandbox.stub() assert.called session.login it 'should do nothing when the form is invalid', -> auth.submit $name: 'login' $valid: false $setValidity: sandbox.stub() assert.notCalled session.login it 'should apply validation errors on submit', -> form = $name: 'register' $valid: true $setValidity: sandbox.stub() username: $setValidity: sandbox.stub() email: $setValidity: sandbox.stub() auth.submit(form) assert.calledWith mockFormRespond, form, {username: 'taken'}, 'registration error' it 'should apply reason-only validation errors from the server', -> # Make a mock session that returns an error response with a "reason" but # no "errors" in the JSON object. reason = 'Argh, crashed! :|' myMockSession = new MockSession() myMockSession.register = (data, callback, errback) -> errback({data: {reason: reason}}) $promise: {finally: sandbox.stub()} # Get an AuthController object with our mock session. authCtrl = $controller( 'loginFormController', {$scope:$scope, session:myMockSession}) form = {$name: 'register', $valid: true} authCtrl.submit(form) assert.calledWith(mockFormRespond, form, undefined, reason) it 'should handle invalid error responses from the server', -> # A mock session that returns an error that isn't a valid JSON object # in the form that the frontend expects. This happens if there's an # uncaught exception on the server. myMockSession = new MockSession() myMockSession.register = (data, callback, errback) -> errback('Oh no!!') $promise: {finally: sandbox.stub()} authCtrl = $controller( 'loginFormController', {$scope:$scope, session:myMockSession}) form = {$name: 'register', $valid: true} authCtrl.submit(form) assert.calledWith(mockFormRespond, form, undefined, "Oops, something went wrong on the server. Please try again later!") it 'should emit an auth event once authenticated', -> form = $name: 'login' $valid: true $setValidity: sandbox.stub() sandbox.spy $scope, '$emit' auth.submit(form) assert.calledWith $scope.$emit, 'auth', null, userid: 'alice' it 'should emit an auth event if destroyed before authentication', -> sandbox.spy $scope, '$emit' $scope.$destroy() assert.calledWith $scope.$emit, 'auth', 'cancel' describe 'auth analytics', -> it 'should not track login errors for local validation errors', -> auth.submit $name: 'login' $valid: false $setValidity: sandbox.stub() assert.notCalled mockAnalytics.track it 'should track login error when server sends a reason', -> # Make a mock session that returns an error response with a "reason" but # no "errors" in the JSON object. reason = 'Argh, crashed! :|' myMockSession = new MockSession() myMockSession.register = (data, callback, errback) -> errback({data: {reason: reason}}) $promise: {finally: sandbox.stub()} # Get an AuthController object with our mock session. authCtrl = $controller( 'loginFormController', {$scope:$scope, session:myMockSession}) form = {$name: 'register', $valid: true} authCtrl.submit(form) assert.calledOnce(mockAnalytics.track) assert.calledWith(mockAnalytics.track, mockAnalytics.events.LOGIN_FAILURE) it 'should emit an auth event once authenticated', -> form = $name: 'login' $valid: true $setValidity: sandbox.stub() sandbox.spy $scope, '$emit' auth.submit(form) assert.calledOnce(mockAnalytics.track) assert.calledWith(mockAnalytics.track, mockAnalytics.events.LOGIN_SUCCESS) describe 'timeout', -> it 'should happen after a period of inactivity', -> sandbox.spy $scope, '$broadcast' $scope.form = $setPristine: sandbox.stub() $scope.model = username: 'test' email: 'test@example.com' password: 'secret' code: '1234' $scope.$digest() assert.called $timeout $timeout.lastCall.args[0]() assert.called $scope.form.$setPristine assert.deepEqual $scope.model, {}, 'the model is erased' assert.called mockFlash.info it 'should not happen if the model is empty', -> $scope.model = undefined $scope.$digest() assert.notCalled $timeout $scope.model = {} $scope.$digest() assert.notCalled $timeout
40183
{inject, module} = angular.mock sandbox = sinon.sandbox.create() class MockSession login: (data, success, failure) -> success?(userid: 'alice') $promise: finally: sandbox.stub() register: (data, callback, errback) -> errback data: errors: username: 'taken' reason: 'registration error' $promise: finally: sandbox.stub() mockFlash = info: sandbox.spy() mockFormRespond = sandbox.spy() mockAnalytics = { track: sandbox.stub(), events: require('../../analytics')().events, } describe 'loginForm.Controller', -> $scope = null $timeout = null auth = null session = null $controller = null before -> angular.module('h', []) .controller('loginFormController', require('../login-form').controller) beforeEach module('h') beforeEach module ($provide) -> $provide.value '$timeout', sandbox.spy() $provide.value 'analytics', mockAnalytics $provide.value 'flash', mockFlash $provide.value 'session', new MockSession() $provide.value 'formRespond', mockFormRespond $provide.value 'serviceUrl', sandbox.spy() return beforeEach inject (_$controller_, $rootScope, _$timeout_, _session_) -> $scope = $rootScope.$new() $timeout = _$timeout_ $controller = _$controller_ auth = $controller 'loginFormController', {$scope} session = _session_ sandbox.spy session, 'login' afterEach -> sandbox.restore() mockAnalytics.track.reset() describe '#submit()', -> it 'should call session methods on submit', -> auth.submit $name: 'login' $valid: true $setValidity: sandbox.stub() assert.called session.login it 'should do nothing when the form is invalid', -> auth.submit $name: 'login' $valid: false $setValidity: sandbox.stub() assert.notCalled session.login it 'should apply validation errors on submit', -> form = $name: 'register' $valid: true $setValidity: sandbox.stub() username: $setValidity: sandbox.stub() email: $setValidity: sandbox.stub() auth.submit(form) assert.calledWith mockFormRespond, form, {username: 'taken'}, 'registration error' it 'should apply reason-only validation errors from the server', -> # Make a mock session that returns an error response with a "reason" but # no "errors" in the JSON object. reason = 'Argh, crashed! :|' myMockSession = new MockSession() myMockSession.register = (data, callback, errback) -> errback({data: {reason: reason}}) $promise: {finally: sandbox.stub()} # Get an AuthController object with our mock session. authCtrl = $controller( 'loginFormController', {$scope:$scope, session:myMockSession}) form = {$name: 'register', $valid: true} authCtrl.submit(form) assert.calledWith(mockFormRespond, form, undefined, reason) it 'should handle invalid error responses from the server', -> # A mock session that returns an error that isn't a valid JSON object # in the form that the frontend expects. This happens if there's an # uncaught exception on the server. myMockSession = new MockSession() myMockSession.register = (data, callback, errback) -> errback('Oh no!!') $promise: {finally: sandbox.stub()} authCtrl = $controller( 'loginFormController', {$scope:$scope, session:myMockSession}) form = {$name: 'register', $valid: true} authCtrl.submit(form) assert.calledWith(mockFormRespond, form, undefined, "Oops, something went wrong on the server. Please try again later!") it 'should emit an auth event once authenticated', -> form = $name: 'login' $valid: true $setValidity: sandbox.stub() sandbox.spy $scope, '$emit' auth.submit(form) assert.calledWith $scope.$emit, 'auth', null, userid: 'alice' it 'should emit an auth event if destroyed before authentication', -> sandbox.spy $scope, '$emit' $scope.$destroy() assert.calledWith $scope.$emit, 'auth', 'cancel' describe 'auth analytics', -> it 'should not track login errors for local validation errors', -> auth.submit $name: 'login' $valid: false $setValidity: sandbox.stub() assert.notCalled mockAnalytics.track it 'should track login error when server sends a reason', -> # Make a mock session that returns an error response with a "reason" but # no "errors" in the JSON object. reason = 'Argh, crashed! :|' myMockSession = new MockSession() myMockSession.register = (data, callback, errback) -> errback({data: {reason: reason}}) $promise: {finally: sandbox.stub()} # Get an AuthController object with our mock session. authCtrl = $controller( 'loginFormController', {$scope:$scope, session:myMockSession}) form = {$name: 'register', $valid: true} authCtrl.submit(form) assert.calledOnce(mockAnalytics.track) assert.calledWith(mockAnalytics.track, mockAnalytics.events.LOGIN_FAILURE) it 'should emit an auth event once authenticated', -> form = $name: 'login' $valid: true $setValidity: sandbox.stub() sandbox.spy $scope, '$emit' auth.submit(form) assert.calledOnce(mockAnalytics.track) assert.calledWith(mockAnalytics.track, mockAnalytics.events.LOGIN_SUCCESS) describe 'timeout', -> it 'should happen after a period of inactivity', -> sandbox.spy $scope, '$broadcast' $scope.form = $setPristine: sandbox.stub() $scope.model = username: 'test' email: '<EMAIL>' password: '<PASSWORD>' code: '1234' $scope.$digest() assert.called $timeout $timeout.lastCall.args[0]() assert.called $scope.form.$setPristine assert.deepEqual $scope.model, {}, 'the model is erased' assert.called mockFlash.info it 'should not happen if the model is empty', -> $scope.model = undefined $scope.$digest() assert.notCalled $timeout $scope.model = {} $scope.$digest() assert.notCalled $timeout
true
{inject, module} = angular.mock sandbox = sinon.sandbox.create() class MockSession login: (data, success, failure) -> success?(userid: 'alice') $promise: finally: sandbox.stub() register: (data, callback, errback) -> errback data: errors: username: 'taken' reason: 'registration error' $promise: finally: sandbox.stub() mockFlash = info: sandbox.spy() mockFormRespond = sandbox.spy() mockAnalytics = { track: sandbox.stub(), events: require('../../analytics')().events, } describe 'loginForm.Controller', -> $scope = null $timeout = null auth = null session = null $controller = null before -> angular.module('h', []) .controller('loginFormController', require('../login-form').controller) beforeEach module('h') beforeEach module ($provide) -> $provide.value '$timeout', sandbox.spy() $provide.value 'analytics', mockAnalytics $provide.value 'flash', mockFlash $provide.value 'session', new MockSession() $provide.value 'formRespond', mockFormRespond $provide.value 'serviceUrl', sandbox.spy() return beforeEach inject (_$controller_, $rootScope, _$timeout_, _session_) -> $scope = $rootScope.$new() $timeout = _$timeout_ $controller = _$controller_ auth = $controller 'loginFormController', {$scope} session = _session_ sandbox.spy session, 'login' afterEach -> sandbox.restore() mockAnalytics.track.reset() describe '#submit()', -> it 'should call session methods on submit', -> auth.submit $name: 'login' $valid: true $setValidity: sandbox.stub() assert.called session.login it 'should do nothing when the form is invalid', -> auth.submit $name: 'login' $valid: false $setValidity: sandbox.stub() assert.notCalled session.login it 'should apply validation errors on submit', -> form = $name: 'register' $valid: true $setValidity: sandbox.stub() username: $setValidity: sandbox.stub() email: $setValidity: sandbox.stub() auth.submit(form) assert.calledWith mockFormRespond, form, {username: 'taken'}, 'registration error' it 'should apply reason-only validation errors from the server', -> # Make a mock session that returns an error response with a "reason" but # no "errors" in the JSON object. reason = 'Argh, crashed! :|' myMockSession = new MockSession() myMockSession.register = (data, callback, errback) -> errback({data: {reason: reason}}) $promise: {finally: sandbox.stub()} # Get an AuthController object with our mock session. authCtrl = $controller( 'loginFormController', {$scope:$scope, session:myMockSession}) form = {$name: 'register', $valid: true} authCtrl.submit(form) assert.calledWith(mockFormRespond, form, undefined, reason) it 'should handle invalid error responses from the server', -> # A mock session that returns an error that isn't a valid JSON object # in the form that the frontend expects. This happens if there's an # uncaught exception on the server. myMockSession = new MockSession() myMockSession.register = (data, callback, errback) -> errback('Oh no!!') $promise: {finally: sandbox.stub()} authCtrl = $controller( 'loginFormController', {$scope:$scope, session:myMockSession}) form = {$name: 'register', $valid: true} authCtrl.submit(form) assert.calledWith(mockFormRespond, form, undefined, "Oops, something went wrong on the server. Please try again later!") it 'should emit an auth event once authenticated', -> form = $name: 'login' $valid: true $setValidity: sandbox.stub() sandbox.spy $scope, '$emit' auth.submit(form) assert.calledWith $scope.$emit, 'auth', null, userid: 'alice' it 'should emit an auth event if destroyed before authentication', -> sandbox.spy $scope, '$emit' $scope.$destroy() assert.calledWith $scope.$emit, 'auth', 'cancel' describe 'auth analytics', -> it 'should not track login errors for local validation errors', -> auth.submit $name: 'login' $valid: false $setValidity: sandbox.stub() assert.notCalled mockAnalytics.track it 'should track login error when server sends a reason', -> # Make a mock session that returns an error response with a "reason" but # no "errors" in the JSON object. reason = 'Argh, crashed! :|' myMockSession = new MockSession() myMockSession.register = (data, callback, errback) -> errback({data: {reason: reason}}) $promise: {finally: sandbox.stub()} # Get an AuthController object with our mock session. authCtrl = $controller( 'loginFormController', {$scope:$scope, session:myMockSession}) form = {$name: 'register', $valid: true} authCtrl.submit(form) assert.calledOnce(mockAnalytics.track) assert.calledWith(mockAnalytics.track, mockAnalytics.events.LOGIN_FAILURE) it 'should emit an auth event once authenticated', -> form = $name: 'login' $valid: true $setValidity: sandbox.stub() sandbox.spy $scope, '$emit' auth.submit(form) assert.calledOnce(mockAnalytics.track) assert.calledWith(mockAnalytics.track, mockAnalytics.events.LOGIN_SUCCESS) describe 'timeout', -> it 'should happen after a period of inactivity', -> sandbox.spy $scope, '$broadcast' $scope.form = $setPristine: sandbox.stub() $scope.model = username: 'test' email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' code: '1234' $scope.$digest() assert.called $timeout $timeout.lastCall.args[0]() assert.called $scope.form.$setPristine assert.deepEqual $scope.model, {}, 'the model is erased' assert.called mockFlash.info it 'should not happen if the model is empty', -> $scope.model = undefined $scope.$digest() assert.notCalled $timeout $scope.model = {} $scope.$digest() assert.notCalled $timeout
[ { "context": " [iOrder](http://neocotic.com/iOrder) \n# (c) 2013 Alasdair Mercer \n# Freely distributable under the MIT license. ", "end": 67, "score": 0.9998700022697449, "start": 52, "tag": "NAME", "value": "Alasdair Mercer" }, { "context": " used to validate order keys.\nR_VALI...
chrome/src/lib/options.coffee
neocotic/iOrder
0
# [iOrder](http://neocotic.com/iOrder) # (c) 2013 Alasdair Mercer # Freely distributable under the MIT license. # For all details and documentation: # <http://neocotic.com/iOrder> # Private constants # ----------------- # Regular expression used to sanitize search queries. R_CLEAN_QUERY = /[^\w\s]/g # Regular expression used to validate order keys. R_VALID_KEY = /^[A-Z0-9]*\.[A-Z0-9]*$/i # Regular expression used to identify whitespace. R_WHITESPACE = /\s+/ # Private variables # ----------------- # Copy of order being actively modified. activeOrder = null # Easily accessible reference to the extension controller. {ext} = chrome.extension.getBackgroundPage() # Indicate whether or not the user feedback feature has been added to the page. feedbackAdded = no # Orders matching the current search query. searchResults = null # Load functions # -------------- # Bind an event of the specified `type` to the elements included by `selector` that, when # triggered, modifies the underlying `option` with the value returned by `evaluate`. bindSaveEvent = (selector, type, option, evaluate, callback) -> log.trace() $(selector).on type, -> $this = $ this key = '' value = null store.modify option, (data) -> key = $this.attr('id').match(new RegExp("^#{option}(\\S*)"))[1] key = key[0].toLowerCase() + key.substr 1 data[key] = value = evaluate.call $this, key callback? $this, key, value # Update the options page with the values from the current settings. load = -> log.trace() $('#analytics').prop 'checked', store.get 'analytics' do loadSaveEvents do loadFrequencies do loadOrders do loadNotifications do loadDeveloperTools # Update the developer tools section of the options page with the current settings. loadDeveloperTools = -> log.trace() do loadLogger # Update the frequency section of the options page with the current settings. loadFrequencies = -> log.trace() frequency = store.get 'frequency' $frequency = $ '#frequency' # Start from a clean slate. $frequency.remove 'option' # Create and insert options representing each available update frequency. for freq in ext.config.frequencies option = $ '<option/>', text: freq.text value: freq.value option.prop 'selected', freq.value is frequency $frequency.append option do loadFrequenciesSaveEvents # Bind the event handlers required for persisting frequency changes. loadFrequenciesSaveEvents = -> log.trace() $('#frequency').on 'change', -> value = $(this).val() log.debug "Changing frequency to '#{value}'" store.set 'frequency', parseInt frequency, 10 ext.updateOrders() analytics.track 'General', 'Changed', 'Frequency', value # Update the logging section of the options page with the current settings. loadLogger = -> log.trace() logger = store.get 'logger' $('#loggerEnabled').prop 'checked', logger.enabled loggerLevel = $ '#loggerLevel' loggerLevel.find('option').remove() for level in log.LEVELS option = $ '<option/>', text: i18n.get "opt_logger_level_#{level.name}_text" value: level.value option.prop 'selected', level.value is logger.level loggerLevel.append option # Ensure debug level is selected if configuration currently matches none. unless loggerLevel.find('option[selected]').length loggerLevel.find("option[value='#{log.DEBUG}']").prop 'selected', yes do loadLoggerSaveEvents # Bind the event handlers required for persisting logging changes. loadLoggerSaveEvents = -> log.trace() bindSaveEvent '#loggerEnabled, #loggerLevel', 'change', 'logger', (key) -> value = if key is 'level' then @val() else @is ':checked' log.debug "Changing logging #{key} to '#{value}'" value , (jel, key, value) -> logger = store.get 'logger' chrome.extension.getBackgroundPage().log.config = log.config = logger analytics.track 'Logging', 'Changed', key[0].toUpperCase() + key.substr(1), Number value # Update the notification section of the options page with the current settings. loadNotifications = -> log.trace() {badges, duration, enabled} = store.get 'notifications' $('#notificationsBadges').prop 'checked', badges $('#notificationsDuration').val if duration > 0 then duration * .001 else 0 $('#notificationsEnabled').prop 'checked', enabled do loadNotificationSaveEvents # Bind the event handlers required for persisting notification changes. loadNotificationSaveEvents = -> log.trace() bindSaveEvent '#notificationsBadges, #notificationsDuration, #notificationsEnabled', 'change', 'notifications', (key) -> value = if key is 'duration' milliseconds = @val() if milliseconds then parseInt(milliseconds, 10) * 1000 else 0 else @is ':checked' log.debug "Changing notifications #{key} to '#{value}'" value , (jel, key, value) -> analytics.track 'Notifications', 'Changed', key[0].toUpperCase() + key.substr(1), Number value # Create a `tr` element representing the `order` provided. # The element returned should then be inserted in to the table that is displaying the orders. loadOrder = (order) -> log.trace() log.debug 'Creating a row for the following order...', order row = $ '<tr/>', draggable: yes alignCenter = css: 'text-align': 'center' row.append $('<td/>', alignCenter).append $ '<input/>', title: i18n.get 'opt_select_box' type: 'checkbox' value: order.key row.append $('<td/>').append $ '<span/>', text: order.label title: i18n.get 'opt_order_modify_title', order.label row.append $('<td/>').append $('<span/>').append $ '<a/>', href: ext.getOrderUrl order target: '_blank' text: order.number title: i18n.get 'opt_order_title' row.append $('<td/>').append $ '<span/>', text: order.email row.append $('<td/>').append $ '<span/>', text: order.code row.append $('<td/>').append $ '<span/>', text: ext.getStatusText order row.append $('<td/>').append if order.trackingUrl $ '<a/>', href: order.trackingUrl target: '_blank' text: i18n.get 'opt_track_text' title: i18n.get 'opt_track_title' else '&nbsp;' row.append $('<td/>').append $ '<span/>', class: 'muted' text: '::::' title: i18n.get 'opt_order_move_title', order.label row # Bind the event handlers required for controlling the orders. loadOrderControlEvents = -> log.trace() # Ensure order wizard is closed if/when tabify links are clicked within it or it is cancelled. $('#order_wizard [tabify], #order_cancel_btn').on 'click', -> do closeWizard $('#order_reset_btn').on 'click', -> do resetWizard # Support search functionality for orders. filter = $ '#order_filter' filter.find('option').remove() for limit in ext.config.options.limits filter.append $ '<option/>', text: limit filter.append $ '<option/>', disabled: 'disabled' text: '-----' filter.append $ '<option/>', text: i18n.get 'opt_show_all_text' value: 0 store.init 'options_limit', parseInt $('#order_filter').val(), 10 limit = store.get 'options_limit' $('#order_filter option').each -> $this = $ this $this.prop 'selected', limit is parseInt $this.val(), 10 $('#order_filter').on 'change', -> store.set 'options_limit', parseInt $(this).val(), 10 loadOrderRows searchResults ? ext.orders $('#order_search :reset').on 'click', -> $('#order_search :text').val '' do searchOrders $('#order_controls').on 'submit', -> searchOrders $('#order_search :text').val() # Ensure user confirms deletion of order. $('#order_delete_btn').on 'click', -> $(this).hide() $('#order_confirm_delete').css 'display', 'inline-block' $('#order_undo_delete_btn').on 'click', -> $('#order_confirm_delete').hide() $('#order_delete_btn').show() $('#order_confirm_delete_btn').on 'click', -> $('#order_confirm_delete').hide() $('#order_delete_btn').show() deleteOrders [activeOrder] do closeWizard validationErrors = [] $('#order_wizard').on 'hide', -> error.hide() for error in validationErrors $('#order_save_btn').on 'click', -> order = deriveOrder() # Clear all existing validation errors. error.hide() for error in validationErrors validationErrors = validateOrder order if validationErrors.length error.show() for error in validationErrors else validationErrors = [] $.extend activeOrder, order saveOrder activeOrder $('#order_search :reset').hide() $('#order_search :text').val '' do closeWizard # Open the order wizard without any context. $('#add_btn').on 'click', -> openWizard null selectedOrders = [] $('#delete_wizard').on 'hide', -> selectedOrders = [] $('#delete_items li').remove() # Prompt the user to confirm removal of the selected order(s). $('#delete_btn').on 'click', -> deleteItems = $ '#delete_items' selectedOrders = getSelectedOrders() deleteItems.find('li').remove() # Create list items for each order and allocate them accordingly. for order in selectedOrders deleteItems.append $ '<li/>', text: "#{order.label} (#{order.number})" # Begin the order removal process by showing the dialog. $('#delete_wizard').modal 'show' # Cancel the order removal process. $('#delete_cancel_btn, #delete_no_btn').on 'click', -> $('#delete_wizard').modal 'hide' # Finalize the order removal process. $('#delete_yes_btn').on 'click', -> deleteOrders selectedOrders $('#delete_wizard').modal 'hide' # Load the `orders` into the table to be displayed to the user. # Optionally, pagination can be disabled but this should only really be used internally by the # pagination process. loadOrderRows = (orders = ext.orders, pagination = yes) -> log.trace() table = $ '#orders' # Start from a clean slate. table.find('tbody tr').remove() if orders.length # Create and insert rows representing each order. table.append loadOrder order for order in orders paginate orders if pagination activateTooltips table do activateDraggables do activateModifications do activateSelections else # Show single row to indicate no orders were found. table.find('tbody').append $('<tr/>').append $ '<td/>', colspan: table.find('thead th').length html: i18n.get 'opt_no_orders_found_text' # Update the orders section of the options page with the current settings. loadOrders = -> log.trace() # Load all of the event handlers required for managing the orders. do loadOrderControlEvents # Load the order data into the table. do loadOrderRows # Bind the event handlers required for persisting general changes. loadSaveEvents = -> log.trace() $('#analytics').on 'change', -> enabled = $(this).is ':checked' log.debug "Changing analytics to '#{enabled}'" if enabled store.set 'analytics', yes chrome.extension.getBackgroundPage().analytics.add() analytics.add() analytics.track 'General', 'Changed', 'Analytics', 1 else analytics.track 'General', 'Changed', 'Analytics', 0 analytics.remove() chrome.extension.getBackgroundPage().analytics.remove() store.set 'analytics', no # Save functions # -------------- # Delete all of the `orders` provided. deleteOrders = (orders) -> log.trace() keys = (order.key for order in orders) if keys.length keep = [] for order, i in ext.orders when order.key not in keys orders.index = i keep.push order store.set 'orders', keep ext.updateOrders() if keys.length > 1 log.debug "Deleted #{keys.length} orders" analytics.track 'Orders', 'Deleted', "Count[#{keys.length}]" else order = orders[0] log.debug "Deleted #{order.label} order" analytics.track 'Orders', 'Deleted', order.label loadOrderRows searchResults ? ext.orders # Reorder the orders after a drag and drop *swap* by updating their indices and sorting them # accordingly. # These changes are then persisted and should be reflected throughout the extension. reorderOrders = (fromIndex, toIndex) -> log.trace() orders = ext.orders if fromIndex? and toIndex? orders[fromIndex].index = toIndex orders[toIndex].index = fromIndex store.set 'orders', orders ext.updateOrders() # Update and persist the `order` provided. # Any required validation should be performed perior to calling this method. saveOrder = (order) -> log.trace() log.debug 'Saving the following order...', order isNew = not order.key? orders = store.get 'orders' if isNew order.key = utils.keyGen() orders.push order else for temp, i in orders when temp.key is order.key orders[i] = order break store.set 'orders', orders ext.updateOrders() do loadOrderRows action = if isNew then 'Added' else 'Saved' analytics.track 'Orders', action, order.label order # Validation classes # ------------------ # `ValidationError` allows easy management and display of validation error messages that are # associated with specific fields. class ValidationError extends utils.Class # Create a new instance of `ValidationError`. constructor: (@id, @key) -> @className = 'error' # Hide any validation messages currently displayed for the associated field. hide: -> field = $ "##{@id}" field.parents('.control-group:first').removeClass @className field.parents('.controls:first').find('.help-block').remove() # Display the validation message for the associated field. show: -> field = $ "##{@id}" field.parents('.control-group:first').addClass @className field.parents('.controls:first').append $ '<span/>', class: 'help-block' html: i18n.get @key # `ValidationWarning` allows easy management and display of validation warning messages that are # associated with specific fields. class ValidationWarning extends ValidationError # Create a new instance of `ValidationWarning`. constructor: (@id, @key) -> @className = 'warning' # Validation functions # -------------------- # Indicate whether or not the specified `key` is valid. isKeyValid = (key) -> log.trace() log.debug "Validating order key '#{key}'" R_VALID_KEY.test key # Determine whether an order number already exists. isNumberAvailable = (order) -> log.trace() {key, number} = order not ext.queryOrder (order) -> order.number is number and order.key isnt key # Validate the `order` and return any validation errors/warnings that were encountered. validateOrder = (order) -> log.trace() isNew = not order.key? errors = [] log.debug 'Validating the following order...', order # Label is missing but is required. unless order.label errors.push new ValidationError 'order_label', 'opt_field_required_error' # Number is missing but is required. unless order.number errors.push new ValidationError 'order_number', 'opt_field_required_error' # Number already exists. unless isNumberAvailable order errors.push new ValidationError 'order_number', 'opt_field_unavailable_error' # Post/zip code and email are missing but at least one is required. unless order.code or order.email errors.push new ValidationError 'order_code', 'opt_field_required_error' errors.push new ValidationError 'order_email', 'opt_field_required_error' # Indicate whether or not any validation errors were encountered. log.debug 'Following validation errors were found...', errors errors # Miscellaneous classes # --------------------- # `Message` allows simple management and display of alert messages. class Message extends utils.Class # Create a new instance of `Message`. constructor: (@block) -> @className = 'alert-info' @headerKey = 'opt_message_header' # Hide this `Message` if it has previously been displayed. hide: -> @alert?.alert 'close' # Display this `Message` at the top of the current tab. show: -> @header = i18n.get @headerKey if @headerKey and not @header? @message = i18n.get @messageKey if @messageKey and not @message? @alert = $ '<div/>', class: "alert #{@className}" @alert.addClass 'alert-block' if @block @alert.append $ '<button/>', class: 'close' 'data-dismiss': 'alert' html: '&times;' type: 'button' @alert.append $ "<#{if @block then 'h4' else 'strong'}/>", html: @header if @header @alert.append if @block then @message else " #{@message}" if @message @alert.prependTo $ $('#navigation li.active a').attr 'tabify' # `ErrorMessage` allows simple management and display of error messages. class ErrorMessage extends Message # Create a new instance of `ErrorMessage`. constructor: (@block) -> @className = 'alert-error' @headerKey = 'opt_message_error_header' # `SuccessMessage` allows simple management and display of success messages. class SuccessMessage extends Message # Create a new instance of `SuccessMessage`. constructor: (@block) -> @className = 'alert-success' @headerKey = 'opt_message_success_header' # `WarningMessage` allows simple management and display of warning messages. class WarningMessage extends Message # Create a new instance of `WarningMessage`. constructor: (@block) -> @className = '' @headerKey = 'opt_message_warning_header' # Miscellaneous functions # ----------------------- # Activate drag and drop functionality for reordering orders. # The activation is done cleanly, unbinding any associated events that have been previously bound. activateDraggables = -> log.trace() table = $ '#orders' dragSource = null draggables = table.find '[draggable]' draggables.off 'dragstart dragend dragenter dragover drop' draggables.on 'dragstart', (e) -> $this = $ this dragSource = this table.removeClass 'table-hover' $this.addClass 'dnd-moving' $this.find('[data-original-title]').tooltip 'hide' e.originalEvent.dataTransfer.effectAllowed = 'move' e.originalEvent.dataTransfer.setData 'text/html', $this.html() draggables.on 'dragend', (e) -> draggables.removeClass 'dnd-moving dnd-over' table.addClass 'table-hover' dragSource = null draggables.on 'dragenter', (e) -> $this = $ this draggables.not($this).removeClass 'dnd-over' $this.addClass 'dnd-over' draggables.on 'dragover', (e) -> e.preventDefault() e.originalEvent.dataTransfer.dropEffect = 'move' no draggables.on 'drop', (e) -> $dragSource = $ dragSource e.stopPropagation() if dragSource isnt this $this = $ this $dragSource.html $this.html() $this.html e.originalEvent.dataTransfer.getData 'text/html' activateTooltips table do activateModifications do activateSelections fromIndex = $dragSource.index() toIndex = $this.index() if searchResults? fromIndex = searchResults[fromIndex].index toIndex = searchResults[toIndex].index reorderOrders fromIndex, toIndex no # Activate functionality to open order wizard when a row is clicked. # The activation is done cleanly, unbinding any associated events that have been previously bound. activateModifications = -> log.trace() $('#orders tbody tr td:not(:first-child)').off('click').on 'click', -> activeKey = $(this).parents('tr:first').find(':checkbox').val() openWizard ext.queryOrder (order) -> order.key is activeKey # Activate select all/one functionality on the orders table. # The activation is done cleanly, unbinding any associated events that have been previously bound. activateSelections = -> log.trace() table = $ '#orders' selectBoxes = table.find 'tbody :checkbox' selectBoxes.off('change').on 'change', -> $this = $ this messageKey = 'opt_select_box' messageKey += '_checked' if $this.is ':checked' $this.attr 'data-original-title', i18n.get messageKey do refreshSelectButtons table.find('thead :checkbox').off('change').on 'change', -> $this = $ this checked = $this.is ':checked' messageKey = 'opt_select_all_box' messageKey += '_checked' if checked $this.attr 'data-original-title', i18n.get messageKey selectBoxes.prop 'checked', checked do refreshSelectButtons # Activate tooltip effects, optionally only within a specific context. # The activation is done cleanly, unbinding any associated events that have been previously bound. activateTooltips = (selector) -> log.trace() base = $ selector or document base.find('[data-original-title]').each -> $this = $ this $this.tooltip 'destroy' $this.attr 'title', $this.attr 'data-original-title' $this.removeAttr 'data-original-title' base.find('[title]').each -> $this = $ this placement = $this.attr 'data-placement' placement = if placement? then trimToLower placement else 'top' $this.tooltip container: $this.attr('data-container') ? 'body' placement: placement # Convenient shorthand for setting the current context to `null`. clearContext = -> do setContext # Clear the current context and close the order wizard. closeWizard = -> do clearContext $('#order_wizard').modal 'hide' # Create a order based on the current context and the information derived from the wizard fields. deriveOrder = -> log.trace() order = code: $('#order_code').val().trim() email: $('#order_email').val().trim() label: $('#order_label').val().trim() number: $('#order_number').val().trim() error: activeOrder.error ? '' index: activeOrder.index ? ext.orders.length key: activeOrder.key trackingUrl: activeOrder.trackingUrl ? '' updates: activeOrder.updates ? [] log.debug 'Following order was derived...', order order # Add the user feedback feature to the page. feedback = -> log.trace() unless feedbackAdded # Continue with normal process of loading Widget. uv = document.createElement 'script' uv.async = 'async' uv.src = "https://widget.uservoice.com/#{ext.config.options.userVoice.id}.js" script = document.getElementsByTagName('script')[0] script.parentNode.insertBefore uv, script # Configure the widget as it's loading. UserVoice = window.UserVoice or= [] UserVoice.push [ 'showTab' 'classic_widget' { mode: 'full' primary_color: '#333' link_color: '#08c' default_mode: 'feedback' forum_id: ext.config.options.userVoice.forum tab_label: i18n.get 'opt_feedback_button' tab_color: '#333' tab_position: 'middle-left' tab_inverted: yes } ] feedbackAdded = yes # Retrieve all currently selected orders. getSelectedOrders = -> selectedKeys = [] $('#orders tbody :checkbox:checked').each -> selectedKeys.push $(this).val() ext.queryOrders (order) -> order.key in selectedKeys # Open the order wizard after optionally setting the current context. openWizard = (order) -> setContext order if arguments.length $('#order_wizard').modal 'show' # Update the pagination UI for the specified `orders`. paginate = (orders) -> log.trace() limit = parseInt $('#order_filter').val(), 10 pagination = $ '#pagination' if orders.length > limit > 0 children = pagination.find 'ul li' pages = Math.ceil orders.length / limit # Refresh the pagination link states based on the new `page`. refreshPagination = (page = 1) -> # Select and display the desired orders subset. start = limit * (page - 1) end = start + limit loadOrderRows orders[start...end], no # Ensure the *previous* link is only enabled when a previous page exists. pagination.find('ul li:first-child').each -> $this = $ this if page is 1 then $this.addClass 'disabled' else $this.removeClass 'disabled' # Ensure only the active page is highlighted. pagination.find('ul li:not(:first-child, :last-child)').each -> $this = $ this if page is parseInt $this.text(), 10 then $this.addClass 'active' else $this.removeClass 'active' # Ensure the *next* link is only enabled when a next page exists. pagination.find('ul li:last-child').each -> $this = $ this if page is pages then $this.addClass 'disabled' else $this.removeClass 'disabled' # Create and insert pagination links. if pages isnt children.length - 2 children.remove() list = pagination.find 'ul' list.append $('<li/>').append $ '<a>&laquo;</a>' for page in [1..pages] list.append $('<li/>').append $ "<a>#{page}</a>" list.append $('<li/>').append $ '<a>&raquo;</a>' # Bind event handlers to manage navigating pages. pagination.find('ul li').off 'click' pagination.find('ul li:first-child').on 'click', -> unless $(this).hasClass 'disabled' refreshPagination pagination.find('ul li.active').index() - 1 pagination.find('ul li:not(:first-child, :last-child)').on 'click', -> $this = $ this refreshPagination $this.index() unless $this.hasClass 'active' pagination.find('ul li:last-child').on 'click', -> unless $(this).hasClass 'disabled' refreshPagination pagination.find('ul li.active').index() + 1 do refreshPagination pagination.show() else # Hide the pagination and remove all links as the results fit on a single page. pagination.hide().find('ul li').remove() # Update the state of the reset button depending on the current search input. refreshResetButton = -> log.trace() container = $ '#order_search' resetButton = container.find ':reset' if container.find(':text').val() container.addClass 'input-prepend' resetButton.show() else resetButton.hide() container.removeClass 'input-prepend' # Update the state of certain buttons depending on whether any select boxes have been checked. refreshSelectButtons = -> log.trace() selections = $ '#orders tbody :checkbox:checked' $('#delete_btn').prop 'disabled', selections.length is 0 # Reset the wizard field values based on the current context. resetWizard = -> log.trace() activeOrder ?= {} $('#order_wizard .modal-header h3').html if activeOrder.key? i18n.get 'opt_order_modify_title', activeOrder.label else i18n.get 'opt_order_new_header' # Assign values to their respective fields. $('#order_code').val activeOrder.code or '' $('#order_email').val activeOrder.email or '' $('#order_label').val activeOrder.label or '' $('#order_number').val activeOrder.number or '' $('#order_delete_btn').each -> $this = $ this if activeOrder.key? then $this.show() else $this.hide() # Search the orders for the specified `query` and filter those displayed. searchOrders = (query = '') -> log.trace() keywords = query.replace(R_CLEAN_QUERY, '').split R_WHITESPACE if keywords.length expression = /// #{(keyword for keyword in keywords when keyword).join '|'} ///i searchResults = ext.queryOrders (order) -> expression.test "#{order.code} #{order.email} #{order.label} #{order.number}" else searchResults = null loadOrderRows searchResults ? ext.orders do refreshResetButton do refreshSelectButtons # Set the current context of the order wizard. setContext = (order = {}) -> log.trace() activeOrder = {} $.extend activeOrder, order do resetWizard # Convenient shorthand for safely trimming a string to lower case. trimToLower = (str = '') -> str.trim().toLowerCase() # Convenient shorthand for safely trimming a string to upper case. trimToUpper = (str = '') -> str.trim().toUpperCase() # Options page setup # ------------------ options = window.options = new class Options extends utils.Class # Public functions # ---------------- # Initialize the options page. # This will involve inserting and configuring the UI elements as well as loading the current # settings. init: -> log.trace() log.info 'Initializing the options page' # Add support for analytics if the user hasn't opted out. analytics.add() if store.get 'analytics' # Add the user feedback feature to the page. do feedback # Begin initialization. i18n.init() $('.year-repl').html "#{new Date().getFullYear()}" # Bind tab selection event to all tabs. initialTabChange = yes $('a[tabify]').on 'click', -> target = $(this).attr 'tabify' nav = $ "#navigation a[tabify='#{target}']" parent = nav.parent 'li' unless parent.hasClass 'active' parent.siblings().removeClass 'active' parent.addClass 'active' $(target).show().siblings('.tab').hide() id = nav.attr 'id' store.set 'options_active_tab', id unless initialTabChange id = id.match(/(\S*)_nav$/)[1] id = id[0].toUpperCase() + id.substr 1 log.debug "Changing tab to #{id}" analytics.track 'Tabs', 'Changed', id initialTabChange = no $(document.body).scrollTop 0 # Reflect the persisted tab. store.init 'options_active_tab', 'general_nav' optionsActiveTab = store.get 'options_active_tab' $("##{optionsActiveTab}").trigger 'click' log.debug "Initially displaying tab for #{optionsActiveTab}" # Bind Developer Tools wizard events to their corresponding elements. $('#tools_nav').on 'click', -> $('#tools_wizard').modal 'show' $('.tools_close_btn').on 'click', -> $('#tools_wizard').modal 'hide' # Ensure that form submissions don't reload the page. $('form:not([target="_blank"])').on 'submit', -> no # Bind analytical tracking events to key footer buttons and links. $('footer a[href*="neocotic.com"]').on 'click', -> analytics.track 'Footer', 'Clicked', 'Homepage' # Setup and configure the donation button in the footer. $('#donation input[name="hosted_button_id"]').val ext.config.options.payPal $('#donation').on 'submit', -> analytics.track 'Footer', 'Clicked', 'Donate' # Load the current option values. do load # Initialize all popovers, tooltips and *go-to* links. $('[popover]').each -> $this = $ this placement = $this.attr 'data-placement' placement = if placement? then trimToLower placement else 'right' trigger = $this.attr 'data-trigger' trigger = if trigger? then trimToLower trigger else 'hover' $this.popover content: -> i18n.get $this.attr 'popover' html: yes placement: placement trigger: trigger if trigger is 'manual' $this.on 'click', -> $this.popover 'toggle' do activateTooltips navHeight = $('.navbar').height() $('[data-goto]').on 'click', -> goto = $ $(this).attr 'data-goto' pos = goto.position()?.top or 0 pos -= navHeight if pos and pos >= navHeight log.debug "Relocating view to include '#{goto.selector}' at #{pos}" $(window).scrollTop pos # Ensure that the persisted tab is currently visible. # This should be called if the user clicks the Options link in the popup while and options page # is already open. refresh: -> $("##{store.get 'options_active_tab'}").trigger 'click' # Initialize `options` when the DOM is ready. utils.ready -> options.init()
126229
# [iOrder](http://neocotic.com/iOrder) # (c) 2013 <NAME> # Freely distributable under the MIT license. # For all details and documentation: # <http://neocotic.com/iOrder> # Private constants # ----------------- # Regular expression used to sanitize search queries. R_CLEAN_QUERY = /[^\w\s]/g # Regular expression used to validate order keys. R_VALID_KEY = /^[A-<KEY>[<KEY>i # Regular expression used to identify whitespace. R_WHITESPACE = /\s+/ # Private variables # ----------------- # Copy of order being actively modified. activeOrder = null # Easily accessible reference to the extension controller. {ext} = chrome.extension.getBackgroundPage() # Indicate whether or not the user feedback feature has been added to the page. feedbackAdded = no # Orders matching the current search query. searchResults = null # Load functions # -------------- # Bind an event of the specified `type` to the elements included by `selector` that, when # triggered, modifies the underlying `option` with the value returned by `evaluate`. bindSaveEvent = (selector, type, option, evaluate, callback) -> log.trace() $(selector).on type, -> $this = $ this key = '' value = null store.modify option, (data) -> key = $this.attr('id').match(new RegExp("^#{option}(\\S*)"))[1] key = key[<KEY> key.<KEY> data[key] = value = evaluate.call $this, key callback? $this, key, value # Update the options page with the values from the current settings. load = -> log.trace() $('#analytics').prop 'checked', store.get 'analytics' do loadSaveEvents do loadFrequencies do loadOrders do loadNotifications do loadDeveloperTools # Update the developer tools section of the options page with the current settings. loadDeveloperTools = -> log.trace() do loadLogger # Update the frequency section of the options page with the current settings. loadFrequencies = -> log.trace() frequency = store.get 'frequency' $frequency = $ '#frequency' # Start from a clean slate. $frequency.remove 'option' # Create and insert options representing each available update frequency. for freq in ext.config.frequencies option = $ '<option/>', text: freq.text value: freq.value option.prop 'selected', freq.value is frequency $frequency.append option do loadFrequenciesSaveEvents # Bind the event handlers required for persisting frequency changes. loadFrequenciesSaveEvents = -> log.trace() $('#frequency').on 'change', -> value = $(this).val() log.debug "Changing frequency to '#{value}'" store.set 'frequency', parseInt frequency, 10 ext.updateOrders() analytics.track 'General', 'Changed', 'Frequency', value # Update the logging section of the options page with the current settings. loadLogger = -> log.trace() logger = store.get 'logger' $('#loggerEnabled').prop 'checked', logger.enabled loggerLevel = $ '#loggerLevel' loggerLevel.find('option').remove() for level in log.LEVELS option = $ '<option/>', text: i18n.get "opt_logger_level_#{level.name}_text" value: level.value option.prop 'selected', level.value is logger.level loggerLevel.append option # Ensure debug level is selected if configuration currently matches none. unless loggerLevel.find('option[selected]').length loggerLevel.find("option[value='#{log.DEBUG}']").prop 'selected', yes do loadLoggerSaveEvents # Bind the event handlers required for persisting logging changes. loadLoggerSaveEvents = -> log.trace() bindSaveEvent '#loggerEnabled, #loggerLevel', 'change', 'logger', (key) -> value = if key is 'level' then @val() else @is ':checked' log.debug "Changing logging #{key} to '#{value}'" value , (jel, key, value) -> logger = store.get 'logger' chrome.extension.getBackgroundPage().log.config = log.config = logger analytics.track 'Logging', 'Changed', key[0].toUpperCase() + key.substr(1), Number value # Update the notification section of the options page with the current settings. loadNotifications = -> log.trace() {badges, duration, enabled} = store.get 'notifications' $('#notificationsBadges').prop 'checked', badges $('#notificationsDuration').val if duration > 0 then duration * .001 else 0 $('#notificationsEnabled').prop 'checked', enabled do loadNotificationSaveEvents # Bind the event handlers required for persisting notification changes. loadNotificationSaveEvents = -> log.trace() bindSaveEvent '#notificationsBadges, #notificationsDuration, #notificationsEnabled', 'change', 'notifications', (key) -> value = if key is 'duration' milliseconds = @val() if milliseconds then parseInt(milliseconds, 10) * 1000 else 0 else @is ':checked' log.debug "Changing notifications #{key} to '#{value}'" value , (jel, key, value) -> analytics.track 'Notifications', 'Changed', key[0].toUpperCase() + key.substr(1), Number value # Create a `tr` element representing the `order` provided. # The element returned should then be inserted in to the table that is displaying the orders. loadOrder = (order) -> log.trace() log.debug 'Creating a row for the following order...', order row = $ '<tr/>', draggable: yes alignCenter = css: 'text-align': 'center' row.append $('<td/>', alignCenter).append $ '<input/>', title: i18n.get 'opt_select_box' type: 'checkbox' value: order.key row.append $('<td/>').append $ '<span/>', text: order.label title: i18n.get 'opt_order_modify_title', order.label row.append $('<td/>').append $('<span/>').append $ '<a/>', href: ext.getOrderUrl order target: '_blank' text: order.number title: i18n.get 'opt_order_title' row.append $('<td/>').append $ '<span/>', text: order.email row.append $('<td/>').append $ '<span/>', text: order.code row.append $('<td/>').append $ '<span/>', text: ext.getStatusText order row.append $('<td/>').append if order.trackingUrl $ '<a/>', href: order.trackingUrl target: '_blank' text: i18n.get 'opt_track_text' title: i18n.get 'opt_track_title' else '&nbsp;' row.append $('<td/>').append $ '<span/>', class: 'muted' text: '::::' title: i18n.get 'opt_order_move_title', order.label row # Bind the event handlers required for controlling the orders. loadOrderControlEvents = -> log.trace() # Ensure order wizard is closed if/when tabify links are clicked within it or it is cancelled. $('#order_wizard [tabify], #order_cancel_btn').on 'click', -> do closeWizard $('#order_reset_btn').on 'click', -> do resetWizard # Support search functionality for orders. filter = $ '#order_filter' filter.find('option').remove() for limit in ext.config.options.limits filter.append $ '<option/>', text: limit filter.append $ '<option/>', disabled: 'disabled' text: '-----' filter.append $ '<option/>', text: i18n.get 'opt_show_all_text' value: 0 store.init 'options_limit', parseInt $('#order_filter').val(), 10 limit = store.get 'options_limit' $('#order_filter option').each -> $this = $ this $this.prop 'selected', limit is parseInt $this.val(), 10 $('#order_filter').on 'change', -> store.set 'options_limit', parseInt $(this).val(), 10 loadOrderRows searchResults ? ext.orders $('#order_search :reset').on 'click', -> $('#order_search :text').val '' do searchOrders $('#order_controls').on 'submit', -> searchOrders $('#order_search :text').val() # Ensure user confirms deletion of order. $('#order_delete_btn').on 'click', -> $(this).hide() $('#order_confirm_delete').css 'display', 'inline-block' $('#order_undo_delete_btn').on 'click', -> $('#order_confirm_delete').hide() $('#order_delete_btn').show() $('#order_confirm_delete_btn').on 'click', -> $('#order_confirm_delete').hide() $('#order_delete_btn').show() deleteOrders [activeOrder] do closeWizard validationErrors = [] $('#order_wizard').on 'hide', -> error.hide() for error in validationErrors $('#order_save_btn').on 'click', -> order = deriveOrder() # Clear all existing validation errors. error.hide() for error in validationErrors validationErrors = validateOrder order if validationErrors.length error.show() for error in validationErrors else validationErrors = [] $.extend activeOrder, order saveOrder activeOrder $('#order_search :reset').hide() $('#order_search :text').val '' do closeWizard # Open the order wizard without any context. $('#add_btn').on 'click', -> openWizard null selectedOrders = [] $('#delete_wizard').on 'hide', -> selectedOrders = [] $('#delete_items li').remove() # Prompt the user to confirm removal of the selected order(s). $('#delete_btn').on 'click', -> deleteItems = $ '#delete_items' selectedOrders = getSelectedOrders() deleteItems.find('li').remove() # Create list items for each order and allocate them accordingly. for order in selectedOrders deleteItems.append $ '<li/>', text: "#{order.label} (#{order.number})" # Begin the order removal process by showing the dialog. $('#delete_wizard').modal 'show' # Cancel the order removal process. $('#delete_cancel_btn, #delete_no_btn').on 'click', -> $('#delete_wizard').modal 'hide' # Finalize the order removal process. $('#delete_yes_btn').on 'click', -> deleteOrders selectedOrders $('#delete_wizard').modal 'hide' # Load the `orders` into the table to be displayed to the user. # Optionally, pagination can be disabled but this should only really be used internally by the # pagination process. loadOrderRows = (orders = ext.orders, pagination = yes) -> log.trace() table = $ '#orders' # Start from a clean slate. table.find('tbody tr').remove() if orders.length # Create and insert rows representing each order. table.append loadOrder order for order in orders paginate orders if pagination activateTooltips table do activateDraggables do activateModifications do activateSelections else # Show single row to indicate no orders were found. table.find('tbody').append $('<tr/>').append $ '<td/>', colspan: table.find('thead th').length html: i18n.get 'opt_no_orders_found_text' # Update the orders section of the options page with the current settings. loadOrders = -> log.trace() # Load all of the event handlers required for managing the orders. do loadOrderControlEvents # Load the order data into the table. do loadOrderRows # Bind the event handlers required for persisting general changes. loadSaveEvents = -> log.trace() $('#analytics').on 'change', -> enabled = $(this).is ':checked' log.debug "Changing analytics to '#{enabled}'" if enabled store.set 'analytics', yes chrome.extension.getBackgroundPage().analytics.add() analytics.add() analytics.track 'General', 'Changed', 'Analytics', 1 else analytics.track 'General', 'Changed', 'Analytics', 0 analytics.remove() chrome.extension.getBackgroundPage().analytics.remove() store.set 'analytics', no # Save functions # -------------- # Delete all of the `orders` provided. deleteOrders = (orders) -> log.trace() keys = (order.key for order in orders) if keys.length keep = [] for order, i in ext.orders when order.key not in keys orders.index = i keep.push order store.set 'orders', keep ext.updateOrders() if keys.length > 1 log.debug "Deleted #{keys.length} orders" analytics.track 'Orders', 'Deleted', "Count[#{keys.length}]" else order = orders[0] log.debug "Deleted #{order.label} order" analytics.track 'Orders', 'Deleted', order.label loadOrderRows searchResults ? ext.orders # Reorder the orders after a drag and drop *swap* by updating their indices and sorting them # accordingly. # These changes are then persisted and should be reflected throughout the extension. reorderOrders = (fromIndex, toIndex) -> log.trace() orders = ext.orders if fromIndex? and toIndex? orders[fromIndex].index = toIndex orders[toIndex].index = fromIndex store.set 'orders', orders ext.updateOrders() # Update and persist the `order` provided. # Any required validation should be performed perior to calling this method. saveOrder = (order) -> log.trace() log.debug 'Saving the following order...', order isNew = not order.key? orders = store.get 'orders' if isNew order.key = utils.keyGen() orders.push order else for temp, i in orders when temp.key is order.key orders[i] = order break store.set 'orders', orders ext.updateOrders() do loadOrderRows action = if isNew then 'Added' else 'Saved' analytics.track 'Orders', action, order.label order # Validation classes # ------------------ # `ValidationError` allows easy management and display of validation error messages that are # associated with specific fields. class ValidationError extends utils.Class # Create a new instance of `ValidationError`. constructor: (@id, @key) -> @className = 'error' # Hide any validation messages currently displayed for the associated field. hide: -> field = $ "##{@id}" field.parents('.control-group:first').removeClass @className field.parents('.controls:first').find('.help-block').remove() # Display the validation message for the associated field. show: -> field = $ "##{@id}" field.parents('.control-group:first').addClass @className field.parents('.controls:first').append $ '<span/>', class: 'help-block' html: i18n.get @key # `ValidationWarning` allows easy management and display of validation warning messages that are # associated with specific fields. class ValidationWarning extends ValidationError # Create a new instance of `ValidationWarning`. constructor: (@id, @key) -> @className = 'warning' # Validation functions # -------------------- # Indicate whether or not the specified `key` is valid. isKeyValid = (key) -> log.trace() log.debug "Validating order key '#{key}'" R_VALID_KEY.test key # Determine whether an order number already exists. isNumberAvailable = (order) -> log.trace() {key, number} = order not ext.queryOrder (order) -> order.number is number and order.key isnt key # Validate the `order` and return any validation errors/warnings that were encountered. validateOrder = (order) -> log.trace() isNew = not order.key? errors = [] log.debug 'Validating the following order...', order # Label is missing but is required. unless order.label errors.push new ValidationError 'order_label', 'opt_field_required_error' # Number is missing but is required. unless order.number errors.push new ValidationError 'order_number', 'opt_field_required_error' # Number already exists. unless isNumberAvailable order errors.push new ValidationError 'order_number', 'opt_field_unavailable_error' # Post/zip code and email are missing but at least one is required. unless order.code or order.email errors.push new ValidationError 'order_code', 'opt_field_required_error' errors.push new ValidationError 'order_email', 'opt_field_required_error' # Indicate whether or not any validation errors were encountered. log.debug 'Following validation errors were found...', errors errors # Miscellaneous classes # --------------------- # `Message` allows simple management and display of alert messages. class Message extends utils.Class # Create a new instance of `Message`. constructor: (@block) -> @className = 'alert-info' @headerKey = 'opt<KEY>_message_header' # Hide this `Message` if it has previously been displayed. hide: -> @alert?.alert 'close' # Display this `Message` at the top of the current tab. show: -> @header = i18n.get @headerKey if @headerKey and not @header? @message = i18n.get @messageKey if @messageKey and not @message? @alert = $ '<div/>', class: "alert #{@className}" @alert.addClass 'alert-block' if @block @alert.append $ '<button/>', class: 'close' 'data-dismiss': 'alert' html: '&times;' type: 'button' @alert.append $ "<#{if @block then 'h4' else 'strong'}/>", html: @header if @header @alert.append if @block then @message else " #{@message}" if @message @alert.prependTo $ $('#navigation li.active a').attr 'tabify' # `ErrorMessage` allows simple management and display of error messages. class ErrorMessage extends Message # Create a new instance of `ErrorMessage`. constructor: (@block) -> @className = 'alert-error' @headerKey = '<KEY>error_<KEY>' # `SuccessMessage` allows simple management and display of success messages. class SuccessMessage extends Message # Create a new instance of `SuccessMessage`. constructor: (@block) -> @className = 'alert-success' @headerKey = '<KEY>' # `WarningMessage` allows simple management and display of warning messages. class WarningMessage extends Message # Create a new instance of `WarningMessage`. constructor: (@block) -> @className = '' @headerKey = '<KEY>' # Miscellaneous functions # ----------------------- # Activate drag and drop functionality for reordering orders. # The activation is done cleanly, unbinding any associated events that have been previously bound. activateDraggables = -> log.trace() table = $ '#orders' dragSource = null draggables = table.find '[draggable]' draggables.off 'dragstart dragend dragenter dragover drop' draggables.on 'dragstart', (e) -> $this = $ this dragSource = this table.removeClass 'table-hover' $this.addClass 'dnd-moving' $this.find('[data-original-title]').tooltip 'hide' e.originalEvent.dataTransfer.effectAllowed = 'move' e.originalEvent.dataTransfer.setData 'text/html', $this.html() draggables.on 'dragend', (e) -> draggables.removeClass 'dnd-moving dnd-over' table.addClass 'table-hover' dragSource = null draggables.on 'dragenter', (e) -> $this = $ this draggables.not($this).removeClass 'dnd-over' $this.addClass 'dnd-over' draggables.on 'dragover', (e) -> e.preventDefault() e.originalEvent.dataTransfer.dropEffect = 'move' no draggables.on 'drop', (e) -> $dragSource = $ dragSource e.stopPropagation() if dragSource isnt this $this = $ this $dragSource.html $this.html() $this.html e.originalEvent.dataTransfer.getData 'text/html' activateTooltips table do activateModifications do activateSelections fromIndex = $dragSource.index() toIndex = $this.index() if searchResults? fromIndex = searchResults[fromIndex].index toIndex = searchResults[toIndex].index reorderOrders fromIndex, toIndex no # Activate functionality to open order wizard when a row is clicked. # The activation is done cleanly, unbinding any associated events that have been previously bound. activateModifications = -> log.trace() $('#orders tbody tr td:not(:first-child)').off('click').on 'click', -> activeKey = $(this).parents('tr:first').find(':checkbox').val() openWizard ext.queryOrder (order) -> order.key is activeKey # Activate select all/one functionality on the orders table. # The activation is done cleanly, unbinding any associated events that have been previously bound. activateSelections = -> log.trace() table = $ '#orders' selectBoxes = table.find 'tbody :checkbox' selectBoxes.off('change').on 'change', -> $this = $ this messageKey = '<KEY>' messageKey += <KEY>' if $this.is ':checked' $this.attr 'data-original-title', i18n.get messageKey do refreshSelectButtons table.find('thead :checkbox').off('change').on 'change', -> $this = $ this checked = $this.is ':checked' messageKey = '<KEY>' messageKey += <KEY>' if checked $this.attr 'data-original-title', i18n.get messageKey selectBoxes.prop 'checked', checked do refreshSelectButtons # Activate tooltip effects, optionally only within a specific context. # The activation is done cleanly, unbinding any associated events that have been previously bound. activateTooltips = (selector) -> log.trace() base = $ selector or document base.find('[data-original-title]').each -> $this = $ this $this.tooltip 'destroy' $this.attr 'title', $this.attr 'data-original-title' $this.removeAttr 'data-original-title' base.find('[title]').each -> $this = $ this placement = $this.attr 'data-placement' placement = if placement? then trimToLower placement else 'top' $this.tooltip container: $this.attr('data-container') ? 'body' placement: placement # Convenient shorthand for setting the current context to `null`. clearContext = -> do setContext # Clear the current context and close the order wizard. closeWizard = -> do clearContext $('#order_wizard').modal 'hide' # Create a order based on the current context and the information derived from the wizard fields. deriveOrder = -> log.trace() order = code: $('#order_code').val().trim() email: $('#order_email').val().trim() label: $('#order_label').val().trim() number: $('#order_number').val().trim() error: activeOrder.error ? '' index: activeOrder.index ? ext.orders.length key: activeOrder.key trackingUrl: activeOrder.trackingUrl ? '' updates: activeOrder.updates ? [] log.debug 'Following order was derived...', order order # Add the user feedback feature to the page. feedback = -> log.trace() unless feedbackAdded # Continue with normal process of loading Widget. uv = document.createElement 'script' uv.async = 'async' uv.src = "https://widget.uservoice.com/#{ext.config.options.userVoice.id}.js" script = document.getElementsByTagName('script')[0] script.parentNode.insertBefore uv, script # Configure the widget as it's loading. UserVoice = window.UserVoice or= [] UserVoice.push [ 'showTab' 'classic_widget' { mode: 'full' primary_color: '#333' link_color: '#08c' default_mode: 'feedback' forum_id: ext.config.options.userVoice.forum tab_label: i18n.get 'opt_feedback_button' tab_color: '#333' tab_position: 'middle-left' tab_inverted: yes } ] feedbackAdded = yes # Retrieve all currently selected orders. getSelectedOrders = -> selectedKeys = [] $('#orders tbody :checkbox:checked').each -> selectedKeys.push $(this).val() ext.queryOrders (order) -> order.key in selectedKeys # Open the order wizard after optionally setting the current context. openWizard = (order) -> setContext order if arguments.length $('#order_wizard').modal 'show' # Update the pagination UI for the specified `orders`. paginate = (orders) -> log.trace() limit = parseInt $('#order_filter').val(), 10 pagination = $ '#pagination' if orders.length > limit > 0 children = pagination.find 'ul li' pages = Math.ceil orders.length / limit # Refresh the pagination link states based on the new `page`. refreshPagination = (page = 1) -> # Select and display the desired orders subset. start = limit * (page - 1) end = start + limit loadOrderRows orders[start...end], no # Ensure the *previous* link is only enabled when a previous page exists. pagination.find('ul li:first-child').each -> $this = $ this if page is 1 then $this.addClass 'disabled' else $this.removeClass 'disabled' # Ensure only the active page is highlighted. pagination.find('ul li:not(:first-child, :last-child)').each -> $this = $ this if page is parseInt $this.text(), 10 then $this.addClass 'active' else $this.removeClass 'active' # Ensure the *next* link is only enabled when a next page exists. pagination.find('ul li:last-child').each -> $this = $ this if page is pages then $this.addClass 'disabled' else $this.removeClass 'disabled' # Create and insert pagination links. if pages isnt children.length - 2 children.remove() list = pagination.find 'ul' list.append $('<li/>').append $ '<a>&laquo;</a>' for page in [1..pages] list.append $('<li/>').append $ "<a>#{page}</a>" list.append $('<li/>').append $ '<a>&raquo;</a>' # Bind event handlers to manage navigating pages. pagination.find('ul li').off 'click' pagination.find('ul li:first-child').on 'click', -> unless $(this).hasClass 'disabled' refreshPagination pagination.find('ul li.active').index() - 1 pagination.find('ul li:not(:first-child, :last-child)').on 'click', -> $this = $ this refreshPagination $this.index() unless $this.hasClass 'active' pagination.find('ul li:last-child').on 'click', -> unless $(this).hasClass 'disabled' refreshPagination pagination.find('ul li.active').index() + 1 do refreshPagination pagination.show() else # Hide the pagination and remove all links as the results fit on a single page. pagination.hide().find('ul li').remove() # Update the state of the reset button depending on the current search input. refreshResetButton = -> log.trace() container = $ '#order_search' resetButton = container.find ':reset' if container.find(':text').val() container.addClass 'input-prepend' resetButton.show() else resetButton.hide() container.removeClass 'input-prepend' # Update the state of certain buttons depending on whether any select boxes have been checked. refreshSelectButtons = -> log.trace() selections = $ '#orders tbody :checkbox:checked' $('#delete_btn').prop 'disabled', selections.length is 0 # Reset the wizard field values based on the current context. resetWizard = -> log.trace() activeOrder ?= {} $('#order_wizard .modal-header h3').html if activeOrder.key? i18n.get 'opt_order_modify_title', activeOrder.label else i18n.get 'opt_order_new_header' # Assign values to their respective fields. $('#order_code').val activeOrder.code or '' $('#order_email').val activeOrder.email or '' $('#order_label').val activeOrder.label or '' $('#order_number').val activeOrder.number or '' $('#order_delete_btn').each -> $this = $ this if activeOrder.key? then $this.show() else $this.hide() # Search the orders for the specified `query` and filter those displayed. searchOrders = (query = '') -> log.trace() keywords = query.replace(R_CLEAN_QUERY, '').split R_WHITESPACE if keywords.length expression = /// #{(keyword for keyword in keywords when keyword).join '|'} ///i searchResults = ext.queryOrders (order) -> expression.test "#{order.code} #{order.email} #{order.label} #{order.number}" else searchResults = null loadOrderRows searchResults ? ext.orders do refreshResetButton do refreshSelectButtons # Set the current context of the order wizard. setContext = (order = {}) -> log.trace() activeOrder = {} $.extend activeOrder, order do resetWizard # Convenient shorthand for safely trimming a string to lower case. trimToLower = (str = '') -> str.trim().toLowerCase() # Convenient shorthand for safely trimming a string to upper case. trimToUpper = (str = '') -> str.trim().toUpperCase() # Options page setup # ------------------ options = window.options = new class Options extends utils.Class # Public functions # ---------------- # Initialize the options page. # This will involve inserting and configuring the UI elements as well as loading the current # settings. init: -> log.trace() log.info 'Initializing the options page' # Add support for analytics if the user hasn't opted out. analytics.add() if store.get 'analytics' # Add the user feedback feature to the page. do feedback # Begin initialization. i18n.init() $('.year-repl').html "#{new Date().getFullYear()}" # Bind tab selection event to all tabs. initialTabChange = yes $('a[tabify]').on 'click', -> target = $(this).attr 'tabify' nav = $ "#navigation a[tabify='#{target}']" parent = nav.parent 'li' unless parent.hasClass 'active' parent.siblings().removeClass 'active' parent.addClass 'active' $(target).show().siblings('.tab').hide() id = nav.attr 'id' store.set 'options_active_tab', id unless initialTabChange id = id.match(/(\S*)_nav$/)[1] id = id[0].toUpperCase() + id.substr 1 log.debug "Changing tab to #{id}" analytics.track 'Tabs', 'Changed', id initialTabChange = no $(document.body).scrollTop 0 # Reflect the persisted tab. store.init 'options_active_tab', 'general_nav' optionsActiveTab = store.get 'options_active_tab' $("##{optionsActiveTab}").trigger 'click' log.debug "Initially displaying tab for #{optionsActiveTab}" # Bind Developer Tools wizard events to their corresponding elements. $('#tools_nav').on 'click', -> $('#tools_wizard').modal 'show' $('.tools_close_btn').on 'click', -> $('#tools_wizard').modal 'hide' # Ensure that form submissions don't reload the page. $('form:not([target="_blank"])').on 'submit', -> no # Bind analytical tracking events to key footer buttons and links. $('footer a[href*="neocotic.com"]').on 'click', -> analytics.track 'Footer', 'Clicked', 'Homepage' # Setup and configure the donation button in the footer. $('#donation input[name="hosted_button_id"]').val ext.config.options.payPal $('#donation').on 'submit', -> analytics.track 'Footer', 'Clicked', 'Donate' # Load the current option values. do load # Initialize all popovers, tooltips and *go-to* links. $('[popover]').each -> $this = $ this placement = $this.attr 'data-placement' placement = if placement? then trimToLower placement else 'right' trigger = $this.attr 'data-trigger' trigger = if trigger? then trimToLower trigger else 'hover' $this.popover content: -> i18n.get $this.attr 'popover' html: yes placement: placement trigger: trigger if trigger is 'manual' $this.on 'click', -> $this.popover 'toggle' do activateTooltips navHeight = $('.navbar').height() $('[data-goto]').on 'click', -> goto = $ $(this).attr 'data-goto' pos = goto.position()?.top or 0 pos -= navHeight if pos and pos >= navHeight log.debug "Relocating view to include '#{goto.selector}' at #{pos}" $(window).scrollTop pos # Ensure that the persisted tab is currently visible. # This should be called if the user clicks the Options link in the popup while and options page # is already open. refresh: -> $("##{store.get 'options_active_tab'}").trigger 'click' # Initialize `options` when the DOM is ready. utils.ready -> options.init()
true
# [iOrder](http://neocotic.com/iOrder) # (c) 2013 PI:NAME:<NAME>END_PI # Freely distributable under the MIT license. # For all details and documentation: # <http://neocotic.com/iOrder> # Private constants # ----------------- # Regular expression used to sanitize search queries. R_CLEAN_QUERY = /[^\w\s]/g # Regular expression used to validate order keys. R_VALID_KEY = /^[A-PI:KEY:<KEY>END_PI[PI:KEY:<KEY>END_PIi # Regular expression used to identify whitespace. R_WHITESPACE = /\s+/ # Private variables # ----------------- # Copy of order being actively modified. activeOrder = null # Easily accessible reference to the extension controller. {ext} = chrome.extension.getBackgroundPage() # Indicate whether or not the user feedback feature has been added to the page. feedbackAdded = no # Orders matching the current search query. searchResults = null # Load functions # -------------- # Bind an event of the specified `type` to the elements included by `selector` that, when # triggered, modifies the underlying `option` with the value returned by `evaluate`. bindSaveEvent = (selector, type, option, evaluate, callback) -> log.trace() $(selector).on type, -> $this = $ this key = '' value = null store.modify option, (data) -> key = $this.attr('id').match(new RegExp("^#{option}(\\S*)"))[1] key = key[PI:KEY:<KEY>END_PI key.PI:KEY:<KEY>END_PI data[key] = value = evaluate.call $this, key callback? $this, key, value # Update the options page with the values from the current settings. load = -> log.trace() $('#analytics').prop 'checked', store.get 'analytics' do loadSaveEvents do loadFrequencies do loadOrders do loadNotifications do loadDeveloperTools # Update the developer tools section of the options page with the current settings. loadDeveloperTools = -> log.trace() do loadLogger # Update the frequency section of the options page with the current settings. loadFrequencies = -> log.trace() frequency = store.get 'frequency' $frequency = $ '#frequency' # Start from a clean slate. $frequency.remove 'option' # Create and insert options representing each available update frequency. for freq in ext.config.frequencies option = $ '<option/>', text: freq.text value: freq.value option.prop 'selected', freq.value is frequency $frequency.append option do loadFrequenciesSaveEvents # Bind the event handlers required for persisting frequency changes. loadFrequenciesSaveEvents = -> log.trace() $('#frequency').on 'change', -> value = $(this).val() log.debug "Changing frequency to '#{value}'" store.set 'frequency', parseInt frequency, 10 ext.updateOrders() analytics.track 'General', 'Changed', 'Frequency', value # Update the logging section of the options page with the current settings. loadLogger = -> log.trace() logger = store.get 'logger' $('#loggerEnabled').prop 'checked', logger.enabled loggerLevel = $ '#loggerLevel' loggerLevel.find('option').remove() for level in log.LEVELS option = $ '<option/>', text: i18n.get "opt_logger_level_#{level.name}_text" value: level.value option.prop 'selected', level.value is logger.level loggerLevel.append option # Ensure debug level is selected if configuration currently matches none. unless loggerLevel.find('option[selected]').length loggerLevel.find("option[value='#{log.DEBUG}']").prop 'selected', yes do loadLoggerSaveEvents # Bind the event handlers required for persisting logging changes. loadLoggerSaveEvents = -> log.trace() bindSaveEvent '#loggerEnabled, #loggerLevel', 'change', 'logger', (key) -> value = if key is 'level' then @val() else @is ':checked' log.debug "Changing logging #{key} to '#{value}'" value , (jel, key, value) -> logger = store.get 'logger' chrome.extension.getBackgroundPage().log.config = log.config = logger analytics.track 'Logging', 'Changed', key[0].toUpperCase() + key.substr(1), Number value # Update the notification section of the options page with the current settings. loadNotifications = -> log.trace() {badges, duration, enabled} = store.get 'notifications' $('#notificationsBadges').prop 'checked', badges $('#notificationsDuration').val if duration > 0 then duration * .001 else 0 $('#notificationsEnabled').prop 'checked', enabled do loadNotificationSaveEvents # Bind the event handlers required for persisting notification changes. loadNotificationSaveEvents = -> log.trace() bindSaveEvent '#notificationsBadges, #notificationsDuration, #notificationsEnabled', 'change', 'notifications', (key) -> value = if key is 'duration' milliseconds = @val() if milliseconds then parseInt(milliseconds, 10) * 1000 else 0 else @is ':checked' log.debug "Changing notifications #{key} to '#{value}'" value , (jel, key, value) -> analytics.track 'Notifications', 'Changed', key[0].toUpperCase() + key.substr(1), Number value # Create a `tr` element representing the `order` provided. # The element returned should then be inserted in to the table that is displaying the orders. loadOrder = (order) -> log.trace() log.debug 'Creating a row for the following order...', order row = $ '<tr/>', draggable: yes alignCenter = css: 'text-align': 'center' row.append $('<td/>', alignCenter).append $ '<input/>', title: i18n.get 'opt_select_box' type: 'checkbox' value: order.key row.append $('<td/>').append $ '<span/>', text: order.label title: i18n.get 'opt_order_modify_title', order.label row.append $('<td/>').append $('<span/>').append $ '<a/>', href: ext.getOrderUrl order target: '_blank' text: order.number title: i18n.get 'opt_order_title' row.append $('<td/>').append $ '<span/>', text: order.email row.append $('<td/>').append $ '<span/>', text: order.code row.append $('<td/>').append $ '<span/>', text: ext.getStatusText order row.append $('<td/>').append if order.trackingUrl $ '<a/>', href: order.trackingUrl target: '_blank' text: i18n.get 'opt_track_text' title: i18n.get 'opt_track_title' else '&nbsp;' row.append $('<td/>').append $ '<span/>', class: 'muted' text: '::::' title: i18n.get 'opt_order_move_title', order.label row # Bind the event handlers required for controlling the orders. loadOrderControlEvents = -> log.trace() # Ensure order wizard is closed if/when tabify links are clicked within it or it is cancelled. $('#order_wizard [tabify], #order_cancel_btn').on 'click', -> do closeWizard $('#order_reset_btn').on 'click', -> do resetWizard # Support search functionality for orders. filter = $ '#order_filter' filter.find('option').remove() for limit in ext.config.options.limits filter.append $ '<option/>', text: limit filter.append $ '<option/>', disabled: 'disabled' text: '-----' filter.append $ '<option/>', text: i18n.get 'opt_show_all_text' value: 0 store.init 'options_limit', parseInt $('#order_filter').val(), 10 limit = store.get 'options_limit' $('#order_filter option').each -> $this = $ this $this.prop 'selected', limit is parseInt $this.val(), 10 $('#order_filter').on 'change', -> store.set 'options_limit', parseInt $(this).val(), 10 loadOrderRows searchResults ? ext.orders $('#order_search :reset').on 'click', -> $('#order_search :text').val '' do searchOrders $('#order_controls').on 'submit', -> searchOrders $('#order_search :text').val() # Ensure user confirms deletion of order. $('#order_delete_btn').on 'click', -> $(this).hide() $('#order_confirm_delete').css 'display', 'inline-block' $('#order_undo_delete_btn').on 'click', -> $('#order_confirm_delete').hide() $('#order_delete_btn').show() $('#order_confirm_delete_btn').on 'click', -> $('#order_confirm_delete').hide() $('#order_delete_btn').show() deleteOrders [activeOrder] do closeWizard validationErrors = [] $('#order_wizard').on 'hide', -> error.hide() for error in validationErrors $('#order_save_btn').on 'click', -> order = deriveOrder() # Clear all existing validation errors. error.hide() for error in validationErrors validationErrors = validateOrder order if validationErrors.length error.show() for error in validationErrors else validationErrors = [] $.extend activeOrder, order saveOrder activeOrder $('#order_search :reset').hide() $('#order_search :text').val '' do closeWizard # Open the order wizard without any context. $('#add_btn').on 'click', -> openWizard null selectedOrders = [] $('#delete_wizard').on 'hide', -> selectedOrders = [] $('#delete_items li').remove() # Prompt the user to confirm removal of the selected order(s). $('#delete_btn').on 'click', -> deleteItems = $ '#delete_items' selectedOrders = getSelectedOrders() deleteItems.find('li').remove() # Create list items for each order and allocate them accordingly. for order in selectedOrders deleteItems.append $ '<li/>', text: "#{order.label} (#{order.number})" # Begin the order removal process by showing the dialog. $('#delete_wizard').modal 'show' # Cancel the order removal process. $('#delete_cancel_btn, #delete_no_btn').on 'click', -> $('#delete_wizard').modal 'hide' # Finalize the order removal process. $('#delete_yes_btn').on 'click', -> deleteOrders selectedOrders $('#delete_wizard').modal 'hide' # Load the `orders` into the table to be displayed to the user. # Optionally, pagination can be disabled but this should only really be used internally by the # pagination process. loadOrderRows = (orders = ext.orders, pagination = yes) -> log.trace() table = $ '#orders' # Start from a clean slate. table.find('tbody tr').remove() if orders.length # Create and insert rows representing each order. table.append loadOrder order for order in orders paginate orders if pagination activateTooltips table do activateDraggables do activateModifications do activateSelections else # Show single row to indicate no orders were found. table.find('tbody').append $('<tr/>').append $ '<td/>', colspan: table.find('thead th').length html: i18n.get 'opt_no_orders_found_text' # Update the orders section of the options page with the current settings. loadOrders = -> log.trace() # Load all of the event handlers required for managing the orders. do loadOrderControlEvents # Load the order data into the table. do loadOrderRows # Bind the event handlers required for persisting general changes. loadSaveEvents = -> log.trace() $('#analytics').on 'change', -> enabled = $(this).is ':checked' log.debug "Changing analytics to '#{enabled}'" if enabled store.set 'analytics', yes chrome.extension.getBackgroundPage().analytics.add() analytics.add() analytics.track 'General', 'Changed', 'Analytics', 1 else analytics.track 'General', 'Changed', 'Analytics', 0 analytics.remove() chrome.extension.getBackgroundPage().analytics.remove() store.set 'analytics', no # Save functions # -------------- # Delete all of the `orders` provided. deleteOrders = (orders) -> log.trace() keys = (order.key for order in orders) if keys.length keep = [] for order, i in ext.orders when order.key not in keys orders.index = i keep.push order store.set 'orders', keep ext.updateOrders() if keys.length > 1 log.debug "Deleted #{keys.length} orders" analytics.track 'Orders', 'Deleted', "Count[#{keys.length}]" else order = orders[0] log.debug "Deleted #{order.label} order" analytics.track 'Orders', 'Deleted', order.label loadOrderRows searchResults ? ext.orders # Reorder the orders after a drag and drop *swap* by updating their indices and sorting them # accordingly. # These changes are then persisted and should be reflected throughout the extension. reorderOrders = (fromIndex, toIndex) -> log.trace() orders = ext.orders if fromIndex? and toIndex? orders[fromIndex].index = toIndex orders[toIndex].index = fromIndex store.set 'orders', orders ext.updateOrders() # Update and persist the `order` provided. # Any required validation should be performed perior to calling this method. saveOrder = (order) -> log.trace() log.debug 'Saving the following order...', order isNew = not order.key? orders = store.get 'orders' if isNew order.key = utils.keyGen() orders.push order else for temp, i in orders when temp.key is order.key orders[i] = order break store.set 'orders', orders ext.updateOrders() do loadOrderRows action = if isNew then 'Added' else 'Saved' analytics.track 'Orders', action, order.label order # Validation classes # ------------------ # `ValidationError` allows easy management and display of validation error messages that are # associated with specific fields. class ValidationError extends utils.Class # Create a new instance of `ValidationError`. constructor: (@id, @key) -> @className = 'error' # Hide any validation messages currently displayed for the associated field. hide: -> field = $ "##{@id}" field.parents('.control-group:first').removeClass @className field.parents('.controls:first').find('.help-block').remove() # Display the validation message for the associated field. show: -> field = $ "##{@id}" field.parents('.control-group:first').addClass @className field.parents('.controls:first').append $ '<span/>', class: 'help-block' html: i18n.get @key # `ValidationWarning` allows easy management and display of validation warning messages that are # associated with specific fields. class ValidationWarning extends ValidationError # Create a new instance of `ValidationWarning`. constructor: (@id, @key) -> @className = 'warning' # Validation functions # -------------------- # Indicate whether or not the specified `key` is valid. isKeyValid = (key) -> log.trace() log.debug "Validating order key '#{key}'" R_VALID_KEY.test key # Determine whether an order number already exists. isNumberAvailable = (order) -> log.trace() {key, number} = order not ext.queryOrder (order) -> order.number is number and order.key isnt key # Validate the `order` and return any validation errors/warnings that were encountered. validateOrder = (order) -> log.trace() isNew = not order.key? errors = [] log.debug 'Validating the following order...', order # Label is missing but is required. unless order.label errors.push new ValidationError 'order_label', 'opt_field_required_error' # Number is missing but is required. unless order.number errors.push new ValidationError 'order_number', 'opt_field_required_error' # Number already exists. unless isNumberAvailable order errors.push new ValidationError 'order_number', 'opt_field_unavailable_error' # Post/zip code and email are missing but at least one is required. unless order.code or order.email errors.push new ValidationError 'order_code', 'opt_field_required_error' errors.push new ValidationError 'order_email', 'opt_field_required_error' # Indicate whether or not any validation errors were encountered. log.debug 'Following validation errors were found...', errors errors # Miscellaneous classes # --------------------- # `Message` allows simple management and display of alert messages. class Message extends utils.Class # Create a new instance of `Message`. constructor: (@block) -> @className = 'alert-info' @headerKey = 'optPI:KEY:<KEY>END_PI_message_header' # Hide this `Message` if it has previously been displayed. hide: -> @alert?.alert 'close' # Display this `Message` at the top of the current tab. show: -> @header = i18n.get @headerKey if @headerKey and not @header? @message = i18n.get @messageKey if @messageKey and not @message? @alert = $ '<div/>', class: "alert #{@className}" @alert.addClass 'alert-block' if @block @alert.append $ '<button/>', class: 'close' 'data-dismiss': 'alert' html: '&times;' type: 'button' @alert.append $ "<#{if @block then 'h4' else 'strong'}/>", html: @header if @header @alert.append if @block then @message else " #{@message}" if @message @alert.prependTo $ $('#navigation li.active a').attr 'tabify' # `ErrorMessage` allows simple management and display of error messages. class ErrorMessage extends Message # Create a new instance of `ErrorMessage`. constructor: (@block) -> @className = 'alert-error' @headerKey = 'PI:KEY:<KEY>END_PIerror_PI:KEY:<KEY>END_PI' # `SuccessMessage` allows simple management and display of success messages. class SuccessMessage extends Message # Create a new instance of `SuccessMessage`. constructor: (@block) -> @className = 'alert-success' @headerKey = 'PI:KEY:<KEY>END_PI' # `WarningMessage` allows simple management and display of warning messages. class WarningMessage extends Message # Create a new instance of `WarningMessage`. constructor: (@block) -> @className = '' @headerKey = 'PI:KEY:<KEY>END_PI' # Miscellaneous functions # ----------------------- # Activate drag and drop functionality for reordering orders. # The activation is done cleanly, unbinding any associated events that have been previously bound. activateDraggables = -> log.trace() table = $ '#orders' dragSource = null draggables = table.find '[draggable]' draggables.off 'dragstart dragend dragenter dragover drop' draggables.on 'dragstart', (e) -> $this = $ this dragSource = this table.removeClass 'table-hover' $this.addClass 'dnd-moving' $this.find('[data-original-title]').tooltip 'hide' e.originalEvent.dataTransfer.effectAllowed = 'move' e.originalEvent.dataTransfer.setData 'text/html', $this.html() draggables.on 'dragend', (e) -> draggables.removeClass 'dnd-moving dnd-over' table.addClass 'table-hover' dragSource = null draggables.on 'dragenter', (e) -> $this = $ this draggables.not($this).removeClass 'dnd-over' $this.addClass 'dnd-over' draggables.on 'dragover', (e) -> e.preventDefault() e.originalEvent.dataTransfer.dropEffect = 'move' no draggables.on 'drop', (e) -> $dragSource = $ dragSource e.stopPropagation() if dragSource isnt this $this = $ this $dragSource.html $this.html() $this.html e.originalEvent.dataTransfer.getData 'text/html' activateTooltips table do activateModifications do activateSelections fromIndex = $dragSource.index() toIndex = $this.index() if searchResults? fromIndex = searchResults[fromIndex].index toIndex = searchResults[toIndex].index reorderOrders fromIndex, toIndex no # Activate functionality to open order wizard when a row is clicked. # The activation is done cleanly, unbinding any associated events that have been previously bound. activateModifications = -> log.trace() $('#orders tbody tr td:not(:first-child)').off('click').on 'click', -> activeKey = $(this).parents('tr:first').find(':checkbox').val() openWizard ext.queryOrder (order) -> order.key is activeKey # Activate select all/one functionality on the orders table. # The activation is done cleanly, unbinding any associated events that have been previously bound. activateSelections = -> log.trace() table = $ '#orders' selectBoxes = table.find 'tbody :checkbox' selectBoxes.off('change').on 'change', -> $this = $ this messageKey = 'PI:KEY:<KEY>END_PI' messageKey += PI:KEY:<KEY>END_PI' if $this.is ':checked' $this.attr 'data-original-title', i18n.get messageKey do refreshSelectButtons table.find('thead :checkbox').off('change').on 'change', -> $this = $ this checked = $this.is ':checked' messageKey = 'PI:KEY:<KEY>END_PI' messageKey += PI:KEY:<KEY>END_PI' if checked $this.attr 'data-original-title', i18n.get messageKey selectBoxes.prop 'checked', checked do refreshSelectButtons # Activate tooltip effects, optionally only within a specific context. # The activation is done cleanly, unbinding any associated events that have been previously bound. activateTooltips = (selector) -> log.trace() base = $ selector or document base.find('[data-original-title]').each -> $this = $ this $this.tooltip 'destroy' $this.attr 'title', $this.attr 'data-original-title' $this.removeAttr 'data-original-title' base.find('[title]').each -> $this = $ this placement = $this.attr 'data-placement' placement = if placement? then trimToLower placement else 'top' $this.tooltip container: $this.attr('data-container') ? 'body' placement: placement # Convenient shorthand for setting the current context to `null`. clearContext = -> do setContext # Clear the current context and close the order wizard. closeWizard = -> do clearContext $('#order_wizard').modal 'hide' # Create a order based on the current context and the information derived from the wizard fields. deriveOrder = -> log.trace() order = code: $('#order_code').val().trim() email: $('#order_email').val().trim() label: $('#order_label').val().trim() number: $('#order_number').val().trim() error: activeOrder.error ? '' index: activeOrder.index ? ext.orders.length key: activeOrder.key trackingUrl: activeOrder.trackingUrl ? '' updates: activeOrder.updates ? [] log.debug 'Following order was derived...', order order # Add the user feedback feature to the page. feedback = -> log.trace() unless feedbackAdded # Continue with normal process of loading Widget. uv = document.createElement 'script' uv.async = 'async' uv.src = "https://widget.uservoice.com/#{ext.config.options.userVoice.id}.js" script = document.getElementsByTagName('script')[0] script.parentNode.insertBefore uv, script # Configure the widget as it's loading. UserVoice = window.UserVoice or= [] UserVoice.push [ 'showTab' 'classic_widget' { mode: 'full' primary_color: '#333' link_color: '#08c' default_mode: 'feedback' forum_id: ext.config.options.userVoice.forum tab_label: i18n.get 'opt_feedback_button' tab_color: '#333' tab_position: 'middle-left' tab_inverted: yes } ] feedbackAdded = yes # Retrieve all currently selected orders. getSelectedOrders = -> selectedKeys = [] $('#orders tbody :checkbox:checked').each -> selectedKeys.push $(this).val() ext.queryOrders (order) -> order.key in selectedKeys # Open the order wizard after optionally setting the current context. openWizard = (order) -> setContext order if arguments.length $('#order_wizard').modal 'show' # Update the pagination UI for the specified `orders`. paginate = (orders) -> log.trace() limit = parseInt $('#order_filter').val(), 10 pagination = $ '#pagination' if orders.length > limit > 0 children = pagination.find 'ul li' pages = Math.ceil orders.length / limit # Refresh the pagination link states based on the new `page`. refreshPagination = (page = 1) -> # Select and display the desired orders subset. start = limit * (page - 1) end = start + limit loadOrderRows orders[start...end], no # Ensure the *previous* link is only enabled when a previous page exists. pagination.find('ul li:first-child').each -> $this = $ this if page is 1 then $this.addClass 'disabled' else $this.removeClass 'disabled' # Ensure only the active page is highlighted. pagination.find('ul li:not(:first-child, :last-child)').each -> $this = $ this if page is parseInt $this.text(), 10 then $this.addClass 'active' else $this.removeClass 'active' # Ensure the *next* link is only enabled when a next page exists. pagination.find('ul li:last-child').each -> $this = $ this if page is pages then $this.addClass 'disabled' else $this.removeClass 'disabled' # Create and insert pagination links. if pages isnt children.length - 2 children.remove() list = pagination.find 'ul' list.append $('<li/>').append $ '<a>&laquo;</a>' for page in [1..pages] list.append $('<li/>').append $ "<a>#{page}</a>" list.append $('<li/>').append $ '<a>&raquo;</a>' # Bind event handlers to manage navigating pages. pagination.find('ul li').off 'click' pagination.find('ul li:first-child').on 'click', -> unless $(this).hasClass 'disabled' refreshPagination pagination.find('ul li.active').index() - 1 pagination.find('ul li:not(:first-child, :last-child)').on 'click', -> $this = $ this refreshPagination $this.index() unless $this.hasClass 'active' pagination.find('ul li:last-child').on 'click', -> unless $(this).hasClass 'disabled' refreshPagination pagination.find('ul li.active').index() + 1 do refreshPagination pagination.show() else # Hide the pagination and remove all links as the results fit on a single page. pagination.hide().find('ul li').remove() # Update the state of the reset button depending on the current search input. refreshResetButton = -> log.trace() container = $ '#order_search' resetButton = container.find ':reset' if container.find(':text').val() container.addClass 'input-prepend' resetButton.show() else resetButton.hide() container.removeClass 'input-prepend' # Update the state of certain buttons depending on whether any select boxes have been checked. refreshSelectButtons = -> log.trace() selections = $ '#orders tbody :checkbox:checked' $('#delete_btn').prop 'disabled', selections.length is 0 # Reset the wizard field values based on the current context. resetWizard = -> log.trace() activeOrder ?= {} $('#order_wizard .modal-header h3').html if activeOrder.key? i18n.get 'opt_order_modify_title', activeOrder.label else i18n.get 'opt_order_new_header' # Assign values to their respective fields. $('#order_code').val activeOrder.code or '' $('#order_email').val activeOrder.email or '' $('#order_label').val activeOrder.label or '' $('#order_number').val activeOrder.number or '' $('#order_delete_btn').each -> $this = $ this if activeOrder.key? then $this.show() else $this.hide() # Search the orders for the specified `query` and filter those displayed. searchOrders = (query = '') -> log.trace() keywords = query.replace(R_CLEAN_QUERY, '').split R_WHITESPACE if keywords.length expression = /// #{(keyword for keyword in keywords when keyword).join '|'} ///i searchResults = ext.queryOrders (order) -> expression.test "#{order.code} #{order.email} #{order.label} #{order.number}" else searchResults = null loadOrderRows searchResults ? ext.orders do refreshResetButton do refreshSelectButtons # Set the current context of the order wizard. setContext = (order = {}) -> log.trace() activeOrder = {} $.extend activeOrder, order do resetWizard # Convenient shorthand for safely trimming a string to lower case. trimToLower = (str = '') -> str.trim().toLowerCase() # Convenient shorthand for safely trimming a string to upper case. trimToUpper = (str = '') -> str.trim().toUpperCase() # Options page setup # ------------------ options = window.options = new class Options extends utils.Class # Public functions # ---------------- # Initialize the options page. # This will involve inserting and configuring the UI elements as well as loading the current # settings. init: -> log.trace() log.info 'Initializing the options page' # Add support for analytics if the user hasn't opted out. analytics.add() if store.get 'analytics' # Add the user feedback feature to the page. do feedback # Begin initialization. i18n.init() $('.year-repl').html "#{new Date().getFullYear()}" # Bind tab selection event to all tabs. initialTabChange = yes $('a[tabify]').on 'click', -> target = $(this).attr 'tabify' nav = $ "#navigation a[tabify='#{target}']" parent = nav.parent 'li' unless parent.hasClass 'active' parent.siblings().removeClass 'active' parent.addClass 'active' $(target).show().siblings('.tab').hide() id = nav.attr 'id' store.set 'options_active_tab', id unless initialTabChange id = id.match(/(\S*)_nav$/)[1] id = id[0].toUpperCase() + id.substr 1 log.debug "Changing tab to #{id}" analytics.track 'Tabs', 'Changed', id initialTabChange = no $(document.body).scrollTop 0 # Reflect the persisted tab. store.init 'options_active_tab', 'general_nav' optionsActiveTab = store.get 'options_active_tab' $("##{optionsActiveTab}").trigger 'click' log.debug "Initially displaying tab for #{optionsActiveTab}" # Bind Developer Tools wizard events to their corresponding elements. $('#tools_nav').on 'click', -> $('#tools_wizard').modal 'show' $('.tools_close_btn').on 'click', -> $('#tools_wizard').modal 'hide' # Ensure that form submissions don't reload the page. $('form:not([target="_blank"])').on 'submit', -> no # Bind analytical tracking events to key footer buttons and links. $('footer a[href*="neocotic.com"]').on 'click', -> analytics.track 'Footer', 'Clicked', 'Homepage' # Setup and configure the donation button in the footer. $('#donation input[name="hosted_button_id"]').val ext.config.options.payPal $('#donation').on 'submit', -> analytics.track 'Footer', 'Clicked', 'Donate' # Load the current option values. do load # Initialize all popovers, tooltips and *go-to* links. $('[popover]').each -> $this = $ this placement = $this.attr 'data-placement' placement = if placement? then trimToLower placement else 'right' trigger = $this.attr 'data-trigger' trigger = if trigger? then trimToLower trigger else 'hover' $this.popover content: -> i18n.get $this.attr 'popover' html: yes placement: placement trigger: trigger if trigger is 'manual' $this.on 'click', -> $this.popover 'toggle' do activateTooltips navHeight = $('.navbar').height() $('[data-goto]').on 'click', -> goto = $ $(this).attr 'data-goto' pos = goto.position()?.top or 0 pos -= navHeight if pos and pos >= navHeight log.debug "Relocating view to include '#{goto.selector}' at #{pos}" $(window).scrollTop pos # Ensure that the persisted tab is currently visible. # This should be called if the user clicks the Options link in the popup while and options page # is already open. refresh: -> $("##{store.get 'options_active_tab'}").trigger 'click' # Initialize `options` when the DOM is ready. utils.ready -> options.init()
[ { "context": "y(events, (event) ->\n currentKey = utils.date.getKey(@currentDate)\n eventKey = utils.date.getKey(", "end": 715, "score": 0.6337714195251465, "start": 709, "tag": "KEY", "value": "getKey" }, { "context": " _.each(events, (event) =>\n key = utils.date.get...
src/events.coffee
ivanbokii/TinyEvents
0
templates = $.fn.tinyEventsModules.templates utils = $.fn.tinyEventsModules.utils class Events animationSpeed = 200 constructor: (@element, @events, @handlers) -> @template = _.template(templates.events) @_groupEvents() @_initHandlers() @_subsribeToEvents() #---public api---------------------------------------------------------------- getDateEvents: (date) -> @_findDateEvents(date) getAllEvents: -> @groupedEvents addEvents: (events) -> @events = @events.concat(events) @_groupEvents() #check whether event is for the current date and if yes - rerender events #panel shouldRender = not _.every(events, (event) -> currentKey = utils.date.getKey(@currentDate) eventKey = utils.date.getKey(event.time) currentKey isnt eventKey ) @_render(@_findDateEvents(@currentDate)) if shouldRender @handlers.run('onEventsAdd', events) removeEvents: (events) -> shouldRemove = false _.each(events, (event) => key = utils.date.getKey(new Date(event.time)) if _.isUndefined(@groupedEvents[key]) and not _.contains(@groupedEvents[key], event) then return @groupedEvents[key] = _.without(@groupedEvents[key], event) shouldRemove = true ) if shouldRemove @_render(@_findDateEvents(@currentDate)) @handlers.run('onEventsRemove', events) resetEvents: (events) -> @events = events @_groupEvents() @_render(@events) #----------------------------------------------------------------------------- #---events handlers---------------- _findDateEvents: (date) -> key = utils.date.getKey(date) @groupedEvents[key] _initHandlers: -> @element.on('click', '.events .has-description .event-control', @._expandDescription) _subsribeToEvents: -> @handlers.add('onDateChange', @_onDateChange) _onDateChange: (newDate) => @currentDate = newDate dateEvents = @_findDateEvents(newDate) @_render(dateEvents) @currentDate = newDate #---------------------------------- _groupEvents: -> @groupedEvents = _.chain(@events) .map((e) -> time = new Date(e.time) e.day = time.getDate() e.month = time.getMonth() e.year = time.getFullYear() e) .groupBy((e) -> "#{e.day}/#{e.month}/#{e.year}") .value() _render: (events) -> sortedEvents = _.sortBy(events, (e) -> e.time) #add zero to the beginning because otherwise 00 would be 0 hours = (e) -> tmp = (new Date(e.time)).getHours() if tmp < 10 then "0" + tmp.toString() else tmp #add zero to the beginning because otherwise 00 would be 0 minutes = (e) -> tmp = (new Date(e.time)).getMinutes() if tmp < 10 then "0" + tmp.toString() else tmp _.each(events, (e) -> e.formattedTime = "#{hours(e)}:#{minutes(e)}"); renderedTemplate = @template( events: sortedEvents ) $('.tiny-events .events').empty() renderedTemplate = $(renderedTemplate).hide() $('.tiny-events .events').append(renderedTemplate) $(renderedTemplate).fadeIn(animationSpeed) $('.events div').last().addClass('last') _expandDescription: -> eventControl = $(@).parent().find('.event-control') if eventControl.hasClass('expand') eventControl.hide(); eventControl.removeClass('expand').addClass('collapse') eventControl.attr('src', 'images/collapse.png') eventControl.fadeIn(200); else eventControl.hide(); eventControl.removeClass('collapse').addClass('expand') eventControl.attr('src', 'images/expand.png') eventControl.fadeIn(200); $(@).parent().find('.description').animate( height: 'toggle' opacity: 'toggle', animationSpeed) $.fn.tinyEventsModules.Events = Events
127282
templates = $.fn.tinyEventsModules.templates utils = $.fn.tinyEventsModules.utils class Events animationSpeed = 200 constructor: (@element, @events, @handlers) -> @template = _.template(templates.events) @_groupEvents() @_initHandlers() @_subsribeToEvents() #---public api---------------------------------------------------------------- getDateEvents: (date) -> @_findDateEvents(date) getAllEvents: -> @groupedEvents addEvents: (events) -> @events = @events.concat(events) @_groupEvents() #check whether event is for the current date and if yes - rerender events #panel shouldRender = not _.every(events, (event) -> currentKey = utils.date.<KEY>(@currentDate) eventKey = utils.date.getKey(event.time) currentKey isnt eventKey ) @_render(@_findDateEvents(@currentDate)) if shouldRender @handlers.run('onEventsAdd', events) removeEvents: (events) -> shouldRemove = false _.each(events, (event) => key = utils.date.<KEY>(new Date(event.time)) if _.isUndefined(@groupedEvents[key]) and not _.contains(@groupedEvents[key], event) then return @groupedEvents[key] = _.without(@groupedEvents[key], event) shouldRemove = true ) if shouldRemove @_render(@_findDateEvents(@currentDate)) @handlers.run('onEventsRemove', events) resetEvents: (events) -> @events = events @_groupEvents() @_render(@events) #----------------------------------------------------------------------------- #---events handlers---------------- _findDateEvents: (date) -> key = utils.date.getKey(date) @groupedEvents[key] _initHandlers: -> @element.on('click', '.events .has-description .event-control', @._expandDescription) _subsribeToEvents: -> @handlers.add('onDateChange', @_onDateChange) _onDateChange: (newDate) => @currentDate = newDate dateEvents = @_findDateEvents(newDate) @_render(dateEvents) @currentDate = newDate #---------------------------------- _groupEvents: -> @groupedEvents = _.chain(@events) .map((e) -> time = new Date(e.time) e.day = time.getDate() e.month = time.getMonth() e.year = time.getFullYear() e) .groupBy((e) -> "#{e.day}/#{e.month}/#{e.year}") .value() _render: (events) -> sortedEvents = _.sortBy(events, (e) -> e.time) #add zero to the beginning because otherwise 00 would be 0 hours = (e) -> tmp = (new Date(e.time)).getHours() if tmp < 10 then "0" + tmp.toString() else tmp #add zero to the beginning because otherwise 00 would be 0 minutes = (e) -> tmp = (new Date(e.time)).getMinutes() if tmp < 10 then "0" + tmp.toString() else tmp _.each(events, (e) -> e.formattedTime = "#{hours(e)}:#{minutes(e)}"); renderedTemplate = @template( events: sortedEvents ) $('.tiny-events .events').empty() renderedTemplate = $(renderedTemplate).hide() $('.tiny-events .events').append(renderedTemplate) $(renderedTemplate).fadeIn(animationSpeed) $('.events div').last().addClass('last') _expandDescription: -> eventControl = $(@).parent().find('.event-control') if eventControl.hasClass('expand') eventControl.hide(); eventControl.removeClass('expand').addClass('collapse') eventControl.attr('src', 'images/collapse.png') eventControl.fadeIn(200); else eventControl.hide(); eventControl.removeClass('collapse').addClass('expand') eventControl.attr('src', 'images/expand.png') eventControl.fadeIn(200); $(@).parent().find('.description').animate( height: 'toggle' opacity: 'toggle', animationSpeed) $.fn.tinyEventsModules.Events = Events
true
templates = $.fn.tinyEventsModules.templates utils = $.fn.tinyEventsModules.utils class Events animationSpeed = 200 constructor: (@element, @events, @handlers) -> @template = _.template(templates.events) @_groupEvents() @_initHandlers() @_subsribeToEvents() #---public api---------------------------------------------------------------- getDateEvents: (date) -> @_findDateEvents(date) getAllEvents: -> @groupedEvents addEvents: (events) -> @events = @events.concat(events) @_groupEvents() #check whether event is for the current date and if yes - rerender events #panel shouldRender = not _.every(events, (event) -> currentKey = utils.date.PI:KEY:<KEY>END_PI(@currentDate) eventKey = utils.date.getKey(event.time) currentKey isnt eventKey ) @_render(@_findDateEvents(@currentDate)) if shouldRender @handlers.run('onEventsAdd', events) removeEvents: (events) -> shouldRemove = false _.each(events, (event) => key = utils.date.PI:KEY:<KEY>END_PI(new Date(event.time)) if _.isUndefined(@groupedEvents[key]) and not _.contains(@groupedEvents[key], event) then return @groupedEvents[key] = _.without(@groupedEvents[key], event) shouldRemove = true ) if shouldRemove @_render(@_findDateEvents(@currentDate)) @handlers.run('onEventsRemove', events) resetEvents: (events) -> @events = events @_groupEvents() @_render(@events) #----------------------------------------------------------------------------- #---events handlers---------------- _findDateEvents: (date) -> key = utils.date.getKey(date) @groupedEvents[key] _initHandlers: -> @element.on('click', '.events .has-description .event-control', @._expandDescription) _subsribeToEvents: -> @handlers.add('onDateChange', @_onDateChange) _onDateChange: (newDate) => @currentDate = newDate dateEvents = @_findDateEvents(newDate) @_render(dateEvents) @currentDate = newDate #---------------------------------- _groupEvents: -> @groupedEvents = _.chain(@events) .map((e) -> time = new Date(e.time) e.day = time.getDate() e.month = time.getMonth() e.year = time.getFullYear() e) .groupBy((e) -> "#{e.day}/#{e.month}/#{e.year}") .value() _render: (events) -> sortedEvents = _.sortBy(events, (e) -> e.time) #add zero to the beginning because otherwise 00 would be 0 hours = (e) -> tmp = (new Date(e.time)).getHours() if tmp < 10 then "0" + tmp.toString() else tmp #add zero to the beginning because otherwise 00 would be 0 minutes = (e) -> tmp = (new Date(e.time)).getMinutes() if tmp < 10 then "0" + tmp.toString() else tmp _.each(events, (e) -> e.formattedTime = "#{hours(e)}:#{minutes(e)}"); renderedTemplate = @template( events: sortedEvents ) $('.tiny-events .events').empty() renderedTemplate = $(renderedTemplate).hide() $('.tiny-events .events').append(renderedTemplate) $(renderedTemplate).fadeIn(animationSpeed) $('.events div').last().addClass('last') _expandDescription: -> eventControl = $(@).parent().find('.event-control') if eventControl.hasClass('expand') eventControl.hide(); eventControl.removeClass('expand').addClass('collapse') eventControl.attr('src', 'images/collapse.png') eventControl.fadeIn(200); else eventControl.hide(); eventControl.removeClass('collapse').addClass('expand') eventControl.attr('src', 'images/expand.png') eventControl.fadeIn(200); $(@).parent().find('.description').animate( height: 'toggle' opacity: 'toggle', animationSpeed) $.fn.tinyEventsModules.Events = Events
[ { "context": "# Copyright 2015 SASAKI, Shunsuke. All rights reserved.\n#\n# Licensed under", "end": 23, "score": 0.9534600377082825, "start": 17, "tag": "NAME", "value": "SASAKI" }, { "context": "# Copyright 2015 SASAKI, Shunsuke. All rights reserved.\n#\n# Licensed under the Apac", ...
src/raw_driver.coffee
erukiti/cerebrums
7
# Copyright 2015 SASAKI, Shunsuke. All rights reserved. # # 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. Rx = require 'rx' class RawDriver constructor: (rxfs, conf) -> @rxfs = rxfs @conf = conf writeTemp: (filename, file) => path = "#{@conf.basePath}/temp/#{filename}" # console.dir "writeTemp: #{path}" @rxfs.writeFile(path, file) writeBlob: (hash, file) => path = "#{@conf.basePath}/blob/#{hash}" # console.log "writeBlob: #{path}" @rxfs.writeFile(path, file) writePointer: (uuid, file) => path = "#{@conf.basePath}/pointer/#{uuid}" # console.log "writePointer: #{path}" @rxfs.writeFile(path, file) readTemp: (filename) => path = "#{@conf.basePath}/temp/#{filename}" @rxfs.readFile(path) readBlob: (hash) => path = "#{@conf.basePath}/blob/#{hash}" # console.log "readBlob: #{path}" @rxfs.readFile(path) readPointer: (uuid) => path = "#{@conf.basePath}/pointer/#{uuid}" # console.log "readPointer: #{path}" @rxfs.readFile(path) getAllPointer: => Rx.Observable.create (obs) => @rxfs.readDir("#{@conf.basePath}/pointer").subscribe((dirs) => for dir in dirs obs.onNext(dir.substr("#{@conf.basePath}/pointer/".length)) obs.onCompleted() , (err) => if err.code == 'ENOENT' obs.onCompleted() else obs.onError(err) ) module.exports = RawDriver
30750
# Copyright 2015 <NAME>, <NAME>. All rights reserved. # # 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. Rx = require 'rx' class RawDriver constructor: (rxfs, conf) -> @rxfs = rxfs @conf = conf writeTemp: (filename, file) => path = "#{@conf.basePath}/temp/#{filename}" # console.dir "writeTemp: #{path}" @rxfs.writeFile(path, file) writeBlob: (hash, file) => path = "#{@conf.basePath}/blob/#{hash}" # console.log "writeBlob: #{path}" @rxfs.writeFile(path, file) writePointer: (uuid, file) => path = "#{@conf.basePath}/pointer/#{uuid}" # console.log "writePointer: #{path}" @rxfs.writeFile(path, file) readTemp: (filename) => path = "#{@conf.basePath}/temp/#{filename}" @rxfs.readFile(path) readBlob: (hash) => path = "#{@conf.basePath}/blob/#{hash}" # console.log "readBlob: #{path}" @rxfs.readFile(path) readPointer: (uuid) => path = "#{@conf.basePath}/pointer/#{uuid}" # console.log "readPointer: #{path}" @rxfs.readFile(path) getAllPointer: => Rx.Observable.create (obs) => @rxfs.readDir("#{@conf.basePath}/pointer").subscribe((dirs) => for dir in dirs obs.onNext(dir.substr("#{@conf.basePath}/pointer/".length)) obs.onCompleted() , (err) => if err.code == 'ENOENT' obs.onCompleted() else obs.onError(err) ) module.exports = RawDriver
true
# Copyright 2015 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI. All rights reserved. # # 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. Rx = require 'rx' class RawDriver constructor: (rxfs, conf) -> @rxfs = rxfs @conf = conf writeTemp: (filename, file) => path = "#{@conf.basePath}/temp/#{filename}" # console.dir "writeTemp: #{path}" @rxfs.writeFile(path, file) writeBlob: (hash, file) => path = "#{@conf.basePath}/blob/#{hash}" # console.log "writeBlob: #{path}" @rxfs.writeFile(path, file) writePointer: (uuid, file) => path = "#{@conf.basePath}/pointer/#{uuid}" # console.log "writePointer: #{path}" @rxfs.writeFile(path, file) readTemp: (filename) => path = "#{@conf.basePath}/temp/#{filename}" @rxfs.readFile(path) readBlob: (hash) => path = "#{@conf.basePath}/blob/#{hash}" # console.log "readBlob: #{path}" @rxfs.readFile(path) readPointer: (uuid) => path = "#{@conf.basePath}/pointer/#{uuid}" # console.log "readPointer: #{path}" @rxfs.readFile(path) getAllPointer: => Rx.Observable.create (obs) => @rxfs.readDir("#{@conf.basePath}/pointer").subscribe((dirs) => for dir in dirs obs.onNext(dir.substr("#{@conf.basePath}/pointer/".length)) obs.onCompleted() , (err) => if err.code == 'ENOENT' obs.onCompleted() else obs.onError(err) ) module.exports = RawDriver
[ { "context": "###\n# @module : shopping\n# @author : Manuel Del Pozo\n# @description : This module implement a slider o", "end": 53, "score": 0.9998923540115356, "start": 38, "tag": "NAME", "value": "Manuel Del Pozo" } ]
frontend/frontend/resources/coffee/modules/all/shopping.coffee
ronnyfly2/delicores
0
### # @module : shopping # @author : Manuel Del Pozo # @description : This module implement a slider of the User's shopping list ### define ['libUnderscore', 'initBxSlider'], (underscore, bxSliderObject) -> 'user strict' slide = undefined st = ticketsItems: '.Tickets-items' ticketsDetail: '.Tickets-detail' tplTicketsDetail: '.tplTicketsDetail' tplTicket: '.tplTicket' inpSearch: '.Tickets-search-box' resultSearch: '.resultSearch' cleanerSearch: '.Tickets-search-cleaner' dom = {} type = 'selected' start = false resetStyles = () -> $items = dom.ticketsDetail.find('.Slider-item') maxHeight = 0 [].forEach.call $items, (item) -> height = $(item).height() if ( maxHeight < height ) maxHeight = height return $items.height maxHeight return catchDom = (st) -> Object.keys(st).forEach (item, idx, obj) -> dom[item] = $ st[item] return return renderTickets = (data) -> html = _.template(dom.tplTicketsDetail.html())( items: data ) ticketsHTML = _.template(dom.tplTicket.html())( tickets: data ) dom.ticketsDetail.html(html) dom.ticketsItems.html(ticketsHTML) afterCatchDom() dom.tickets.eq(0) .addClass type slide = bxSliderObject.init $('.bxslider'), 'controls': data.length > 1 ? true : false 'infiniteLoop': true 'mode': 'horizontal' 'adaptiveHeight': true 'pager': false 'touchEnabled': true 'prevSelector': $ '.Slider-arrow-left span' 'nextSelector': $ '.Slider-arrow-right span' 'onSlideBefore': (obj, old, current) -> dom.tickets.removeClass(type) dom.tickets.eq(current).addClass(type) return 'onSliderLoad': () -> resetStyles() return dom.tickets.on 'click', events.selectTicket return afterCatchDom = () -> dom.tickets = $ '.Ticket' return suscribeEvents = ()-> dom.inpSearch.on 'keyup', _.debounce(events.searchTicket, 600) dom.cleanerSearch.on 'click', events.cleanerSearch return events = cleanerSearch: (e) -> dom.inpSearch.val('').trigger('keyup') $( this ).hide() return selectTicket: (e) -> slide.goToSlide parseInt $( this ).data('index'), 10 return searchTicket: (e) -> el = $ this searchText = el.val() .toLowerCase() .trim() len = searchText.length dom.resultSearch.hide() if len > 2 options = listDetail.filter (item, idx, obj) -> if item.infoCine.name_movie isnt null title = item.infoCine.name_movie.toLowerCase() return title.indexOf(searchText) isnt -1 else return false if options.length renderTickets(options) else renderTickets(options) dom.ticketsItems.html('<div class="Ticket selected"></div><div class="Ticket">no se encontraron tickets con '+searchText+'</div>') dom.cleanerSearch.show() else dom.cleanerSearch.hide() renderTickets(listDetail) return catchDom(st) renderTickets(listDetail) suscribeEvents() return
120113
### # @module : shopping # @author : <NAME> # @description : This module implement a slider of the User's shopping list ### define ['libUnderscore', 'initBxSlider'], (underscore, bxSliderObject) -> 'user strict' slide = undefined st = ticketsItems: '.Tickets-items' ticketsDetail: '.Tickets-detail' tplTicketsDetail: '.tplTicketsDetail' tplTicket: '.tplTicket' inpSearch: '.Tickets-search-box' resultSearch: '.resultSearch' cleanerSearch: '.Tickets-search-cleaner' dom = {} type = 'selected' start = false resetStyles = () -> $items = dom.ticketsDetail.find('.Slider-item') maxHeight = 0 [].forEach.call $items, (item) -> height = $(item).height() if ( maxHeight < height ) maxHeight = height return $items.height maxHeight return catchDom = (st) -> Object.keys(st).forEach (item, idx, obj) -> dom[item] = $ st[item] return return renderTickets = (data) -> html = _.template(dom.tplTicketsDetail.html())( items: data ) ticketsHTML = _.template(dom.tplTicket.html())( tickets: data ) dom.ticketsDetail.html(html) dom.ticketsItems.html(ticketsHTML) afterCatchDom() dom.tickets.eq(0) .addClass type slide = bxSliderObject.init $('.bxslider'), 'controls': data.length > 1 ? true : false 'infiniteLoop': true 'mode': 'horizontal' 'adaptiveHeight': true 'pager': false 'touchEnabled': true 'prevSelector': $ '.Slider-arrow-left span' 'nextSelector': $ '.Slider-arrow-right span' 'onSlideBefore': (obj, old, current) -> dom.tickets.removeClass(type) dom.tickets.eq(current).addClass(type) return 'onSliderLoad': () -> resetStyles() return dom.tickets.on 'click', events.selectTicket return afterCatchDom = () -> dom.tickets = $ '.Ticket' return suscribeEvents = ()-> dom.inpSearch.on 'keyup', _.debounce(events.searchTicket, 600) dom.cleanerSearch.on 'click', events.cleanerSearch return events = cleanerSearch: (e) -> dom.inpSearch.val('').trigger('keyup') $( this ).hide() return selectTicket: (e) -> slide.goToSlide parseInt $( this ).data('index'), 10 return searchTicket: (e) -> el = $ this searchText = el.val() .toLowerCase() .trim() len = searchText.length dom.resultSearch.hide() if len > 2 options = listDetail.filter (item, idx, obj) -> if item.infoCine.name_movie isnt null title = item.infoCine.name_movie.toLowerCase() return title.indexOf(searchText) isnt -1 else return false if options.length renderTickets(options) else renderTickets(options) dom.ticketsItems.html('<div class="Ticket selected"></div><div class="Ticket">no se encontraron tickets con '+searchText+'</div>') dom.cleanerSearch.show() else dom.cleanerSearch.hide() renderTickets(listDetail) return catchDom(st) renderTickets(listDetail) suscribeEvents() return
true
### # @module : shopping # @author : PI:NAME:<NAME>END_PI # @description : This module implement a slider of the User's shopping list ### define ['libUnderscore', 'initBxSlider'], (underscore, bxSliderObject) -> 'user strict' slide = undefined st = ticketsItems: '.Tickets-items' ticketsDetail: '.Tickets-detail' tplTicketsDetail: '.tplTicketsDetail' tplTicket: '.tplTicket' inpSearch: '.Tickets-search-box' resultSearch: '.resultSearch' cleanerSearch: '.Tickets-search-cleaner' dom = {} type = 'selected' start = false resetStyles = () -> $items = dom.ticketsDetail.find('.Slider-item') maxHeight = 0 [].forEach.call $items, (item) -> height = $(item).height() if ( maxHeight < height ) maxHeight = height return $items.height maxHeight return catchDom = (st) -> Object.keys(st).forEach (item, idx, obj) -> dom[item] = $ st[item] return return renderTickets = (data) -> html = _.template(dom.tplTicketsDetail.html())( items: data ) ticketsHTML = _.template(dom.tplTicket.html())( tickets: data ) dom.ticketsDetail.html(html) dom.ticketsItems.html(ticketsHTML) afterCatchDom() dom.tickets.eq(0) .addClass type slide = bxSliderObject.init $('.bxslider'), 'controls': data.length > 1 ? true : false 'infiniteLoop': true 'mode': 'horizontal' 'adaptiveHeight': true 'pager': false 'touchEnabled': true 'prevSelector': $ '.Slider-arrow-left span' 'nextSelector': $ '.Slider-arrow-right span' 'onSlideBefore': (obj, old, current) -> dom.tickets.removeClass(type) dom.tickets.eq(current).addClass(type) return 'onSliderLoad': () -> resetStyles() return dom.tickets.on 'click', events.selectTicket return afterCatchDom = () -> dom.tickets = $ '.Ticket' return suscribeEvents = ()-> dom.inpSearch.on 'keyup', _.debounce(events.searchTicket, 600) dom.cleanerSearch.on 'click', events.cleanerSearch return events = cleanerSearch: (e) -> dom.inpSearch.val('').trigger('keyup') $( this ).hide() return selectTicket: (e) -> slide.goToSlide parseInt $( this ).data('index'), 10 return searchTicket: (e) -> el = $ this searchText = el.val() .toLowerCase() .trim() len = searchText.length dom.resultSearch.hide() if len > 2 options = listDetail.filter (item, idx, obj) -> if item.infoCine.name_movie isnt null title = item.infoCine.name_movie.toLowerCase() return title.indexOf(searchText) isnt -1 else return false if options.length renderTickets(options) else renderTickets(options) dom.ticketsItems.html('<div class="Ticket selected"></div><div class="Ticket">no se encontraron tickets con '+searchText+'</div>') dom.cleanerSearch.show() else dom.cleanerSearch.hide() renderTickets(listDetail) return catchDom(st) renderTickets(listDetail) suscribeEvents() return
[ { "context": "$ ->\n # 2019-3-3,at Petit Paris.\n # change the mind at 2019-3-4.yao qu da zhen.\n", "end": 32, "score": 0.9997992515563965, "start": 21, "tag": "NAME", "value": "Petit Paris" } ]
coffees/old-mine-index.coffee
android1and1/tickets
0
$ -> # 2019-3-3,at Petit Paris. # change the mind at 2019-3-4.yao qu da zhen. ['#user-logout','#admin-logout'].forEach (ele)-> $(ele).on 'click',(e)-> url = ele.replace /#/,'/' .replace /\-/,'/' $.ajax url:url # in fact ,there is an error,not 'method',should be 'type' method:'PUT' # in fact ,there is an error,not 'responseType',should be 'dataType' responseType:'json' .done (json)-> #in fact,there is an error,when client's role not as it said(logout),ajax will not fail,but case the 'else' case if json.code is 0 alert json.status $(ele).parent().addClass 'disabled' else alert json.status + ' reason: ' + json.reason .fail (xhr,status,thrown)-> console.log status console.log thrown e.preventDefault() e.stopPropagation()
93241
$ -> # 2019-3-3,at <NAME>. # change the mind at 2019-3-4.yao qu da zhen. ['#user-logout','#admin-logout'].forEach (ele)-> $(ele).on 'click',(e)-> url = ele.replace /#/,'/' .replace /\-/,'/' $.ajax url:url # in fact ,there is an error,not 'method',should be 'type' method:'PUT' # in fact ,there is an error,not 'responseType',should be 'dataType' responseType:'json' .done (json)-> #in fact,there is an error,when client's role not as it said(logout),ajax will not fail,but case the 'else' case if json.code is 0 alert json.status $(ele).parent().addClass 'disabled' else alert json.status + ' reason: ' + json.reason .fail (xhr,status,thrown)-> console.log status console.log thrown e.preventDefault() e.stopPropagation()
true
$ -> # 2019-3-3,at PI:NAME:<NAME>END_PI. # change the mind at 2019-3-4.yao qu da zhen. ['#user-logout','#admin-logout'].forEach (ele)-> $(ele).on 'click',(e)-> url = ele.replace /#/,'/' .replace /\-/,'/' $.ajax url:url # in fact ,there is an error,not 'method',should be 'type' method:'PUT' # in fact ,there is an error,not 'responseType',should be 'dataType' responseType:'json' .done (json)-> #in fact,there is an error,when client's role not as it said(logout),ajax will not fail,but case the 'else' case if json.code is 0 alert json.status $(ele).parent().addClass 'disabled' else alert json.status + ' reason: ' + json.reason .fail (xhr,status,thrown)-> console.log status console.log thrown e.preventDefault() e.stopPropagation()
[ { "context": "Mocha-cakes Reference ========\nhttps://github.com/quangv/mocha-cakes\nhttps://github.com/visionmedia/should", "end": 153, "score": 0.999700129032135, "start": 147, "tag": "USERNAME", "value": "quangv" }, { "context": "/github.com/quangv/mocha-cakes\nhttps://github.com/...
src/test/clock_spec.coffee
NicMcPhee/whooping-crane-model
0
'use strict' require 'mocha-cakes' Clock = require '../lib/clock' ### ======== A Handy Little Mocha-cakes Reference ======== https://github.com/quangv/mocha-cakes https://github.com/visionmedia/should.js https://github.com/visionmedia/mocha Mocha-cakes: Feature, Scenario: maps to describe Given, When, Then: maps to it, but if first message argument is ommited, it'll be a describe And, But, I: maps to it, but if first message argument is ommited, it'll be a describe Mocha hooks: before ()-> # before describe after ()-> # after describe beforeEach ()-> # before each it afterEach ()-> # after each it Should assertions: should.exist('hello') should.fail('expected an error!') true.should.be.ok true.should.be.true false.should.be.false (()-> arguments)(1,2,3).should.be.arguments [1,2,3].should.eql([1,2,3]) should.strictEqual(undefined, value) user.age.should.be.within(5, 50) username.should.match(/^\w+$/) user.should.be.a('object') [].should.be.an.instanceOf(Array) user.should.have.property('age', 15) user.age.should.be.above(5) user.age.should.be.below(100) user.pets.should.have.length(5) res.should.have.status(200) #res.statusCode should be 200 res.should.be.json res.should.be.html res.should.have.header('Content-Length', '123') [].should.be.empty [1,2,3].should.include(3) 'foo bar baz'.should.include('foo') { name: 'TJ', pet: tobi }.user.should.include({ pet: tobi, name: 'TJ' }) { foo: 'bar', baz: 'raz' }.should.have.keys('foo', 'bar') (()-> throw new Error('failed to baz')).should.throwError(/^fail.+/) user.should.have.property('pets').with.lengthOf(4) user.should.be.a('object').and.have.property('name', 'tj') ### Feature "Global clock resets", "In order to be able to track bird ages", "as a modeler", "I need a shared clock that I can reset", -> Scenario "Global clock is zero after a reset", -> Given "I reset the global clock", -> Clock.reset() Then "the current year is 0", -> Clock.currentYear.should.eql 0 Scenario "Global clock increments correctly", -> Given "I reset the global clock", -> Clock.reset() When "I increment the clock once", -> Clock.incrementYear() Then "The current year is 1", -> Clock.currentYear.should.eql 1
3346
'use strict' require 'mocha-cakes' Clock = require '../lib/clock' ### ======== A Handy Little Mocha-cakes Reference ======== https://github.com/quangv/mocha-cakes https://github.com/visionmedia/should.js https://github.com/visionmedia/mocha Mocha-cakes: Feature, Scenario: maps to describe Given, When, Then: maps to it, but if first message argument is ommited, it'll be a describe And, But, I: maps to it, but if first message argument is ommited, it'll be a describe Mocha hooks: before ()-> # before describe after ()-> # after describe beforeEach ()-> # before each it afterEach ()-> # after each it Should assertions: should.exist('hello') should.fail('expected an error!') true.should.be.ok true.should.be.true false.should.be.false (()-> arguments)(1,2,3).should.be.arguments [1,2,3].should.eql([1,2,3]) should.strictEqual(undefined, value) user.age.should.be.within(5, 50) username.should.match(/^\w+$/) user.should.be.a('object') [].should.be.an.instanceOf(Array) user.should.have.property('age', 15) user.age.should.be.above(5) user.age.should.be.below(100) user.pets.should.have.length(5) res.should.have.status(200) #res.statusCode should be 200 res.should.be.json res.should.be.html res.should.have.header('Content-Length', '123') [].should.be.empty [1,2,3].should.include(3) 'foo bar baz'.should.include('foo') { name: '<NAME>', pet: tobi }.user.should.include({ pet: tobi, name: 'TJ' }) { foo: 'bar', baz: 'raz' }.should.have.keys('foo', 'bar') (()-> throw new Error('failed to baz')).should.throwError(/^fail.+/) user.should.have.property('pets').with.lengthOf(4) user.should.be.a('object').and.have.property('name', '<NAME>') ### Feature "Global clock resets", "In order to be able to track bird ages", "as a modeler", "I need a shared clock that I can reset", -> Scenario "Global clock is zero after a reset", -> Given "I reset the global clock", -> Clock.reset() Then "the current year is 0", -> Clock.currentYear.should.eql 0 Scenario "Global clock increments correctly", -> Given "I reset the global clock", -> Clock.reset() When "I increment the clock once", -> Clock.incrementYear() Then "The current year is 1", -> Clock.currentYear.should.eql 1
true
'use strict' require 'mocha-cakes' Clock = require '../lib/clock' ### ======== A Handy Little Mocha-cakes Reference ======== https://github.com/quangv/mocha-cakes https://github.com/visionmedia/should.js https://github.com/visionmedia/mocha Mocha-cakes: Feature, Scenario: maps to describe Given, When, Then: maps to it, but if first message argument is ommited, it'll be a describe And, But, I: maps to it, but if first message argument is ommited, it'll be a describe Mocha hooks: before ()-> # before describe after ()-> # after describe beforeEach ()-> # before each it afterEach ()-> # after each it Should assertions: should.exist('hello') should.fail('expected an error!') true.should.be.ok true.should.be.true false.should.be.false (()-> arguments)(1,2,3).should.be.arguments [1,2,3].should.eql([1,2,3]) should.strictEqual(undefined, value) user.age.should.be.within(5, 50) username.should.match(/^\w+$/) user.should.be.a('object') [].should.be.an.instanceOf(Array) user.should.have.property('age', 15) user.age.should.be.above(5) user.age.should.be.below(100) user.pets.should.have.length(5) res.should.have.status(200) #res.statusCode should be 200 res.should.be.json res.should.be.html res.should.have.header('Content-Length', '123') [].should.be.empty [1,2,3].should.include(3) 'foo bar baz'.should.include('foo') { name: 'PI:NAME:<NAME>END_PI', pet: tobi }.user.should.include({ pet: tobi, name: 'TJ' }) { foo: 'bar', baz: 'raz' }.should.have.keys('foo', 'bar') (()-> throw new Error('failed to baz')).should.throwError(/^fail.+/) user.should.have.property('pets').with.lengthOf(4) user.should.be.a('object').and.have.property('name', 'PI:NAME:<NAME>END_PI') ### Feature "Global clock resets", "In order to be able to track bird ages", "as a modeler", "I need a shared clock that I can reset", -> Scenario "Global clock is zero after a reset", -> Given "I reset the global clock", -> Clock.reset() Then "the current year is 0", -> Clock.currentYear.should.eql 0 Scenario "Global clock increments correctly", -> Given "I reset the global clock", -> Clock.reset() When "I increment the clock once", -> Clock.incrementYear() Then "The current year is 1", -> Clock.currentYear.should.eql 1
[ { "context": "###\n# Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n#", "end": 21, "score": 0.9955976009368896, "start": 14, "tag": "USERNAME", "value": "iTonyYo" }, { "context": "###\n# Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n# Last Update ...
node_modules/node-find-folder/dev/node.find.folder.coffee
long-grass/mikey
0
### # Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo) ### 'use strict' _options = undefined fs = require 'fs' glob = require 'glob' lodash = require 'lodash' isFile = require 'is-file' isDir = require 'is-directory' # @name _default # @description Default options. # @type # {object} _default # {array} _default.nottraversal # {array} _default.ignore # @author 沈维忠 ( Tony Stark / Shen Weizhong ) _default = nottraversal: ['.git', 'node_modules'] ignore: [] # @function convertTo_Obj # @description Convert given string or array to a brace like object. # @param {(string|string[])} filter - a string or an array data that need to be converted to brace like object # @returns {object} # @author 沈维忠 ( Tony Stark / Shen Weizhong ) convertTo_Obj = (filter) -> obj = {} if lodash.isArray filter lodash.forEach filter, (_item, _index, _array) -> obj[_item] = _index else if lodash.isString filter obj[filter] = 0 obj # @function _filter # @description Filter some unwanted elements from an array. # @param {array} arr - data need to be converted # @param {(string|string[])} filter - a string or an array data for filter condition # @returns {array} # @author 沈维忠 ( Tony Stark / Shen Weizhong ) _filter = (arr, filter) -> exclude = (item) -> (item not of convertTo_Obj(filter)) lodash.filter arr, exclude # @function _readDirFolderCache # @description Get list of all folders which under some directory. # @returns {object} # @author 沈维忠 ( Tony Stark / Shen Weizhong ) _readDirFolderCache = (-> instance = undefined init = -> list = fs.readdirSync process.cwd() folders = [] _deal = (_item, _index, _array) -> if isDir.sync _item folders.push _item return lodash.forEach list, _deal return folders return { # @instance getInstance: -> if !instance instance = init() return instance } )() # @function traverse_scope # @description Get top-level directory needs to be traversed. # @returns {array} # @author 沈维忠 ( Tony Stark / Shen Weizhong ) traverse_scope = -> _filter _readDirFolderCache.getInstance(), _options.nottraversal # @function ignoreFilter # @description Filter result need to be ignored. # @returns {array} # @author 沈维忠 ( Tony Stark / Shen Weizhong ) ignoreFilter = -> _filter arguments[0], _options.ignore # @function ifExistInRoot # @description Determine whether there is any relevant folders under the specified directory. # @returns {boolean} # @author 沈维忠 ( Tony Stark / Shen Weizhong ) ifExistInRoot = -> lodash.includes traverse_scope(), arguments[0] # @function traversal_pattern # @description Matches zero or more directories and subdirectories searching for matches. # @param {string} target - name of folder # @returns {string} # @author 沈维忠 ( Tony Stark / Shen Weizhong ) traversal_pattern = (target) -> if ifExistInRoot target pattern = '+(' + _filter(traverse_scope(), target).join('|') + ')/**/' + target else pattern = '+(' + traverse_scope().join('|') + ')/**/' + target pattern # @function getFolders # @description # This is the main method.Use just the name of folder to find the folder(s), rather than # through given path(s) - To search the targeted directory(s) you want in the whole # project,return array type result. Then, you can do anything you want with the result! # For batch operations which according to the directory(s). # @param {string} target - name of folder # @param {object} options # @returns {array} # @author 沈维忠 ( Tony Stark / Shen Weizhong ) getFolders = -> target = arguments[0] option = arguments[1] if not lodash.isUndefined option if lodash.isPlainObject option _options = lodash.merge _default, option else _options = _default if lodash.isString(target) and not isFile(target) traversal_matched = glob.sync traversal_pattern target if ifExistInRoot target traversal_matched.push target return ignoreFilter traversal_matched # @class FF # @description # @param {string} target - name of folder # @param {object} options # @returns {array} # @author 沈维忠 ( Tony Stark / Shen Weizhong ) class FF # @constructs constructor: (@folderTarget, @searchOptions) -> return getFolders @folderTarget, @searchOptions # @module node-find-folder module.exports = FF
148910
### # Author: iTonyYo <<EMAIL>> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <<EMAIL>> (https://github.com/iTonyYo) ### 'use strict' _options = undefined fs = require 'fs' glob = require 'glob' lodash = require 'lodash' isFile = require 'is-file' isDir = require 'is-directory' # @name _default # @description Default options. # @type # {object} _default # {array} _default.nottraversal # {array} _default.ignore # @author <NAME> ( <NAME> / Sh<NAME> ) _default = nottraversal: ['.git', 'node_modules'] ignore: [] # @function convertTo_Obj # @description Convert given string or array to a brace like object. # @param {(string|string[])} filter - a string or an array data that need to be converted to brace like object # @returns {object} # @author <NAME> ( <NAME> / Sh<NAME>h<NAME> ) convertTo_Obj = (filter) -> obj = {} if lodash.isArray filter lodash.forEach filter, (_item, _index, _array) -> obj[_item] = _index else if lodash.isString filter obj[filter] = 0 obj # @function _filter # @description Filter some unwanted elements from an array. # @param {array} arr - data need to be converted # @param {(string|string[])} filter - a string or an array data for filter condition # @returns {array} # @author <NAME> ( <NAME> / <NAME> ) _filter = (arr, filter) -> exclude = (item) -> (item not of convertTo_Obj(filter)) lodash.filter arr, exclude # @function _readDirFolderCache # @description Get list of all folders which under some directory. # @returns {object} # @author <NAME> ( <NAME> / <NAME> ) _readDirFolderCache = (-> instance = undefined init = -> list = fs.readdirSync process.cwd() folders = [] _deal = (_item, _index, _array) -> if isDir.sync _item folders.push _item return lodash.forEach list, _deal return folders return { # @instance getInstance: -> if !instance instance = init() return instance } )() # @function traverse_scope # @description Get top-level directory needs to be traversed. # @returns {array} # @author <NAME> ( <NAME> / <NAME> ) traverse_scope = -> _filter _readDirFolderCache.getInstance(), _options.nottraversal # @function ignoreFilter # @description Filter result need to be ignored. # @returns {array} # @author <NAME> ( <NAME> / <NAME> ) ignoreFilter = -> _filter arguments[0], _options.ignore # @function ifExistInRoot # @description Determine whether there is any relevant folders under the specified directory. # @returns {boolean} # @author <NAME> ( <NAME> / <NAME> ) ifExistInRoot = -> lodash.includes traverse_scope(), arguments[0] # @function traversal_pattern # @description Matches zero or more directories and subdirectories searching for matches. # @param {string} target - name of folder # @returns {string} # @author <NAME> ( <NAME> / <NAME> ) traversal_pattern = (target) -> if ifExistInRoot target pattern = '+(' + _filter(traverse_scope(), target).join('|') + ')/**/' + target else pattern = '+(' + traverse_scope().join('|') + ')/**/' + target pattern # @function getFolders # @description # This is the main method.Use just the name of folder to find the folder(s), rather than # through given path(s) - To search the targeted directory(s) you want in the whole # project,return array type result. Then, you can do anything you want with the result! # For batch operations which according to the directory(s). # @param {string} target - name of folder # @param {object} options # @returns {array} # @author <NAME> ( <NAME> / <NAME> ) getFolders = -> target = arguments[0] option = arguments[1] if not lodash.isUndefined option if lodash.isPlainObject option _options = lodash.merge _default, option else _options = _default if lodash.isString(target) and not isFile(target) traversal_matched = glob.sync traversal_pattern target if ifExistInRoot target traversal_matched.push target return ignoreFilter traversal_matched # @class FF # @description # @param {string} target - name of folder # @param {object} options # @returns {array} # @author <NAME> ( <NAME> / <NAME> ) class FF # @constructs constructor: (@folderTarget, @searchOptions) -> return getFolders @folderTarget, @searchOptions # @module node-find-folder module.exports = FF
true
### # Author: iTonyYo <PI:EMAIL:<EMAIL>END_PI> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <PI:EMAIL:<EMAIL>END_PI> (https://github.com/iTonyYo) ### 'use strict' _options = undefined fs = require 'fs' glob = require 'glob' lodash = require 'lodash' isFile = require 'is-file' isDir = require 'is-directory' # @name _default # @description Default options. # @type # {object} _default # {array} _default.nottraversal # {array} _default.ignore # @author PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / ShPI:NAME:<NAME>END_PI ) _default = nottraversal: ['.git', 'node_modules'] ignore: [] # @function convertTo_Obj # @description Convert given string or array to a brace like object. # @param {(string|string[])} filter - a string or an array data that need to be converted to brace like object # @returns {object} # @author PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / ShPI:NAME:<NAME>END_PIhPI:NAME:<NAME>END_PI ) convertTo_Obj = (filter) -> obj = {} if lodash.isArray filter lodash.forEach filter, (_item, _index, _array) -> obj[_item] = _index else if lodash.isString filter obj[filter] = 0 obj # @function _filter # @description Filter some unwanted elements from an array. # @param {array} arr - data need to be converted # @param {(string|string[])} filter - a string or an array data for filter condition # @returns {array} # @author PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) _filter = (arr, filter) -> exclude = (item) -> (item not of convertTo_Obj(filter)) lodash.filter arr, exclude # @function _readDirFolderCache # @description Get list of all folders which under some directory. # @returns {object} # @author PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) _readDirFolderCache = (-> instance = undefined init = -> list = fs.readdirSync process.cwd() folders = [] _deal = (_item, _index, _array) -> if isDir.sync _item folders.push _item return lodash.forEach list, _deal return folders return { # @instance getInstance: -> if !instance instance = init() return instance } )() # @function traverse_scope # @description Get top-level directory needs to be traversed. # @returns {array} # @author PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) traverse_scope = -> _filter _readDirFolderCache.getInstance(), _options.nottraversal # @function ignoreFilter # @description Filter result need to be ignored. # @returns {array} # @author PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) ignoreFilter = -> _filter arguments[0], _options.ignore # @function ifExistInRoot # @description Determine whether there is any relevant folders under the specified directory. # @returns {boolean} # @author PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) ifExistInRoot = -> lodash.includes traverse_scope(), arguments[0] # @function traversal_pattern # @description Matches zero or more directories and subdirectories searching for matches. # @param {string} target - name of folder # @returns {string} # @author PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) traversal_pattern = (target) -> if ifExistInRoot target pattern = '+(' + _filter(traverse_scope(), target).join('|') + ')/**/' + target else pattern = '+(' + traverse_scope().join('|') + ')/**/' + target pattern # @function getFolders # @description # This is the main method.Use just the name of folder to find the folder(s), rather than # through given path(s) - To search the targeted directory(s) you want in the whole # project,return array type result. Then, you can do anything you want with the result! # For batch operations which according to the directory(s). # @param {string} target - name of folder # @param {object} options # @returns {array} # @author PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) getFolders = -> target = arguments[0] option = arguments[1] if not lodash.isUndefined option if lodash.isPlainObject option _options = lodash.merge _default, option else _options = _default if lodash.isString(target) and not isFile(target) traversal_matched = glob.sync traversal_pattern target if ifExistInRoot target traversal_matched.push target return ignoreFilter traversal_matched # @class FF # @description # @param {string} target - name of folder # @param {object} options # @returns {array} # @author PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) class FF # @constructs constructor: (@folderTarget, @searchOptions) -> return getFolders @folderTarget, @searchOptions # @module node-find-folder module.exports = FF
[ { "context": "ithMode = (mode) ->\n #require(\"../\").withApiKey \"abcdefghijklmnopqrstuvwxyz123457\", \"abcdefghijklmnopqrstuvwxyz123456\", mode\n#descr", "end": 119, "score": 0.9995661377906799, "start": 87, "tag": "KEY", "value": "abcdefghijklmnopqrstuvwxyz123457" }, { "context":...
test/test.coffee
buttercoin/buttercoinsdk-node
2
#should = require("should") #clientWithMode = (mode) -> #require("../").withApiKey "abcdefghijklmnopqrstuvwxyz123457", "abcdefghijklmnopqrstuvwxyz123456", mode #describe "Buttercoin", -> #buttercoin = undefined #api_key = undefined #api_secret = undefined #mode = undefined #version = undefined #describe "setup of client object", -> #beforeEach -> #api_key = "" #api_secret = "" #mode = "" #version = "" #return #it "should configure the client correctly on new object", -> #api_key = "abcdefghijklmnopqrstuvwxyz123456" #api_secret = "abcdefghijklmnopqrstuvwxyz123456" #mode = "production" #version = "v1" #buttercoin = require("../").withApiKey(api_key, api_secret, mode, version) #should.exist buttercoin #buttercoin.apiKey.should.equal api_key #buttercoin.apiSecret.should.equal api_secret #buttercoin.apiUrl.should.equal "https://api.buttercoin.com" #buttercoin.version.should.equal version #return #it "should throw an error if no api_key is present", -> #try #buttercoin = require("../").withApiKey() #catch error #should.exist error #error.message.should.equal "API Key parameter must be specified and be of length 32 characters" #return #it "should throw an error if api_key is incorrect length", -> #try #buttercoin = require("../").withApiKey("too_short") #catch error #should.exist error #error.message.should.equal "API Key parameter must be specified and be of length 32 characters" #return #it "should throw an error if no api_secret is present", -> #try #buttercoin = require("../").withApiKey("abcdefghijklmnopqrstuvwxyz123456") #catch error #should.exist error #error.message.should.equal "API Secret parameter must be specified and be of length 32 characters" #return #it "should throw an error if api_secret is incorrect length", -> #try #buttercoin = require("../").withApiKey("abcdefghijklmnopqrstuvwxyz123456", "too_short") #catch error #should.exist error #error.message.should.equal "API Secret parameter must be specified and be of length 32 characters" #return #it "should point to staging if mode is not production", -> #buttercoin = clientWithMode("staging") #buttercoin.apiUrl.should.equal "https://sandbox.buttercoin.com" #return #it "should allow for the specificatoin of a custom endpoint", -> #buttercoin = clientWithMode( #protocol: "http" #host: "localhost" #port: 1234 #headers: #"X-Forwarded-For": "127.0.0.1" #) #url = buttercoin.buildUrl("key") #timestamp = "1403558182457" #signature = buttercoin.signUrl(url, timestamp) #buttercoin.apiUrl.should.equal "http://localhost:1234" #headers = buttercoin.getHeaders(signature, timestamp) #headers["X-Forwarded-For"].should.equal "127.0.0.1" #return #it "should build a url correctly with the given endpoint, sign the url and build the headers", -> #buttercoin = clientWithMode("production") #url = buttercoin.buildUrl("key") #url.should.equal "https://api.buttercoin.com/v1/key" #timestamp = "1403558182457" #signature = buttercoin.signUrl(url, timestamp) #signature.should.equal "amakcIy40XLCUaSz6urhl+687F2pIexux+TJ2bl+66I=" #headers = buttercoin.getHeaders(signature, timestamp) #headers["X-Buttercoin-Access-Key"].should.equal "abcdefghijklmnopqrstuvwxyz123457" #headers["X-Buttercoin-Signature"].should.equal "amakcIy40XLCUaSz6urhl+687F2pIexux+TJ2bl+66I=" #headers["X-Buttercoin-Date"].should.equal "1403558182457" #return #it "should build the correct options headers based on get method type", -> #buttercoin = require("../").withApiKey("abcdefghijklmnopqrstuvwxyz123457", "abcdefghijklmnopqrstuvwxyz123456", "production") #method = "GET" #endpoint = "orders" #timestamp = "1403558182457" #body = testParam: "testVal" #options = buttercoin.buildRequest(method, endpoint, timestamp, body) #options.headers["X-Buttercoin-Access-Key"].should.equal "abcdefghijklmnopqrstuvwxyz123457" #options.headers["X-Buttercoin-Signature"].should.equal "M0cug9fN1vRh+eECgBz+bTRhu1u/A7Mgm5cpHPKwWIU=" #options.headers["X-Buttercoin-Date"].should.equal "1403558182457" #options.qs.should.equal body #options.json.should.equal true #return #it "should build the correct options headers based on post method type", -> #buttercoin = require("../").withApiKey("abcdefghijklmnopqrstuvwxyz123457", "abcdefghijklmnopqrstuvwxyz123456", "production") #method = "POST" #endpoint = "orders" #timestamp = "1403558182457" #body = testParam: "testVal" #options = buttercoin.buildRequest(method, endpoint, timestamp, body) #options.headers["X-Buttercoin-Access-Key"].should.equal "abcdefghijklmnopqrstuvwxyz123457" #options.headers["X-Buttercoin-Signature"].should.equal "KuGR55mSi+OiF6NOu7UG1lgVV7XTMc91IpUuCRdczr4=" #options.headers["X-Buttercoin-Date"].should.equal "1403558182457" #options.hasOwnProperty("qs").should.equal false #options.json.should.equal body #return #it "should build the correct options headers based on post method type", -> #buttercoin = require("../").withApiKey("abcdefghijklmnopqrstuvwxyz123457", "abcdefghijklmnopqrstuvwxyz123456", "production") #method = "DELETE" #endpoint = "orders/my_order_id" #timestamp = "1403558182457" #body = testParam: "testVal" #options = buttercoin.buildRequest(method, endpoint, timestamp, body) #options.headers["X-Buttercoin-Access-Key"].should.equal "abcdefghijklmnopqrstuvwxyz123457" #options.headers["X-Buttercoin-Signature"].should.equal "rI9nSlbev0b+wY+qge38n72bGi6RolaLLZ0fnVEiVGM=" #options.headers["X-Buttercoin-Date"].should.equal "1403558182457" #options.hasOwnProperty("qs").should.equal false #options.json.should.equal true #return #return #return
9231
#should = require("should") #clientWithMode = (mode) -> #require("../").withApiKey "<KEY>", "<KEY>", mode #describe "Buttercoin", -> #buttercoin = undefined #api_key = undefined #api_secret = undefined #mode = undefined #version = undefined #describe "setup of client object", -> #beforeEach -> #api_key = "" #api_secret = "" #mode = "" #version = "" #return #it "should configure the client correctly on new object", -> #api_key = "<KEY>" #api_secret = "<KEY>" #mode = "production" #version = "v1" #buttercoin = require("../").withApiKey(api_key, api_secret, mode, version) #should.exist buttercoin #buttercoin.apiKey.should.equal api_key #buttercoin.apiSecret.should.equal api_secret #buttercoin.apiUrl.should.equal "https://api.buttercoin.com" #buttercoin.version.should.equal version #return #it "should throw an error if no api_key is present", -> #try #buttercoin = require("../").withApiKey() #catch error #should.exist error #error.message.should.equal "API Key parameter must be specified and be of length 32 characters" #return #it "should throw an error if api_key is incorrect length", -> #try #buttercoin = require("../").withApiKey("too_short") #catch error #should.exist error #error.message.should.equal "API Key parameter must be specified and be of length 32 characters" #return #it "should throw an error if no api_secret is present", -> #try #buttercoin = require("../").withApiKey("<KEY>") #catch error #should.exist error #error.message.should.equal "API Secret parameter must be specified and be of length 32 characters" #return #it "should throw an error if api_secret is incorrect length", -> #try #buttercoin = require("../").withApiKey("<KEY>", "too_short") #catch error #should.exist error #error.message.should.equal "API Secret parameter must be specified and be of length 32 characters" #return #it "should point to staging if mode is not production", -> #buttercoin = clientWithMode("staging") #buttercoin.apiUrl.should.equal "https://sandbox.buttercoin.com" #return #it "should allow for the specificatoin of a custom endpoint", -> #buttercoin = clientWithMode( #protocol: "http" #host: "localhost" #port: 1234 #headers: #"X-Forwarded-For": "127.0.0.1" #) #url = buttercoin.buildUrl("key") #timestamp = "1403558182457" #signature = buttercoin.signUrl(url, timestamp) #buttercoin.apiUrl.should.equal "http://localhost:1234" #headers = buttercoin.getHeaders(signature, timestamp) #headers["X-Forwarded-For"].should.equal "127.0.0.1" #return #it "should build a url correctly with the given endpoint, sign the url and build the headers", -> #buttercoin = clientWithMode("production") #url = buttercoin.buildUrl("key") #url.should.equal "https://api.buttercoin.com/v1/key" #timestamp = "1403558182457" #signature = buttercoin.signUrl(url, timestamp) #signature.should.equal "amakcIy40XLCUaSz6urhl+687F2pIexux+TJ2bl+66I=" #headers = buttercoin.getHeaders(signature, timestamp) #headers["X-Buttercoin-Access-Key"].should.equal "<KEY>" #headers["X-Buttercoin-Signature"].should.equal "amakcIy40XLCUaSz6urhl+687F2pIexux+TJ2bl+66I=" #headers["X-Buttercoin-Date"].should.equal "1403558182457" #return #it "should build the correct options headers based on get method type", -> #buttercoin = require("../").withApiKey("<KEY>", "<KEY>", "production") #method = "GET" #endpoint = "orders" #timestamp = "1403558182457" #body = testParam: "testVal" #options = buttercoin.buildRequest(method, endpoint, timestamp, body) #options.headers["X-Buttercoin-Access-Key"].should.equal "<KEY>" #options.headers["X-Buttercoin-Signature"].should.equal "M0cug9fN1vRh+eECgBz+bTRhu1u/A7Mgm5cpHPKwWIU=" #options.headers["X-Buttercoin-Date"].should.equal "1403558182457" #options.qs.should.equal body #options.json.should.equal true #return #it "should build the correct options headers based on post method type", -> #buttercoin = require("../").withApiKey("<KEY>", "<KEY>", "production") #method = "POST" #endpoint = "orders" #timestamp = "1403558182457" #body = testParam: "testVal" #options = buttercoin.buildRequest(method, endpoint, timestamp, body) #options.headers["X-Buttercoin-Access-Key"].should.equal "<KEY>" #options.headers["X-Buttercoin-Signature"].should.equal "KuGR55mSi+OiF6NOu7UG1lgVV7XTMc91IpUuCRdczr4=" #options.headers["X-Buttercoin-Date"].should.equal "1403558182457" #options.hasOwnProperty("qs").should.equal false #options.json.should.equal body #return #it "should build the correct options headers based on post method type", -> #buttercoin = require("../").withApiKey("<KEY>", "<KEY>", "production") #method = "DELETE" #endpoint = "orders/my_order_id" #timestamp = "1403558182457" #body = testParam: "testVal" #options = buttercoin.buildRequest(method, endpoint, timestamp, body) #options.headers["X-Buttercoin-Access-Key"].should.equal "<KEY>" #options.headers["X-Buttercoin-Signature"].should.equal "rI9nSlbev0b+wY+qge38n72bGi6RolaLLZ0fnVEiVGM=" #options.headers["X-Buttercoin-Date"].should.equal "1403558182457" #options.hasOwnProperty("qs").should.equal false #options.json.should.equal true #return #return #return
true
#should = require("should") #clientWithMode = (mode) -> #require("../").withApiKey "PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI", mode #describe "Buttercoin", -> #buttercoin = undefined #api_key = undefined #api_secret = undefined #mode = undefined #version = undefined #describe "setup of client object", -> #beforeEach -> #api_key = "" #api_secret = "" #mode = "" #version = "" #return #it "should configure the client correctly on new object", -> #api_key = "PI:KEY:<KEY>END_PI" #api_secret = "PI:KEY:<KEY>END_PI" #mode = "production" #version = "v1" #buttercoin = require("../").withApiKey(api_key, api_secret, mode, version) #should.exist buttercoin #buttercoin.apiKey.should.equal api_key #buttercoin.apiSecret.should.equal api_secret #buttercoin.apiUrl.should.equal "https://api.buttercoin.com" #buttercoin.version.should.equal version #return #it "should throw an error if no api_key is present", -> #try #buttercoin = require("../").withApiKey() #catch error #should.exist error #error.message.should.equal "API Key parameter must be specified and be of length 32 characters" #return #it "should throw an error if api_key is incorrect length", -> #try #buttercoin = require("../").withApiKey("too_short") #catch error #should.exist error #error.message.should.equal "API Key parameter must be specified and be of length 32 characters" #return #it "should throw an error if no api_secret is present", -> #try #buttercoin = require("../").withApiKey("PI:KEY:<KEY>END_PI") #catch error #should.exist error #error.message.should.equal "API Secret parameter must be specified and be of length 32 characters" #return #it "should throw an error if api_secret is incorrect length", -> #try #buttercoin = require("../").withApiKey("PI:KEY:<KEY>END_PI", "too_short") #catch error #should.exist error #error.message.should.equal "API Secret parameter must be specified and be of length 32 characters" #return #it "should point to staging if mode is not production", -> #buttercoin = clientWithMode("staging") #buttercoin.apiUrl.should.equal "https://sandbox.buttercoin.com" #return #it "should allow for the specificatoin of a custom endpoint", -> #buttercoin = clientWithMode( #protocol: "http" #host: "localhost" #port: 1234 #headers: #"X-Forwarded-For": "127.0.0.1" #) #url = buttercoin.buildUrl("key") #timestamp = "1403558182457" #signature = buttercoin.signUrl(url, timestamp) #buttercoin.apiUrl.should.equal "http://localhost:1234" #headers = buttercoin.getHeaders(signature, timestamp) #headers["X-Forwarded-For"].should.equal "127.0.0.1" #return #it "should build a url correctly with the given endpoint, sign the url and build the headers", -> #buttercoin = clientWithMode("production") #url = buttercoin.buildUrl("key") #url.should.equal "https://api.buttercoin.com/v1/key" #timestamp = "1403558182457" #signature = buttercoin.signUrl(url, timestamp) #signature.should.equal "amakcIy40XLCUaSz6urhl+687F2pIexux+TJ2bl+66I=" #headers = buttercoin.getHeaders(signature, timestamp) #headers["X-Buttercoin-Access-Key"].should.equal "PI:KEY:<KEY>END_PI" #headers["X-Buttercoin-Signature"].should.equal "amakcIy40XLCUaSz6urhl+687F2pIexux+TJ2bl+66I=" #headers["X-Buttercoin-Date"].should.equal "1403558182457" #return #it "should build the correct options headers based on get method type", -> #buttercoin = require("../").withApiKey("PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI", "production") #method = "GET" #endpoint = "orders" #timestamp = "1403558182457" #body = testParam: "testVal" #options = buttercoin.buildRequest(method, endpoint, timestamp, body) #options.headers["X-Buttercoin-Access-Key"].should.equal "PI:KEY:<KEY>END_PI" #options.headers["X-Buttercoin-Signature"].should.equal "M0cug9fN1vRh+eECgBz+bTRhu1u/A7Mgm5cpHPKwWIU=" #options.headers["X-Buttercoin-Date"].should.equal "1403558182457" #options.qs.should.equal body #options.json.should.equal true #return #it "should build the correct options headers based on post method type", -> #buttercoin = require("../").withApiKey("PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI", "production") #method = "POST" #endpoint = "orders" #timestamp = "1403558182457" #body = testParam: "testVal" #options = buttercoin.buildRequest(method, endpoint, timestamp, body) #options.headers["X-Buttercoin-Access-Key"].should.equal "PI:KEY:<KEY>END_PI" #options.headers["X-Buttercoin-Signature"].should.equal "KuGR55mSi+OiF6NOu7UG1lgVV7XTMc91IpUuCRdczr4=" #options.headers["X-Buttercoin-Date"].should.equal "1403558182457" #options.hasOwnProperty("qs").should.equal false #options.json.should.equal body #return #it "should build the correct options headers based on post method type", -> #buttercoin = require("../").withApiKey("PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI", "production") #method = "DELETE" #endpoint = "orders/my_order_id" #timestamp = "1403558182457" #body = testParam: "testVal" #options = buttercoin.buildRequest(method, endpoint, timestamp, body) #options.headers["X-Buttercoin-Access-Key"].should.equal "PI:KEY:<KEY>END_PI" #options.headers["X-Buttercoin-Signature"].should.equal "rI9nSlbev0b+wY+qge38n72bGi6RolaLLZ0fnVEiVGM=" #options.headers["X-Buttercoin-Date"].should.equal "1403558182457" #options.hasOwnProperty("qs").should.equal false #options.json.should.equal true #return #return #return
[ { "context": "#\t> File Name: about.coffee\n#\t> Author: LY\n#\t> Mail: ly.franky@gmail.com\n#\t> Created Time: T", "end": 42, "score": 0.9988530874252319, "start": 40, "tag": "USERNAME", "value": "LY" }, { "context": "> File Name: about.coffee\n#\t> Author: LY\n#\t> Mail: ly.franky@...
server/routes/about.coffee
Booker-Z/MIAC-website
0
# > File Name: about.coffee # > Author: LY # > Mail: ly.franky@gmail.com # > Created Time: Thursday, November 27, 2014 AM10:57:45 CST express = require 'express' router = express.Router() ### * Render template 'about' when get '/about' ### router.get '/', (req, res)-> res.render('about') module.exports = router
211191
# > File Name: about.coffee # > Author: LY # > Mail: <EMAIL> # > Created Time: Thursday, November 27, 2014 AM10:57:45 CST express = require 'express' router = express.Router() ### * Render template 'about' when get '/about' ### router.get '/', (req, res)-> res.render('about') module.exports = router
true
# > File Name: about.coffee # > Author: LY # > Mail: PI:EMAIL:<EMAIL>END_PI # > Created Time: Thursday, November 27, 2014 AM10:57:45 CST express = require 'express' router = express.Router() ### * Render template 'about' when get '/about' ### router.get '/', (req, res)-> res.render('about') module.exports = router
[ { "context": "//# sourceMappingURL=data:application/json;base64,eyJtYXBwaW5ncyI6IkFBQWEsUUFBUSxJQUFJIiwibmFtZXMiOltdLCJzb3VyY2VzIjpbImluZGV4LmNvZmZlZSJdLCJzb3VyY2VzQ29udGVudCI6WyJpZiB0cnVlIHRoZW4gY29uc29sZS5sb2cgXCJ0ZXN0XCJcbiJdLCJ2ZXJzaW9uIjozfQ==\\n\n ''')\n (res.sourceMap.mappings?).shoul", "en...
test/inline-source-map.coffee
slang800/accord
0
should = require 'should' path = require 'path' accord = require '../' Job = require '../lib/job' describe 'inline-source-map', -> before -> @inlineSourceMap = accord.load('inline-source-map') it 'should compose with existing sourcemaps', (done) -> job = new Job( text: 'console.log("test");\n' sourceMap: version: 3, sourceRoot: '', sources: ['index.coffee'], sourcesContent: ['if true then console.log "test"\n'] names: [], mappings: 'AAAa,QAAQ,IAAI' ) @inlineSourceMap.render(job).done (res) -> res.text.should.eql(''' console.log("test"); //# sourceMappingURL=data:application/json;base64,eyJtYXBwaW5ncyI6IkFBQWEsUUFBUSxJQUFJIiwibmFtZXMiOltdLCJzb3VyY2VzIjpbImluZGV4LmNvZmZlZSJdLCJzb3VyY2VzQ29udGVudCI6WyJpZiB0cnVlIHRoZW4gY29uc29sZS5sb2cgXCJ0ZXN0XCJcbiJdLCJ2ZXJzaW9uIjozfQ==\n ''') (res.sourceMap.mappings?).should.eql(false) done() it 'should compose with existing sourcemaps', (done) -> coffee = accord.load('coffee') minifyJS = accord.load('minify-js') coffee.render( ''' if true then console.log "test" blah = -> 42 ''' bare: true filename: 'index.coffee' ).then((res) -> res.text.should.eql(''' var blah; if (true) { console.log("test"); } blah = function() { return 42; };\n ''') res.sourceMap.sourcesContent.should.eql([ 'if true then console.log "test"\nblah = -> 42' ]) res.sourceMap.mappings.should.eql( 'AAAA,IAAA,IAAA;;AAAA,IAAG,IAAH;AAAa,EAAA,OAAO,CAAC,GAAR,CAAY,MAAZ,' + 'CAAA,CAAb;CAAA;;AAAA,IACA,GAAO,SAAA,GAAA;SAAG,GAAH;AAAA,CADP,CAAA' ) return res ).then( minifyJS.render ).then((res) -> res.text.should.eql( 'var blah;console.log("test"),blah=function(){return 42};\n' ) res.sourceMap.sourcesContent.should.eql([ 'if true then console.log "test"\nblah = -> 42' ]) res.sourceMap.mappings.should.eql( 'AAAA,GAAA,KAAa,SAAQ,IAAI,QAAzB,KACO,iBAAG' ) return res ).then( @inlineSourceMap.render ).done (res) -> res.text.should.eql(''' var blah;console.log("test"),blah=function(){return 42}; //# sourceMappingURL=data:application/json;base64,eyJmaWxlIjoiaW5kZXgiLCJtYXBwaW5ncyI6IkFBQUEsR0FBQSxLQUFhLFNBQVEsSUFBSSxRQUF6QixLQUNPLGlCQUFHIiwibmFtZXMiOltdLCJzb3VyY2VzIjpbImluZGV4Il0sInNvdXJjZXNDb250ZW50IjpbImlmIHRydWUgdGhlbiBjb25zb2xlLmxvZyBcInRlc3RcIlxuYmxhaCA9IC0+IDQyIl0sInZlcnNpb24iOjN9\n ''') (res.sourceMap.mappings?).should.eql(false) done()
80702
should = require 'should' path = require 'path' accord = require '../' Job = require '../lib/job' describe 'inline-source-map', -> before -> @inlineSourceMap = accord.load('inline-source-map') it 'should compose with existing sourcemaps', (done) -> job = new Job( text: 'console.log("test");\n' sourceMap: version: 3, sourceRoot: '', sources: ['index.coffee'], sourcesContent: ['if true then console.log "test"\n'] names: [], mappings: 'AAAa,QAAQ,IAAI' ) @inlineSourceMap.render(job).done (res) -> res.text.should.eql(''' console.log("test"); //# sourceMappingURL=data:application/json;base64,<KEY>n ''') (res.sourceMap.mappings?).should.eql(false) done() it 'should compose with existing sourcemaps', (done) -> coffee = accord.load('coffee') minifyJS = accord.load('minify-js') coffee.render( ''' if true then console.log "test" blah = -> 42 ''' bare: true filename: 'index.coffee' ).then((res) -> res.text.should.eql(''' var blah; if (true) { console.log("test"); } blah = function() { return 42; };\n ''') res.sourceMap.sourcesContent.should.eql([ 'if true then console.log "test"\nblah = -> 42' ]) res.sourceMap.mappings.should.eql( 'AAAA,IAAA,IAAA;;AAAA,IAAG,IAAH;AAAa,EAAA,OAAO,CAAC,GAAR,CAAY,MAAZ,' + 'CAAA,CAAb;CAAA;;AAAA,IACA,GAAO,SAAA,GAAA;SAAG,GAAH;AAAA,CADP,CAAA' ) return res ).then( minifyJS.render ).then((res) -> res.text.should.eql( 'var blah;console.log("test"),blah=function(){return 42};\n' ) res.sourceMap.sourcesContent.should.eql([ 'if true then console.log "test"\nblah = -> 42' ]) res.sourceMap.mappings.should.eql( 'AAAA,GAAA,KAAa,SAAQ,IAAI,QAAzB,KACO,iBAAG' ) return res ).then( @inlineSourceMap.render ).done (res) -> res.text.should.eql(''' var blah;console.log("test"),blah=function(){return 42}; //# sourceMappingURL=data:application/json;base64,<KEY> ''') (res.sourceMap.mappings?).should.eql(false) done()
true
should = require 'should' path = require 'path' accord = require '../' Job = require '../lib/job' describe 'inline-source-map', -> before -> @inlineSourceMap = accord.load('inline-source-map') it 'should compose with existing sourcemaps', (done) -> job = new Job( text: 'console.log("test");\n' sourceMap: version: 3, sourceRoot: '', sources: ['index.coffee'], sourcesContent: ['if true then console.log "test"\n'] names: [], mappings: 'AAAa,QAAQ,IAAI' ) @inlineSourceMap.render(job).done (res) -> res.text.should.eql(''' console.log("test"); //# sourceMappingURL=data:application/json;base64,PI:KEY:<KEY>END_PIn ''') (res.sourceMap.mappings?).should.eql(false) done() it 'should compose with existing sourcemaps', (done) -> coffee = accord.load('coffee') minifyJS = accord.load('minify-js') coffee.render( ''' if true then console.log "test" blah = -> 42 ''' bare: true filename: 'index.coffee' ).then((res) -> res.text.should.eql(''' var blah; if (true) { console.log("test"); } blah = function() { return 42; };\n ''') res.sourceMap.sourcesContent.should.eql([ 'if true then console.log "test"\nblah = -> 42' ]) res.sourceMap.mappings.should.eql( 'AAAA,IAAA,IAAA;;AAAA,IAAG,IAAH;AAAa,EAAA,OAAO,CAAC,GAAR,CAAY,MAAZ,' + 'CAAA,CAAb;CAAA;;AAAA,IACA,GAAO,SAAA,GAAA;SAAG,GAAH;AAAA,CADP,CAAA' ) return res ).then( minifyJS.render ).then((res) -> res.text.should.eql( 'var blah;console.log("test"),blah=function(){return 42};\n' ) res.sourceMap.sourcesContent.should.eql([ 'if true then console.log "test"\nblah = -> 42' ]) res.sourceMap.mappings.should.eql( 'AAAA,GAAA,KAAa,SAAQ,IAAI,QAAzB,KACO,iBAAG' ) return res ).then( @inlineSourceMap.render ).done (res) -> res.text.should.eql(''' var blah;console.log("test"),blah=function(){return 42}; //# sourceMappingURL=data:application/json;base64,PI:KEY:<KEY>END_PI ''') (res.sourceMap.mappings?).should.eql(false) done()
[ { "context": " scrolled down when switching steps\n key: \"new-place-#{step}\"\n },\n z @$steps[step]\n\n z @$stepB", "end": 11037, "score": 0.9872152209281921, "start": 11019, "tag": "KEY", "value": "new-place-#{step}\"" } ]
src/components/new_place/index.coffee
FreeRoamApp/free-roam
14
z = require 'zorium' RxBehaviorSubject = require('rxjs/BehaviorSubject').BehaviorSubject RxReplaySubject = require('rxjs/ReplaySubject').ReplaySubject RxObservable = require('rxjs/Observable').Observable require 'rxjs/add/observable/of' require 'rxjs/add/observable/combineLatest' require 'rxjs/add/operator/auditTime' _mapValues = require 'lodash/mapValues' _isEmpty = require 'lodash/isEmpty' _keys = require 'lodash/keys' _values = require 'lodash/values' _defaults = require 'lodash/defaults' _find = require 'lodash/find' _filter = require 'lodash/filter' _forEach = require 'lodash/forEach' _map = require 'lodash/map' _merge = require 'lodash/merge' _reduce = require 'lodash/reduce' _zipObject = require 'lodash/zipObject' AppBar = require '../../components/app_bar' ButtonBack = require '../../components/button_back' NewReviewCompose = require '../new_review_compose' Environment = require '../../services/environment' StepBar = require '../step_bar' colors = require '../../colors' config = require '../../config' if window? require './index.styl' # editing can probably be its own component. Editing just needs name, text fields, # of sites, and location # auto-generated: cell, all sliders # new campground is trying to source a lot more # step 1 is add new campsite, then just go through review steps, but all are mandatory # TODO: combine code here with new_place_review/index.coffee (a lot of overlap) STEPS = initialInfo: 0 reviewExtra: 1 review: 2 AUTOSAVE_FREQ_MS = 3000 # every 3 seconds LOCAL_STORAGE_AUTOSAVE = 'newPlace:autosave' module.exports = class NewPlace constructor: ({@model, @router, @location}) -> me = @model.user.getMe() @$appBar = new AppBar {@model} @$buttonBack = new ButtonBack {@model, @router} @step = new RxBehaviorSubject 0 @$stepBar = new StepBar {@model, @step} @season = new RxBehaviorSubject @model.time.getCurrentSeason() @reviewFields = title: valueStreams: new RxReplaySubject 1 errorSubject: new RxBehaviorSubject null body: valueStreams: new RxReplaySubject 1 errorSubject: new RxBehaviorSubject null rating: valueStreams: new RxReplaySubject 1 errorSubject: new RxBehaviorSubject null attachments: valueStreams: new RxReplaySubject 1 errorSubject: new RxBehaviorSubject null reviewExtraFieldsValues = RxObservable.combineLatest( _map @reviewExtraFields, ({valueStreams}) -> valueStreams.switch() (vals...) => _zipObject _keys(@reviewExtraFields), vals ) reviewFeaturesFieldsValues = RxObservable.combineLatest( _map @reviewFeaturesFields, ({valueStreams}) -> valueStreams.switch() (vals...) => _zipObject _keys(@reviewFeaturesFields), vals ) @resetValueStreams() @$steps = _filter [ new @NewPlaceInitialInfo { @model, @router, fields: @initialInfoFields, @season } new @NewReviewExtras { @model, @router, fields: @reviewExtraFields, fieldsValues: reviewExtraFieldsValues, @season } if @NewReviewFeatures new @NewReviewFeatures { @model, @router, fields: @reviewFeaturesFields, fieldsValues: reviewFeaturesFieldsValues } new NewReviewCompose { @model, @router, fields: @reviewFields, @season uploadFn: (args...) => @placeReviewModel.uploadImage.apply( @placeReviewModel.uploadImage args ) } ] @state = z.state { @step me: @model.user.getMe() isLoading: false nameValue: @initialInfoFields.name.valueStreams.switch() detailsValue: @initialInfoFields.details.valueStreams.switch() websiteValue: @initialInfoFields.website.valueStreams.switch() locationValue: @initialInfoFields.location.valueStreams.switch() subTypeValue: @initialInfoFields.subType?.valueStreams.switch() agencyValue: @initialInfoFields.agency?.valueStreams.switch() regionValue: @initialInfoFields.region?.valueStreams.switch() officeValue: @initialInfoFields.office?.valueStreams.switch() titleValue: @reviewFields.title.valueStreams.switch() bodyValue: @reviewFields.body.valueStreams.switch() attachmentsValue: @reviewFields.attachments.valueStreams.switch() ratingValue: @reviewFields.rating.valueStreams.switch() featuresValue: @reviewFeaturesFields?.features.valueStreams.switch() reviewExtraFieldsValues } upsert: => {me, nameValue, detailsValue, locationValue, subTypeValue, agencyValue, regionValue, officeValue, attachmentsValue, websiteValue featuresValue} = @state.getValue() @state.set isLoading: true @model.user.requestLoginIfGuest me .then => if _find attachmentsValue, {isUploading: true} isReady = confirm @model.l.get 'newReview.pendingUpload' else isReady = true if isReady @placeModel.upsert { name: nameValue details: detailsValue location: locationValue subType: subTypeValue agencySlug: agencyValue regionSlug: regionValue officeSlug: officeValue features: featuresValue contact: website: websiteValue } .then @upsertReview .catch (err) => err = try JSON.parse err.message catch {} console.log err @step.next STEPS[err.info.step] or 0 errorSubject = switch err.info.field when 'location' then @initialInfoFields.location.errorSubject when 'body' then @reviewFields.body.errorSubject else @initialInfoFields.location.errorSubject errorSubject.next @model.l.get err.info.langKey @state.set isLoading: false .then => delete localStorage[LOCAL_STORAGE_AUTOSAVE] # clear autosave @state.set isLoading: false else @state.set isLoading: false upsertReview: (parent) => {titleValue, bodyValue, ratingValue, attachmentsValue, reviewExtraFieldsValues} = @state.getValue() attachments = _filter attachmentsValue, ({isUploading}) -> not isUploading extras = _mapValues @reviewExtraFields, ({isSeasonal}, field) => value = reviewExtraFieldsValues[field] if isSeasonal and value? season = @season.getValue() {"#{season}": value} else if not isSeasonal value @placeReviewModel.upsert { type: @type parentId: parent?.id title: titleValue body: bodyValue attachments: attachments rating: ratingValue extras: extras } .then (newReview) => @resetValueStreams() # FIXME FIXME: rm HACK. for some reason thread is empty initially? # still unsure why setTimeout => @router.go @placeWithTabPath, { slug: parent?.slug, tab: 'reviews' }, {reset: true} , 200 afterMount: => # since ios keyboard covers step bar, give an easy way to close ("Done") if Environment.isNativeApp('freeroam') and Environment.isIos() @model.portal.call 'keyboard.showAccessoryBar' changesStream = @getAllChangesStream() @disposable = changesStream.auditTime(AUTOSAVE_FREQ_MS).subscribe (fields) -> localStorage[LOCAL_STORAGE_AUTOSAVE] = JSON.stringify fields beforeUnmount: => if Environment.isNativeApp('freeroam') and Environment.isIos() @model.portal.call 'keyboard.hideAccessoryBar' @step.next 0 @resetValueStreams() @disposable.unsubscribe() resetValueStreams: => autosave = try JSON.parse localStorage[LOCAL_STORAGE_AUTOSAVE] catch {} @initialInfoFields.name.valueStreams.next( RxObservable.of autosave['initialInfo.name'] or '' ) @initialInfoFields.details.valueStreams.next( RxObservable.of autosave['initialInfo.details'] or '' ) @initialInfoFields.website.valueStreams.next( RxObservable.of autosave['initialInfo.websiteUrl'] or '' ) if @initialInfoFields.subType @initialInfoFields.subType?.valueStreams.next( RxObservable.of autosave['initialInfo.subType'] or 'restArea' ) if @location @initialInfoFields.location.valueStreams.next @location.map (location) -> location or autosave['initialInfo.location'] or '' if @initialInfoFields.agency agencyInfo = @initialInfoFields.location.valueStreams.switch().switchMap (location) => if location @model.agency.getAgencyInfoFromLocation location else RxObservable.of null @initialInfoFields.subType.valueStreams.next agencyInfo.map (agencyInfo) -> if agencyInfo 'public' else '' @initialInfoFields.agency.valueStreams.next agencyInfo.map (agencyInfo) -> agencyInfo?.agencySlug or autosave['initialInfo.agency'] or '' @initialInfoFields.region.valueStreams.next agencyInfo.map (agencyInfo) -> agencyInfo?.regionSlug or autosave['initialInfo.region'] or '' @initialInfoFields.office.valueStreams.next agencyInfo.map (agencyInfo) -> agencyInfo?.slug or autosave['initialInfo.office'] or '' @reviewFeaturesFields?.features.valueStreams.next( # RxObservable.of autosave['initialInfo.name'] or '' [] # TODO: autosave ) @reviewFields.title.valueStreams.next( RxObservable.of autosave['review.title'] or '' ) @reviewFields.body.valueStreams.next( RxObservable.of autosave['review.body'] or '' ) @reviewFields.rating.valueStreams.next( RxObservable.of autosave['review.rating'] or null ) @reviewFields.attachments.valueStreams.next new RxBehaviorSubject [] _forEach @reviewExtraFields, (field, key) -> field.valueStreams.next( RxObservable.of autosave["reviewExtra.#{key}"] or null ) @$steps?[1].reset() getAllChangesStream: => initialInfo = @getChangesStream @initialInfoFields, 'initialInfo' review = @getChangesStream @reviewFields, 'review' reviewExtra = @getChangesStream @reviewExtraFields, 'reviewExtra' allChanges = _merge initialInfo, review, reviewExtra keys = _keys allChanges RxObservable.combineLatest( _values allChanges (vals...) -> _zipObject keys, vals ) getChangesStream: (fields, typeKey) => observables = _reduce fields, (obj, field, key) -> if field.valueStreams obj["#{typeKey}.#{key}"] = field.valueStreams.switch() else obj["#{typeKey}.#{key}"] = field.valueSubject obj , {} render: => {step, isLoading, locationValue} = @state.getValue() z '.z-new-place', z @$appBar, { title: @$steps[step].getTitle() style: 'primary' $topLeftButton: z @$buttonBack } z '.step', { # if DOM el is reused, page stays scrolled down when switching steps key: "new-place-#{step}" }, z @$steps[step] z @$stepBar, { isSaving: false steps: @$steps.length isStepCompleted: @$steps[step]?.isCompleted?() isLoading: isLoading save: icon: 'arrow-right' onclick: => unless isLoading @upsert() }
129171
z = require 'zorium' RxBehaviorSubject = require('rxjs/BehaviorSubject').BehaviorSubject RxReplaySubject = require('rxjs/ReplaySubject').ReplaySubject RxObservable = require('rxjs/Observable').Observable require 'rxjs/add/observable/of' require 'rxjs/add/observable/combineLatest' require 'rxjs/add/operator/auditTime' _mapValues = require 'lodash/mapValues' _isEmpty = require 'lodash/isEmpty' _keys = require 'lodash/keys' _values = require 'lodash/values' _defaults = require 'lodash/defaults' _find = require 'lodash/find' _filter = require 'lodash/filter' _forEach = require 'lodash/forEach' _map = require 'lodash/map' _merge = require 'lodash/merge' _reduce = require 'lodash/reduce' _zipObject = require 'lodash/zipObject' AppBar = require '../../components/app_bar' ButtonBack = require '../../components/button_back' NewReviewCompose = require '../new_review_compose' Environment = require '../../services/environment' StepBar = require '../step_bar' colors = require '../../colors' config = require '../../config' if window? require './index.styl' # editing can probably be its own component. Editing just needs name, text fields, # of sites, and location # auto-generated: cell, all sliders # new campground is trying to source a lot more # step 1 is add new campsite, then just go through review steps, but all are mandatory # TODO: combine code here with new_place_review/index.coffee (a lot of overlap) STEPS = initialInfo: 0 reviewExtra: 1 review: 2 AUTOSAVE_FREQ_MS = 3000 # every 3 seconds LOCAL_STORAGE_AUTOSAVE = 'newPlace:autosave' module.exports = class NewPlace constructor: ({@model, @router, @location}) -> me = @model.user.getMe() @$appBar = new AppBar {@model} @$buttonBack = new ButtonBack {@model, @router} @step = new RxBehaviorSubject 0 @$stepBar = new StepBar {@model, @step} @season = new RxBehaviorSubject @model.time.getCurrentSeason() @reviewFields = title: valueStreams: new RxReplaySubject 1 errorSubject: new RxBehaviorSubject null body: valueStreams: new RxReplaySubject 1 errorSubject: new RxBehaviorSubject null rating: valueStreams: new RxReplaySubject 1 errorSubject: new RxBehaviorSubject null attachments: valueStreams: new RxReplaySubject 1 errorSubject: new RxBehaviorSubject null reviewExtraFieldsValues = RxObservable.combineLatest( _map @reviewExtraFields, ({valueStreams}) -> valueStreams.switch() (vals...) => _zipObject _keys(@reviewExtraFields), vals ) reviewFeaturesFieldsValues = RxObservable.combineLatest( _map @reviewFeaturesFields, ({valueStreams}) -> valueStreams.switch() (vals...) => _zipObject _keys(@reviewFeaturesFields), vals ) @resetValueStreams() @$steps = _filter [ new @NewPlaceInitialInfo { @model, @router, fields: @initialInfoFields, @season } new @NewReviewExtras { @model, @router, fields: @reviewExtraFields, fieldsValues: reviewExtraFieldsValues, @season } if @NewReviewFeatures new @NewReviewFeatures { @model, @router, fields: @reviewFeaturesFields, fieldsValues: reviewFeaturesFieldsValues } new NewReviewCompose { @model, @router, fields: @reviewFields, @season uploadFn: (args...) => @placeReviewModel.uploadImage.apply( @placeReviewModel.uploadImage args ) } ] @state = z.state { @step me: @model.user.getMe() isLoading: false nameValue: @initialInfoFields.name.valueStreams.switch() detailsValue: @initialInfoFields.details.valueStreams.switch() websiteValue: @initialInfoFields.website.valueStreams.switch() locationValue: @initialInfoFields.location.valueStreams.switch() subTypeValue: @initialInfoFields.subType?.valueStreams.switch() agencyValue: @initialInfoFields.agency?.valueStreams.switch() regionValue: @initialInfoFields.region?.valueStreams.switch() officeValue: @initialInfoFields.office?.valueStreams.switch() titleValue: @reviewFields.title.valueStreams.switch() bodyValue: @reviewFields.body.valueStreams.switch() attachmentsValue: @reviewFields.attachments.valueStreams.switch() ratingValue: @reviewFields.rating.valueStreams.switch() featuresValue: @reviewFeaturesFields?.features.valueStreams.switch() reviewExtraFieldsValues } upsert: => {me, nameValue, detailsValue, locationValue, subTypeValue, agencyValue, regionValue, officeValue, attachmentsValue, websiteValue featuresValue} = @state.getValue() @state.set isLoading: true @model.user.requestLoginIfGuest me .then => if _find attachmentsValue, {isUploading: true} isReady = confirm @model.l.get 'newReview.pendingUpload' else isReady = true if isReady @placeModel.upsert { name: nameValue details: detailsValue location: locationValue subType: subTypeValue agencySlug: agencyValue regionSlug: regionValue officeSlug: officeValue features: featuresValue contact: website: websiteValue } .then @upsertReview .catch (err) => err = try JSON.parse err.message catch {} console.log err @step.next STEPS[err.info.step] or 0 errorSubject = switch err.info.field when 'location' then @initialInfoFields.location.errorSubject when 'body' then @reviewFields.body.errorSubject else @initialInfoFields.location.errorSubject errorSubject.next @model.l.get err.info.langKey @state.set isLoading: false .then => delete localStorage[LOCAL_STORAGE_AUTOSAVE] # clear autosave @state.set isLoading: false else @state.set isLoading: false upsertReview: (parent) => {titleValue, bodyValue, ratingValue, attachmentsValue, reviewExtraFieldsValues} = @state.getValue() attachments = _filter attachmentsValue, ({isUploading}) -> not isUploading extras = _mapValues @reviewExtraFields, ({isSeasonal}, field) => value = reviewExtraFieldsValues[field] if isSeasonal and value? season = @season.getValue() {"#{season}": value} else if not isSeasonal value @placeReviewModel.upsert { type: @type parentId: parent?.id title: titleValue body: bodyValue attachments: attachments rating: ratingValue extras: extras } .then (newReview) => @resetValueStreams() # FIXME FIXME: rm HACK. for some reason thread is empty initially? # still unsure why setTimeout => @router.go @placeWithTabPath, { slug: parent?.slug, tab: 'reviews' }, {reset: true} , 200 afterMount: => # since ios keyboard covers step bar, give an easy way to close ("Done") if Environment.isNativeApp('freeroam') and Environment.isIos() @model.portal.call 'keyboard.showAccessoryBar' changesStream = @getAllChangesStream() @disposable = changesStream.auditTime(AUTOSAVE_FREQ_MS).subscribe (fields) -> localStorage[LOCAL_STORAGE_AUTOSAVE] = JSON.stringify fields beforeUnmount: => if Environment.isNativeApp('freeroam') and Environment.isIos() @model.portal.call 'keyboard.hideAccessoryBar' @step.next 0 @resetValueStreams() @disposable.unsubscribe() resetValueStreams: => autosave = try JSON.parse localStorage[LOCAL_STORAGE_AUTOSAVE] catch {} @initialInfoFields.name.valueStreams.next( RxObservable.of autosave['initialInfo.name'] or '' ) @initialInfoFields.details.valueStreams.next( RxObservable.of autosave['initialInfo.details'] or '' ) @initialInfoFields.website.valueStreams.next( RxObservable.of autosave['initialInfo.websiteUrl'] or '' ) if @initialInfoFields.subType @initialInfoFields.subType?.valueStreams.next( RxObservable.of autosave['initialInfo.subType'] or 'restArea' ) if @location @initialInfoFields.location.valueStreams.next @location.map (location) -> location or autosave['initialInfo.location'] or '' if @initialInfoFields.agency agencyInfo = @initialInfoFields.location.valueStreams.switch().switchMap (location) => if location @model.agency.getAgencyInfoFromLocation location else RxObservable.of null @initialInfoFields.subType.valueStreams.next agencyInfo.map (agencyInfo) -> if agencyInfo 'public' else '' @initialInfoFields.agency.valueStreams.next agencyInfo.map (agencyInfo) -> agencyInfo?.agencySlug or autosave['initialInfo.agency'] or '' @initialInfoFields.region.valueStreams.next agencyInfo.map (agencyInfo) -> agencyInfo?.regionSlug or autosave['initialInfo.region'] or '' @initialInfoFields.office.valueStreams.next agencyInfo.map (agencyInfo) -> agencyInfo?.slug or autosave['initialInfo.office'] or '' @reviewFeaturesFields?.features.valueStreams.next( # RxObservable.of autosave['initialInfo.name'] or '' [] # TODO: autosave ) @reviewFields.title.valueStreams.next( RxObservable.of autosave['review.title'] or '' ) @reviewFields.body.valueStreams.next( RxObservable.of autosave['review.body'] or '' ) @reviewFields.rating.valueStreams.next( RxObservable.of autosave['review.rating'] or null ) @reviewFields.attachments.valueStreams.next new RxBehaviorSubject [] _forEach @reviewExtraFields, (field, key) -> field.valueStreams.next( RxObservable.of autosave["reviewExtra.#{key}"] or null ) @$steps?[1].reset() getAllChangesStream: => initialInfo = @getChangesStream @initialInfoFields, 'initialInfo' review = @getChangesStream @reviewFields, 'review' reviewExtra = @getChangesStream @reviewExtraFields, 'reviewExtra' allChanges = _merge initialInfo, review, reviewExtra keys = _keys allChanges RxObservable.combineLatest( _values allChanges (vals...) -> _zipObject keys, vals ) getChangesStream: (fields, typeKey) => observables = _reduce fields, (obj, field, key) -> if field.valueStreams obj["#{typeKey}.#{key}"] = field.valueStreams.switch() else obj["#{typeKey}.#{key}"] = field.valueSubject obj , {} render: => {step, isLoading, locationValue} = @state.getValue() z '.z-new-place', z @$appBar, { title: @$steps[step].getTitle() style: 'primary' $topLeftButton: z @$buttonBack } z '.step', { # if DOM el is reused, page stays scrolled down when switching steps key: "<KEY> }, z @$steps[step] z @$stepBar, { isSaving: false steps: @$steps.length isStepCompleted: @$steps[step]?.isCompleted?() isLoading: isLoading save: icon: 'arrow-right' onclick: => unless isLoading @upsert() }
true
z = require 'zorium' RxBehaviorSubject = require('rxjs/BehaviorSubject').BehaviorSubject RxReplaySubject = require('rxjs/ReplaySubject').ReplaySubject RxObservable = require('rxjs/Observable').Observable require 'rxjs/add/observable/of' require 'rxjs/add/observable/combineLatest' require 'rxjs/add/operator/auditTime' _mapValues = require 'lodash/mapValues' _isEmpty = require 'lodash/isEmpty' _keys = require 'lodash/keys' _values = require 'lodash/values' _defaults = require 'lodash/defaults' _find = require 'lodash/find' _filter = require 'lodash/filter' _forEach = require 'lodash/forEach' _map = require 'lodash/map' _merge = require 'lodash/merge' _reduce = require 'lodash/reduce' _zipObject = require 'lodash/zipObject' AppBar = require '../../components/app_bar' ButtonBack = require '../../components/button_back' NewReviewCompose = require '../new_review_compose' Environment = require '../../services/environment' StepBar = require '../step_bar' colors = require '../../colors' config = require '../../config' if window? require './index.styl' # editing can probably be its own component. Editing just needs name, text fields, # of sites, and location # auto-generated: cell, all sliders # new campground is trying to source a lot more # step 1 is add new campsite, then just go through review steps, but all are mandatory # TODO: combine code here with new_place_review/index.coffee (a lot of overlap) STEPS = initialInfo: 0 reviewExtra: 1 review: 2 AUTOSAVE_FREQ_MS = 3000 # every 3 seconds LOCAL_STORAGE_AUTOSAVE = 'newPlace:autosave' module.exports = class NewPlace constructor: ({@model, @router, @location}) -> me = @model.user.getMe() @$appBar = new AppBar {@model} @$buttonBack = new ButtonBack {@model, @router} @step = new RxBehaviorSubject 0 @$stepBar = new StepBar {@model, @step} @season = new RxBehaviorSubject @model.time.getCurrentSeason() @reviewFields = title: valueStreams: new RxReplaySubject 1 errorSubject: new RxBehaviorSubject null body: valueStreams: new RxReplaySubject 1 errorSubject: new RxBehaviorSubject null rating: valueStreams: new RxReplaySubject 1 errorSubject: new RxBehaviorSubject null attachments: valueStreams: new RxReplaySubject 1 errorSubject: new RxBehaviorSubject null reviewExtraFieldsValues = RxObservable.combineLatest( _map @reviewExtraFields, ({valueStreams}) -> valueStreams.switch() (vals...) => _zipObject _keys(@reviewExtraFields), vals ) reviewFeaturesFieldsValues = RxObservable.combineLatest( _map @reviewFeaturesFields, ({valueStreams}) -> valueStreams.switch() (vals...) => _zipObject _keys(@reviewFeaturesFields), vals ) @resetValueStreams() @$steps = _filter [ new @NewPlaceInitialInfo { @model, @router, fields: @initialInfoFields, @season } new @NewReviewExtras { @model, @router, fields: @reviewExtraFields, fieldsValues: reviewExtraFieldsValues, @season } if @NewReviewFeatures new @NewReviewFeatures { @model, @router, fields: @reviewFeaturesFields, fieldsValues: reviewFeaturesFieldsValues } new NewReviewCompose { @model, @router, fields: @reviewFields, @season uploadFn: (args...) => @placeReviewModel.uploadImage.apply( @placeReviewModel.uploadImage args ) } ] @state = z.state { @step me: @model.user.getMe() isLoading: false nameValue: @initialInfoFields.name.valueStreams.switch() detailsValue: @initialInfoFields.details.valueStreams.switch() websiteValue: @initialInfoFields.website.valueStreams.switch() locationValue: @initialInfoFields.location.valueStreams.switch() subTypeValue: @initialInfoFields.subType?.valueStreams.switch() agencyValue: @initialInfoFields.agency?.valueStreams.switch() regionValue: @initialInfoFields.region?.valueStreams.switch() officeValue: @initialInfoFields.office?.valueStreams.switch() titleValue: @reviewFields.title.valueStreams.switch() bodyValue: @reviewFields.body.valueStreams.switch() attachmentsValue: @reviewFields.attachments.valueStreams.switch() ratingValue: @reviewFields.rating.valueStreams.switch() featuresValue: @reviewFeaturesFields?.features.valueStreams.switch() reviewExtraFieldsValues } upsert: => {me, nameValue, detailsValue, locationValue, subTypeValue, agencyValue, regionValue, officeValue, attachmentsValue, websiteValue featuresValue} = @state.getValue() @state.set isLoading: true @model.user.requestLoginIfGuest me .then => if _find attachmentsValue, {isUploading: true} isReady = confirm @model.l.get 'newReview.pendingUpload' else isReady = true if isReady @placeModel.upsert { name: nameValue details: detailsValue location: locationValue subType: subTypeValue agencySlug: agencyValue regionSlug: regionValue officeSlug: officeValue features: featuresValue contact: website: websiteValue } .then @upsertReview .catch (err) => err = try JSON.parse err.message catch {} console.log err @step.next STEPS[err.info.step] or 0 errorSubject = switch err.info.field when 'location' then @initialInfoFields.location.errorSubject when 'body' then @reviewFields.body.errorSubject else @initialInfoFields.location.errorSubject errorSubject.next @model.l.get err.info.langKey @state.set isLoading: false .then => delete localStorage[LOCAL_STORAGE_AUTOSAVE] # clear autosave @state.set isLoading: false else @state.set isLoading: false upsertReview: (parent) => {titleValue, bodyValue, ratingValue, attachmentsValue, reviewExtraFieldsValues} = @state.getValue() attachments = _filter attachmentsValue, ({isUploading}) -> not isUploading extras = _mapValues @reviewExtraFields, ({isSeasonal}, field) => value = reviewExtraFieldsValues[field] if isSeasonal and value? season = @season.getValue() {"#{season}": value} else if not isSeasonal value @placeReviewModel.upsert { type: @type parentId: parent?.id title: titleValue body: bodyValue attachments: attachments rating: ratingValue extras: extras } .then (newReview) => @resetValueStreams() # FIXME FIXME: rm HACK. for some reason thread is empty initially? # still unsure why setTimeout => @router.go @placeWithTabPath, { slug: parent?.slug, tab: 'reviews' }, {reset: true} , 200 afterMount: => # since ios keyboard covers step bar, give an easy way to close ("Done") if Environment.isNativeApp('freeroam') and Environment.isIos() @model.portal.call 'keyboard.showAccessoryBar' changesStream = @getAllChangesStream() @disposable = changesStream.auditTime(AUTOSAVE_FREQ_MS).subscribe (fields) -> localStorage[LOCAL_STORAGE_AUTOSAVE] = JSON.stringify fields beforeUnmount: => if Environment.isNativeApp('freeroam') and Environment.isIos() @model.portal.call 'keyboard.hideAccessoryBar' @step.next 0 @resetValueStreams() @disposable.unsubscribe() resetValueStreams: => autosave = try JSON.parse localStorage[LOCAL_STORAGE_AUTOSAVE] catch {} @initialInfoFields.name.valueStreams.next( RxObservable.of autosave['initialInfo.name'] or '' ) @initialInfoFields.details.valueStreams.next( RxObservable.of autosave['initialInfo.details'] or '' ) @initialInfoFields.website.valueStreams.next( RxObservable.of autosave['initialInfo.websiteUrl'] or '' ) if @initialInfoFields.subType @initialInfoFields.subType?.valueStreams.next( RxObservable.of autosave['initialInfo.subType'] or 'restArea' ) if @location @initialInfoFields.location.valueStreams.next @location.map (location) -> location or autosave['initialInfo.location'] or '' if @initialInfoFields.agency agencyInfo = @initialInfoFields.location.valueStreams.switch().switchMap (location) => if location @model.agency.getAgencyInfoFromLocation location else RxObservable.of null @initialInfoFields.subType.valueStreams.next agencyInfo.map (agencyInfo) -> if agencyInfo 'public' else '' @initialInfoFields.agency.valueStreams.next agencyInfo.map (agencyInfo) -> agencyInfo?.agencySlug or autosave['initialInfo.agency'] or '' @initialInfoFields.region.valueStreams.next agencyInfo.map (agencyInfo) -> agencyInfo?.regionSlug or autosave['initialInfo.region'] or '' @initialInfoFields.office.valueStreams.next agencyInfo.map (agencyInfo) -> agencyInfo?.slug or autosave['initialInfo.office'] or '' @reviewFeaturesFields?.features.valueStreams.next( # RxObservable.of autosave['initialInfo.name'] or '' [] # TODO: autosave ) @reviewFields.title.valueStreams.next( RxObservable.of autosave['review.title'] or '' ) @reviewFields.body.valueStreams.next( RxObservable.of autosave['review.body'] or '' ) @reviewFields.rating.valueStreams.next( RxObservable.of autosave['review.rating'] or null ) @reviewFields.attachments.valueStreams.next new RxBehaviorSubject [] _forEach @reviewExtraFields, (field, key) -> field.valueStreams.next( RxObservable.of autosave["reviewExtra.#{key}"] or null ) @$steps?[1].reset() getAllChangesStream: => initialInfo = @getChangesStream @initialInfoFields, 'initialInfo' review = @getChangesStream @reviewFields, 'review' reviewExtra = @getChangesStream @reviewExtraFields, 'reviewExtra' allChanges = _merge initialInfo, review, reviewExtra keys = _keys allChanges RxObservable.combineLatest( _values allChanges (vals...) -> _zipObject keys, vals ) getChangesStream: (fields, typeKey) => observables = _reduce fields, (obj, field, key) -> if field.valueStreams obj["#{typeKey}.#{key}"] = field.valueStreams.switch() else obj["#{typeKey}.#{key}"] = field.valueSubject obj , {} render: => {step, isLoading, locationValue} = @state.getValue() z '.z-new-place', z @$appBar, { title: @$steps[step].getTitle() style: 'primary' $topLeftButton: z @$buttonBack } z '.step', { # if DOM el is reused, page stays scrolled down when switching steps key: "PI:KEY:<KEY>END_PI }, z @$steps[step] z @$stepBar, { isSaving: false steps: @$steps.length isStepCompleted: @$steps[step]?.isCompleted?() isLoading: isLoading save: icon: 'arrow-right' onclick: => unless isLoading @upsert() }
[ { "context": " url: baseUri + \"/users\"\n json:\n username: username\n password: password\n dhPub: dhPub\n ", "end": 1772, "score": 0.9992098212242126, "start": 1764, "tag": "USERNAME", "value": "username" }, { "context": " json:\n username: username\n ...
test/setup/createusers.coffee
SchoolOfFreelancing/SureSpot
1
request = require("request") http = require 'http' assert = require("assert") should = require("should") redis = require("redis") util = require("util") fs = require("fs") io = require 'socket.io-client' async = require 'async' _ = require 'underscore' dcrypt = require 'dcrypt' crypto = require 'crypto' #rc = redis.createClient() # generate keys like this: (bash) # private: # for i in {0..4999}; do openssl ecparam -name secp521r1 -outform PEM -out test${i}_priv.pem -genkey; done # then public # for i in {0..4999}; do openssl ec -inform PEM -outform PEM -in test${i}_priv.pem -out test${i}_pub.pem -pubout; done testkeydir = '../testkeys' baseUri = "http://localhost:8080" minclient = 3000 maxclient = 9999 #maxsockets = 100 #http.globalAgent.maxSockets = maxsockets #generateKey = (i, callback) -> # ecdsa = new dcrypt.keypair.newECDSA 'secp521r1' # ecdh = new dcrypt.keypair.newECDSA 'secp521r1' # # random = crypto.randomBytes 16 # # dsaPubSig = # crypto # .createSign('sha256') # .update(new Buffer("test#{i}")) # .update(new Buffer("test#{i}")) # .update(random) # .sign(ecdsa.pem_priv, 'base64') # # sig = Buffer.concat([random, new Buffer(dsaPubSig, 'base64')]).toString('base64') # # callback null, { # ecdsa: ecdsa # ecdh: ecdh # sig: sig # } # # #makeKeys = (i) -> # return (callback) -> # generateKey i, callback # #createKeys = (minclient, maxclient, done) -> # keys = [] # for i in [minclient..maxclient] by 1 # keys.push makeKeys(i) # # async.parallel keys, (err, results) -> # if err? # done err # else # done null, results signup = (username, password, dhPub, dsaPub, authSig, done, callback) -> request.post url: baseUri + "/users" json: username: username password: password dhPub: dhPub dsaPub: dsaPub authSig: authSig (err, res, body) -> if err done err else res.statusCode.should.equal 201 callback res, body createUsers = (i, key, callback) -> #console.log 'i: ' + i signup 'test' + i, 'test' + i, key.pub, key.pub, key.sig, callback, (res, body) -> callback null makeCreate = (i, key) -> return (callback) -> createUsers(i, key, callback) keys = [] index = 0 for i in [minclient..maxclient] priv = fs.readFileSync "#{testkeydir}/test#{i}_priv.pem", 'utf-8' pub = fs.readFileSync "#{testkeydir}/test#{i}_pub.pem", 'utf-8' random = crypto.randomBytes 16 dsaPubSig = crypto .createSign('sha256') .update(new Buffer("test#{i}")) .update(new Buffer("test#{i}")) .update(random) .sign(priv, 'base64') sig = Buffer.concat([random, new Buffer(dsaPubSig, 'base64')]).toString('base64') fs.writeFileSync "#{testkeydir}/test#{i}.sig", sig keys[index++] = { pub: pub sig: sig } tasks = [] #create connect clients tasks index = 0 for i in [minclient..maxclient] by 1 tasks.push makeCreate i, keys[index++] #execute the tasks which creates the cookie jars async.series tasks, (err) -> if err? then console.log err process.exit()
125604
request = require("request") http = require 'http' assert = require("assert") should = require("should") redis = require("redis") util = require("util") fs = require("fs") io = require 'socket.io-client' async = require 'async' _ = require 'underscore' dcrypt = require 'dcrypt' crypto = require 'crypto' #rc = redis.createClient() # generate keys like this: (bash) # private: # for i in {0..4999}; do openssl ecparam -name secp521r1 -outform PEM -out test${i}_priv.pem -genkey; done # then public # for i in {0..4999}; do openssl ec -inform PEM -outform PEM -in test${i}_priv.pem -out test${i}_pub.pem -pubout; done testkeydir = '../testkeys' baseUri = "http://localhost:8080" minclient = 3000 maxclient = 9999 #maxsockets = 100 #http.globalAgent.maxSockets = maxsockets #generateKey = (i, callback) -> # ecdsa = new dcrypt.keypair.newECDSA 'secp521r1' # ecdh = new dcrypt.keypair.newECDSA 'secp521r1' # # random = crypto.randomBytes 16 # # dsaPubSig = # crypto # .createSign('sha256') # .update(new Buffer("test#{i}")) # .update(new Buffer("test#{i}")) # .update(random) # .sign(ecdsa.pem_priv, 'base64') # # sig = Buffer.concat([random, new Buffer(dsaPubSig, 'base64')]).toString('base64') # # callback null, { # ecdsa: ecdsa # ecdh: ecdh # sig: sig # } # # #makeKeys = (i) -> # return (callback) -> # generateKey i, callback # #createKeys = (minclient, maxclient, done) -> # keys = [] # for i in [minclient..maxclient] by 1 # keys.push makeKeys(i) # # async.parallel keys, (err, results) -> # if err? # done err # else # done null, results signup = (username, password, dhPub, dsaPub, authSig, done, callback) -> request.post url: baseUri + "/users" json: username: username password: <PASSWORD> dhPub: dhPub dsaPub: dsaPub authSig: authSig (err, res, body) -> if err done err else res.statusCode.should.equal 201 callback res, body createUsers = (i, key, callback) -> #console.log 'i: ' + i signup 'test' + i, 'test' + i, key.pub, key.pub, key.sig, callback, (res, body) -> callback null makeCreate = (i, key) -> return (callback) -> createUsers(i, key, callback) keys = [] index = 0 for i in [minclient..maxclient] priv = fs.readFileSync "#{testkeydir}/test#{i}_priv.pem", 'utf-8' pub = fs.readFileSync "#{testkeydir}/test#{i}_pub.pem", 'utf-8' random = crypto.randomBytes 16 dsaPubSig = crypto .createSign('sha256') .update(new Buffer("test#{i}")) .update(new Buffer("test#{i}")) .update(random) .sign(priv, 'base64') sig = Buffer.concat([random, new Buffer(dsaPubSig, 'base64')]).toString('base64') fs.writeFileSync "#{testkeydir}/test#{i}.sig", sig keys[index++] = { pub: pub sig: sig } tasks = [] #create connect clients tasks index = 0 for i in [minclient..maxclient] by 1 tasks.push makeCreate i, keys[index++] #execute the tasks which creates the cookie jars async.series tasks, (err) -> if err? then console.log err process.exit()
true
request = require("request") http = require 'http' assert = require("assert") should = require("should") redis = require("redis") util = require("util") fs = require("fs") io = require 'socket.io-client' async = require 'async' _ = require 'underscore' dcrypt = require 'dcrypt' crypto = require 'crypto' #rc = redis.createClient() # generate keys like this: (bash) # private: # for i in {0..4999}; do openssl ecparam -name secp521r1 -outform PEM -out test${i}_priv.pem -genkey; done # then public # for i in {0..4999}; do openssl ec -inform PEM -outform PEM -in test${i}_priv.pem -out test${i}_pub.pem -pubout; done testkeydir = '../testkeys' baseUri = "http://localhost:8080" minclient = 3000 maxclient = 9999 #maxsockets = 100 #http.globalAgent.maxSockets = maxsockets #generateKey = (i, callback) -> # ecdsa = new dcrypt.keypair.newECDSA 'secp521r1' # ecdh = new dcrypt.keypair.newECDSA 'secp521r1' # # random = crypto.randomBytes 16 # # dsaPubSig = # crypto # .createSign('sha256') # .update(new Buffer("test#{i}")) # .update(new Buffer("test#{i}")) # .update(random) # .sign(ecdsa.pem_priv, 'base64') # # sig = Buffer.concat([random, new Buffer(dsaPubSig, 'base64')]).toString('base64') # # callback null, { # ecdsa: ecdsa # ecdh: ecdh # sig: sig # } # # #makeKeys = (i) -> # return (callback) -> # generateKey i, callback # #createKeys = (minclient, maxclient, done) -> # keys = [] # for i in [minclient..maxclient] by 1 # keys.push makeKeys(i) # # async.parallel keys, (err, results) -> # if err? # done err # else # done null, results signup = (username, password, dhPub, dsaPub, authSig, done, callback) -> request.post url: baseUri + "/users" json: username: username password: PI:PASSWORD:<PASSWORD>END_PI dhPub: dhPub dsaPub: dsaPub authSig: authSig (err, res, body) -> if err done err else res.statusCode.should.equal 201 callback res, body createUsers = (i, key, callback) -> #console.log 'i: ' + i signup 'test' + i, 'test' + i, key.pub, key.pub, key.sig, callback, (res, body) -> callback null makeCreate = (i, key) -> return (callback) -> createUsers(i, key, callback) keys = [] index = 0 for i in [minclient..maxclient] priv = fs.readFileSync "#{testkeydir}/test#{i}_priv.pem", 'utf-8' pub = fs.readFileSync "#{testkeydir}/test#{i}_pub.pem", 'utf-8' random = crypto.randomBytes 16 dsaPubSig = crypto .createSign('sha256') .update(new Buffer("test#{i}")) .update(new Buffer("test#{i}")) .update(random) .sign(priv, 'base64') sig = Buffer.concat([random, new Buffer(dsaPubSig, 'base64')]).toString('base64') fs.writeFileSync "#{testkeydir}/test#{i}.sig", sig keys[index++] = { pub: pub sig: sig } tasks = [] #create connect clients tasks index = 0 for i in [minclient..maxclient] by 1 tasks.push makeCreate i, keys[index++] #execute the tasks which creates the cookie jars async.series tasks, (err) -> if err? then console.log err process.exit()
[ { "context": "S)\\s+/, ''\n name = name.replace /^(Alexanderplatz) Bhf\\/(.+)$/, '$1 ($2)'\n name = name.replace /^(", "end": 2503, "score": 0.7582191228866577, "start": 2489, "tag": "NAME", "value": "Alexanderplatz" }, { "context": "hf\\/(.+)$/, '$1 ($2)'\n name ...
src/READER.coffee
loveencounterflow/timetable
1
############################################################################################################ # njs_util = require 'util' # njs_path = require 'path' # njs_fs = require 'fs' # njs_crypto = require 'crypto' #........................................................................................................... # BAP = require 'coffeenode-bitsnpieces' # TYPES = require 'coffeenode-types' # TEXT = require 'coffeenode-text' TRM = require 'coffeenode-trm' rpr = TRM.rpr.bind TRM badge = 'TIMETABLE/READER' log = TRM.get_logger 'plain', badge info = TRM.get_logger 'info', badge whisper = TRM.get_logger 'whisper', badge alert = TRM.get_logger 'alert', badge debug = TRM.get_logger 'debug', badge warn = TRM.get_logger 'warn', badge help = TRM.get_logger 'help', badge urge = TRM.get_logger 'urge', badge echo = TRM.echo.bind TRM rainbow = TRM.rainbow.bind TRM #........................................................................................................... ASYNC = require 'async' #........................................................................................................... REGISTRY = require './REGISTRY' COURSES = require './COURSES' P = require 'pipedreams' $ = P.$.bind P #........................................................................................................... options = require '../options' DEV = options[ 'mode' ] is 'dev' #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- ### TAINT very Berlin-specific method, shouldnt appear here ### @normalize_berlin_station_name = ( name ) -> name = name.replace /\s+\(Berlin\)(\s+Bus)?$/, '' unless /^(U|S) Olympiastadion/.test name name = name.replace /^(U|S\+U|S)\s+/, '' name = name.replace /^(Alexanderplatz) Bhf\/(.+)$/, '$1 ($2)' name = name.replace /^(Lichtenberg) Bhf\/(.+)$/, '$1 ($2)' name = name.replace /^(Alexanderplatz) Bhf/, '$1' name = name.replace /^(Zoologischer Garten) Bhf/, '$1' name = name.replace /^(Gesundbrunnen) Bhf/, '$1' name = name.replace /^(Potsdamer Platz) Bhf/, '$1' name = name.replace /^(Lichtenberg) Bhf/, '$1' name = name.replace /^(Friedrichstr\.) Bhf/, '$1' name = name.replace /^(Jungfernheide) Bhf/, '$1' name = name.replace /^(Stadtmitte) U[26]/, '$1' name = name.replace /str\./g, 'straße' name = name.replace /\s+Str\./g, ' Straße' return name #----------------------------------------------------------------------------------------------------------- @$rn_normalize_station_name = ( key ) -> return $ ( [ record, node, ], handler ) => name = node[ key ] unless name? return handler new Error """ unable to find key #{rpr key} in #{rpr node}""" node[ key ] = @normalize_berlin_station_name name handler null, [ record, node, ] # #----------------------------------------------------------------------------------------------------------- # @$rn_add_n4j_system_properties = ( label ) -> # return $ ( [ record, node, ], handler ) -> # node[ '~isa' ] = 'node' # node[ '~label' ] = label # handler null, [ record, node, ] #----------------------------------------------------------------------------------------------------------- @$remove_gtfs_fields = -> return $ ( node, handler ) -> for name of node delete node[ name ] if /^%gtfs/.test name handler null, node #----------------------------------------------------------------------------------------------------------- @$side_by_side = -> return $ ( node, handler ) -> record = {} record[ name ] = value for name, value of node handler null, [ record, node, ] #----------------------------------------------------------------------------------------------------------- @$rn_one_by_one = -> on_data = ( [ record, node, ]) -> @emit 'data', record @emit 'data', node return P.through on_data, null # #----------------------------------------------------------------------------------------------------------- # @$add_id = -> # idx = 0 # return $ ( node, handler ) -> # id = node[ 'id' ] # label = node[ '~label' ] # return handler new Error "ID already set: #{rpr node}" if id? # return handler new Error "unable to set ID on node without label: #{rpr node}" unless label? # node[ 'id' ] = "#{label}-#{idx}" # idx += 1 # handler null, node #----------------------------------------------------------------------------------------------------------- @$rn_add_ids_etc = ( label ) -> idx = 0 return $ ( [ record, node, ], handler ) -> node[ '~isa' ] = 'node' node[ '~label' ] = label record[ 'node-id' ] = \ node_id = \ node[ 'id' ] = "timetable/#{label}/#{idx}" node[ 'record-id' ] = record[ 'id' ] delete node[ 'gtfs-id' ] delete node[ 'gtfs-type' ] idx += 1 handler null, [ record, node, ] #=========================================================================================================== # AGENCIES #----------------------------------------------------------------------------------------------------------- @read_agency_nodes = ( registry, handler ) -> input = registry.createReadStream keys: no, gte: 'gtfs/agency', lte: 'gtfs/agency\xff' #......................................................................................................... input .pipe @$side_by_side() .pipe @$rn_add_agency_id_etc() .pipe P.$collect_sample 1, ( _, sample ) -> whisper 'agency', sample .pipe @$rn_one_by_one() # .pipe @$remove_gtfs_fields() # .pipe P.$show() .pipe REGISTRY.$register registry .pipe P.$on_end -> handler null #----------------------------------------------------------------------------------------------------------- @$rn_add_agency_id_etc = -> return $ ( [ record, node, ], handler ) -> node[ '~isa' ] = 'node' node[ '~label' ] = 'agency' record[ 'node-id' ] = \ node_id = \ node[ 'id' ] = \ record[ 'id' ].replace /^gtfs\/([^-_]+)[-_]+$/, 'timetable/$1' delete node[ 'gtfs-id' ] node[ 'record-id' ] = record[ 'id' ] delete node[ 'gtfs-type' ] handler null, [ record, node, ] #=========================================================================================================== # STATIONS #----------------------------------------------------------------------------------------------------------- @read_station_nodes = ( registry, handler ) -> ratio = if DEV then 1 / 5000 else 1 input = registry.createReadStream keys: no, gte: 'gtfs/stops', lte: 'gtfs/stops\xff' #......................................................................................................... input .pipe P.$sample ratio, headers: true, seed: 5 # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< .pipe @$side_by_side() .pipe @$rn_normalize_station_name 'name' .pipe @$rn_add_ids_etc 'station' .pipe P.$collect_sample 1, ( _, sample ) -> whisper 'station', sample .pipe @$rn_one_by_one() # .pipe @$remove_gtfs_fields() # .pipe P.$show() .pipe REGISTRY.$register registry .pipe P.$on_end -> handler null #=========================================================================================================== # ROUTES #----------------------------------------------------------------------------------------------------------- @read_route_nodes = ( registry, handler ) -> input = registry.createReadStream keys: no, gte: 'gtfs/routes', lte: 'gtfs/routes\xff' #......................................................................................................... input .pipe @$side_by_side() .pipe @$rn_add_ids_etc 'route' .pipe P.$collect_sample 1, ( _, sample ) -> whisper 'route', sample .pipe @$rn_agency_id_from_gtfs registry .pipe @$rn_one_by_one() # .pipe P.$show() .pipe REGISTRY.$register registry .pipe P.$on_end -> handler null #----------------------------------------------------------------------------------------------------------- @$rn_agency_id_from_gtfs = ( registry ) -> return $ ( [ record, node, ], handler ) -> gtfs_agency_id = node[ 'gtfs-agency-id' ] registry.get "gtfs/agency/#{gtfs_agency_id}", ( error, gtfs_agency_record ) -> return handler error if error? node[ 'agency-id' ] = gtfs_agency_record[ 'node-id' ] delete node[ 'gtfs-agency-id' ] handler null, [ record, node, ] #=========================================================================================================== # COURSES AND TOURS #----------------------------------------------------------------------------------------------------------- @read_tour_nodes = ( registry, handler ) -> ### OBS implies reading courses and halts. ### ratio = if DEV then 1 / 5000 else 1 input = registry.createReadStream keys: no, gte: 'gtfs/trips', lte: 'gtfs/trips\xff' #......................................................................................................... input .pipe @$side_by_side() .pipe P.$sample ratio, headers: true, seed: 5 # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # .pipe @$rn_normalize_station_name 'name' # .pipe @$rn_add_ids_etc 'station' .pipe P.$collect_sample 1, ( _, sample ) -> whisper 'station', sample .pipe @$rn_one_by_one() # .pipe @$remove_gtfs_fields() # .pipe P.$show() # .pipe @$rn_add_n4j_system_properties 'tour' # .pipe @$clean_trip_arr_dep() # .pipe @$tour_from_trip registry # .pipe @$add_tour_id() # .pipe @$remove_gtfs_fields() # .pipe REGISTRY.$register registry .pipe P.$on_end -> handler null #----------------------------------------------------------------------------------------------------------- @$clean_trip_arr_dep = -> ### Replace the first stoptime's arrival and the last stoptime's departure time from the trip. ### return $ ( node, handler ) -> last_idx = node[ '%gtfs-stoptimes' ].length - 1 node[ '%gtfs-stoptimes' ][ 0 ][ 'arr' ] = null node[ '%gtfs-stoptimes' ][ last_idx ][ 'dep' ] = null handler null, node #----------------------------------------------------------------------------------------------------------- @$tour_from_trip = ( registry ) -> return $ ( node, handler ) => reltrip_info = COURSES.reltrip_info_from_abstrip node course = COURSES.registered_course_from_reltrip_info registry, reltrip_info headsign = @normalize_berlin_station_name reltrip_info[ 'headsign' ] gtfs_routes_id = node[ '%gtfs-routes-id' ] route = registry[ '%gtfs' ][ 'routes' ][ gtfs_routes_id ] route_id = route[ 'id' ] #....................................................................................................... tour = '~isa': 'node' '~label': 'tour' 'course-id': reltrip_info[ 'course-id' ] 'route-id': route_id 'headsign': headsign 'offset.hhmmss': reltrip_info[ 'offset.hhmmss' ] 'offset.s': reltrip_info[ 'offset.s' ] #....................................................................................................... handler null, tour #----------------------------------------------------------------------------------------------------------- @$add_tour_id = -> idxs = {} return $ ( node, handler ) => route_id = node[ 'route-id' ] idx = idxs[ route_id ] = ( idxs[ route_id ]?= 0 ) + 1 node[ 'id' ] = "tour/#{route_id}/#{idx}" handler null, node #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- @main = ( registry, handler ) -> # debug '©7u9', 'skipping' # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # return handler null, registry # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t0 = 1 * new Date() # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tasks = [] no_source = [] no_method = [] ok_types = [] #....................................................................................................... for node_type in options[ 'data' ][ 'node-types' ] if node_type not in [ 'agency', 'station', 'route', 'tour', ] # <<<<<<<<<< warn "skipping #{node_type}" # <<<<<<<<<< continue # #..................................................................................................... method_name = "read_#{node_type}_nodes" method = @[ method_name ] unless method? no_method.push "no method to read nodes of type #{rpr node_type}; skipping" continue method = method.bind @ ok_types.push node_type #..................................................................................................... do ( method_name, method ) => tasks.push ( async_handler ) => help "#{badge}/#{method_name}" method registry, ( P... ) => info "#{badge}/#{method_name}" async_handler P... #....................................................................................................... for messages in [ no_source, no_method, ] for message in messages warn message #....................................................................................................... info "reading data for #{ok_types.length} type(s)" info " (#{ok_types.join ', '})" #......................................................................................................... ASYNC.series tasks, ( error ) => throw error if error? t1 = 1 * new Date() # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! urge 'dt:', ( t1 - t0 ) / 1000 # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! handler null, registry #......................................................................................................... return null
185977
############################################################################################################ # njs_util = require 'util' # njs_path = require 'path' # njs_fs = require 'fs' # njs_crypto = require 'crypto' #........................................................................................................... # BAP = require 'coffeenode-bitsnpieces' # TYPES = require 'coffeenode-types' # TEXT = require 'coffeenode-text' TRM = require 'coffeenode-trm' rpr = TRM.rpr.bind TRM badge = 'TIMETABLE/READER' log = TRM.get_logger 'plain', badge info = TRM.get_logger 'info', badge whisper = TRM.get_logger 'whisper', badge alert = TRM.get_logger 'alert', badge debug = TRM.get_logger 'debug', badge warn = TRM.get_logger 'warn', badge help = TRM.get_logger 'help', badge urge = TRM.get_logger 'urge', badge echo = TRM.echo.bind TRM rainbow = TRM.rainbow.bind TRM #........................................................................................................... ASYNC = require 'async' #........................................................................................................... REGISTRY = require './REGISTRY' COURSES = require './COURSES' P = require 'pipedreams' $ = P.$.bind P #........................................................................................................... options = require '../options' DEV = options[ 'mode' ] is 'dev' #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- ### TAINT very Berlin-specific method, shouldnt appear here ### @normalize_berlin_station_name = ( name ) -> name = name.replace /\s+\(Berlin\)(\s+Bus)?$/, '' unless /^(U|S) Olympiastadion/.test name name = name.replace /^(U|S\+U|S)\s+/, '' name = name.replace /^(<NAME>) Bhf\/(.+)$/, '$1 ($2)' name = name.replace /^(Lichtenberg) Bhf\/(.+)$/, '$1 ($2)' name = name.replace /^(<NAME>) Bhf/, '$1' name = name.replace /^(<NAME>) Bhf/, '$1' name = name.replace /^(<NAME>un<NAME>) Bhf/, '$1' name = name.replace /^(<NAME>) Bhf/, '$1' name = name.replace /^(Lichtenberg) Bhf/, '$1' name = name.replace /^(<NAME>\.) Bhf/, '$1' name = name.replace /^(<NAME>) Bhf/, '$1' name = name.replace /^(Stadtmitte) U[26]/, '$1' name = name.replace /str\./g, 'straße' name = name.replace /\s+Str\./g, ' Straße' return name #----------------------------------------------------------------------------------------------------------- @$rn_normalize_station_name = ( key ) -> return $ ( [ record, node, ], handler ) => name = node[ key ] unless name? return handler new Error """ unable to find key #{rpr key} in #{rpr node}""" node[ key ] = @normalize_berlin_station_name name handler null, [ record, node, ] # #----------------------------------------------------------------------------------------------------------- # @$rn_add_n4j_system_properties = ( label ) -> # return $ ( [ record, node, ], handler ) -> # node[ '~isa' ] = 'node' # node[ '~label' ] = label # handler null, [ record, node, ] #----------------------------------------------------------------------------------------------------------- @$remove_gtfs_fields = -> return $ ( node, handler ) -> for name of node delete node[ name ] if /^%gtfs/.test name handler null, node #----------------------------------------------------------------------------------------------------------- @$side_by_side = -> return $ ( node, handler ) -> record = {} record[ name ] = value for name, value of node handler null, [ record, node, ] #----------------------------------------------------------------------------------------------------------- @$rn_one_by_one = -> on_data = ( [ record, node, ]) -> @emit 'data', record @emit 'data', node return P.through on_data, null # #----------------------------------------------------------------------------------------------------------- # @$add_id = -> # idx = 0 # return $ ( node, handler ) -> # id = node[ 'id' ] # label = node[ '~label' ] # return handler new Error "ID already set: #{rpr node}" if id? # return handler new Error "unable to set ID on node without label: #{rpr node}" unless label? # node[ 'id' ] = "#{label}-#{idx}" # idx += 1 # handler null, node #----------------------------------------------------------------------------------------------------------- @$rn_add_ids_etc = ( label ) -> idx = 0 return $ ( [ record, node, ], handler ) -> node[ '~isa' ] = 'node' node[ '~label' ] = label record[ 'node-id' ] = \ node_id = \ node[ 'id' ] = "timetable/#{label}/#{idx}" node[ 'record-id' ] = record[ 'id' ] delete node[ 'gtfs-id' ] delete node[ 'gtfs-type' ] idx += 1 handler null, [ record, node, ] #=========================================================================================================== # AGENCIES #----------------------------------------------------------------------------------------------------------- @read_agency_nodes = ( registry, handler ) -> input = registry.createReadStream keys: no, gte: 'gtfs/agency', lte: 'gtfs/agency\xff' #......................................................................................................... input .pipe @$side_by_side() .pipe @$rn_add_agency_id_etc() .pipe P.$collect_sample 1, ( _, sample ) -> whisper 'agency', sample .pipe @$rn_one_by_one() # .pipe @$remove_gtfs_fields() # .pipe P.$show() .pipe REGISTRY.$register registry .pipe P.$on_end -> handler null #----------------------------------------------------------------------------------------------------------- @$rn_add_agency_id_etc = -> return $ ( [ record, node, ], handler ) -> node[ '~isa' ] = 'node' node[ '~label' ] = 'agency' record[ 'node-id' ] = \ node_id = \ node[ 'id' ] = \ record[ 'id' ].replace /^gtfs\/([^-_]+)[-_]+$/, 'timetable/$1' delete node[ 'gtfs-id' ] node[ 'record-id' ] = record[ 'id' ] delete node[ 'gtfs-type' ] handler null, [ record, node, ] #=========================================================================================================== # STATIONS #----------------------------------------------------------------------------------------------------------- @read_station_nodes = ( registry, handler ) -> ratio = if DEV then 1 / 5000 else 1 input = registry.createReadStream keys: no, gte: 'gtfs/stops', lte: 'gtfs/stops\xff' #......................................................................................................... input .pipe P.$sample ratio, headers: true, seed: 5 # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< .pipe @$side_by_side() .pipe @$rn_normalize_station_name 'name' .pipe @$rn_add_ids_etc 'station' .pipe P.$collect_sample 1, ( _, sample ) -> whisper 'station', sample .pipe @$rn_one_by_one() # .pipe @$remove_gtfs_fields() # .pipe P.$show() .pipe REGISTRY.$register registry .pipe P.$on_end -> handler null #=========================================================================================================== # ROUTES #----------------------------------------------------------------------------------------------------------- @read_route_nodes = ( registry, handler ) -> input = registry.createReadStream keys: no, gte: 'gtfs/routes', lte: 'gtfs/routes\xff' #......................................................................................................... input .pipe @$side_by_side() .pipe @$rn_add_ids_etc 'route' .pipe P.$collect_sample 1, ( _, sample ) -> whisper 'route', sample .pipe @$rn_agency_id_from_gtfs registry .pipe @$rn_one_by_one() # .pipe P.$show() .pipe REGISTRY.$register registry .pipe P.$on_end -> handler null #----------------------------------------------------------------------------------------------------------- @$rn_agency_id_from_gtfs = ( registry ) -> return $ ( [ record, node, ], handler ) -> gtfs_agency_id = node[ 'gtfs-agency-id' ] registry.get "gtfs/agency/#{gtfs_agency_id}", ( error, gtfs_agency_record ) -> return handler error if error? node[ 'agency-id' ] = gtfs_agency_record[ 'node-id' ] delete node[ 'gtfs-agency-id' ] handler null, [ record, node, ] #=========================================================================================================== # COURSES AND TOURS #----------------------------------------------------------------------------------------------------------- @read_tour_nodes = ( registry, handler ) -> ### OBS implies reading courses and halts. ### ratio = if DEV then 1 / 5000 else 1 input = registry.createReadStream keys: no, gte: 'gtfs/trips', lte: 'gtfs/trips\xff' #......................................................................................................... input .pipe @$side_by_side() .pipe P.$sample ratio, headers: true, seed: 5 # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # .pipe @$rn_normalize_station_name 'name' # .pipe @$rn_add_ids_etc 'station' .pipe P.$collect_sample 1, ( _, sample ) -> whisper 'station', sample .pipe @$rn_one_by_one() # .pipe @$remove_gtfs_fields() # .pipe P.$show() # .pipe @$rn_add_n4j_system_properties 'tour' # .pipe @$clean_trip_arr_dep() # .pipe @$tour_from_trip registry # .pipe @$add_tour_id() # .pipe @$remove_gtfs_fields() # .pipe REGISTRY.$register registry .pipe P.$on_end -> handler null #----------------------------------------------------------------------------------------------------------- @$clean_trip_arr_dep = -> ### Replace the first stoptime's arrival and the last stoptime's departure time from the trip. ### return $ ( node, handler ) -> last_idx = node[ '%gtfs-stoptimes' ].length - 1 node[ '%gtfs-stoptimes' ][ 0 ][ 'arr' ] = null node[ '%gtfs-stoptimes' ][ last_idx ][ 'dep' ] = null handler null, node #----------------------------------------------------------------------------------------------------------- @$tour_from_trip = ( registry ) -> return $ ( node, handler ) => reltrip_info = COURSES.reltrip_info_from_abstrip node course = COURSES.registered_course_from_reltrip_info registry, reltrip_info headsign = @normalize_berlin_station_name reltrip_info[ 'headsign' ] gtfs_routes_id = node[ '%gtfs-routes-id' ] route = registry[ '%gtfs' ][ 'routes' ][ gtfs_routes_id ] route_id = route[ 'id' ] #....................................................................................................... tour = '~isa': 'node' '~label': 'tour' 'course-id': reltrip_info[ 'course-id' ] 'route-id': route_id 'headsign': headsign 'offset.hhmmss': reltrip_info[ 'offset.hhmmss' ] 'offset.s': reltrip_info[ 'offset.s' ] #....................................................................................................... handler null, tour #----------------------------------------------------------------------------------------------------------- @$add_tour_id = -> idxs = {} return $ ( node, handler ) => route_id = node[ 'route-id' ] idx = idxs[ route_id ] = ( idxs[ route_id ]?= 0 ) + 1 node[ 'id' ] = "tour/#{route_id}/#{idx}" handler null, node #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- @main = ( registry, handler ) -> # debug '©7u9', 'skipping' # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # return handler null, registry # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t0 = 1 * new Date() # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tasks = [] no_source = [] no_method = [] ok_types = [] #....................................................................................................... for node_type in options[ 'data' ][ 'node-types' ] if node_type not in [ 'agency', 'station', 'route', 'tour', ] # <<<<<<<<<< warn "skipping #{node_type}" # <<<<<<<<<< continue # #..................................................................................................... method_name = "read_#{node_type}_nodes" method = @[ method_name ] unless method? no_method.push "no method to read nodes of type #{rpr node_type}; skipping" continue method = method.bind @ ok_types.push node_type #..................................................................................................... do ( method_name, method ) => tasks.push ( async_handler ) => help "#{badge}/#{method_name}" method registry, ( P... ) => info "#{badge}/#{method_name}" async_handler P... #....................................................................................................... for messages in [ no_source, no_method, ] for message in messages warn message #....................................................................................................... info "reading data for #{ok_types.length} type(s)" info " (#{ok_types.join ', '})" #......................................................................................................... ASYNC.series tasks, ( error ) => throw error if error? t1 = 1 * new Date() # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! urge 'dt:', ( t1 - t0 ) / 1000 # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! handler null, registry #......................................................................................................... return null
true
############################################################################################################ # njs_util = require 'util' # njs_path = require 'path' # njs_fs = require 'fs' # njs_crypto = require 'crypto' #........................................................................................................... # BAP = require 'coffeenode-bitsnpieces' # TYPES = require 'coffeenode-types' # TEXT = require 'coffeenode-text' TRM = require 'coffeenode-trm' rpr = TRM.rpr.bind TRM badge = 'TIMETABLE/READER' log = TRM.get_logger 'plain', badge info = TRM.get_logger 'info', badge whisper = TRM.get_logger 'whisper', badge alert = TRM.get_logger 'alert', badge debug = TRM.get_logger 'debug', badge warn = TRM.get_logger 'warn', badge help = TRM.get_logger 'help', badge urge = TRM.get_logger 'urge', badge echo = TRM.echo.bind TRM rainbow = TRM.rainbow.bind TRM #........................................................................................................... ASYNC = require 'async' #........................................................................................................... REGISTRY = require './REGISTRY' COURSES = require './COURSES' P = require 'pipedreams' $ = P.$.bind P #........................................................................................................... options = require '../options' DEV = options[ 'mode' ] is 'dev' #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- ### TAINT very Berlin-specific method, shouldnt appear here ### @normalize_berlin_station_name = ( name ) -> name = name.replace /\s+\(Berlin\)(\s+Bus)?$/, '' unless /^(U|S) Olympiastadion/.test name name = name.replace /^(U|S\+U|S)\s+/, '' name = name.replace /^(PI:NAME:<NAME>END_PI) Bhf\/(.+)$/, '$1 ($2)' name = name.replace /^(Lichtenberg) Bhf\/(.+)$/, '$1 ($2)' name = name.replace /^(PI:NAME:<NAME>END_PI) Bhf/, '$1' name = name.replace /^(PI:NAME:<NAME>END_PI) Bhf/, '$1' name = name.replace /^(PI:NAME:<NAME>END_PIunPI:NAME:<NAME>END_PI) Bhf/, '$1' name = name.replace /^(PI:NAME:<NAME>END_PI) Bhf/, '$1' name = name.replace /^(Lichtenberg) Bhf/, '$1' name = name.replace /^(PI:NAME:<NAME>END_PI\.) Bhf/, '$1' name = name.replace /^(PI:NAME:<NAME>END_PI) Bhf/, '$1' name = name.replace /^(Stadtmitte) U[26]/, '$1' name = name.replace /str\./g, 'straße' name = name.replace /\s+Str\./g, ' Straße' return name #----------------------------------------------------------------------------------------------------------- @$rn_normalize_station_name = ( key ) -> return $ ( [ record, node, ], handler ) => name = node[ key ] unless name? return handler new Error """ unable to find key #{rpr key} in #{rpr node}""" node[ key ] = @normalize_berlin_station_name name handler null, [ record, node, ] # #----------------------------------------------------------------------------------------------------------- # @$rn_add_n4j_system_properties = ( label ) -> # return $ ( [ record, node, ], handler ) -> # node[ '~isa' ] = 'node' # node[ '~label' ] = label # handler null, [ record, node, ] #----------------------------------------------------------------------------------------------------------- @$remove_gtfs_fields = -> return $ ( node, handler ) -> for name of node delete node[ name ] if /^%gtfs/.test name handler null, node #----------------------------------------------------------------------------------------------------------- @$side_by_side = -> return $ ( node, handler ) -> record = {} record[ name ] = value for name, value of node handler null, [ record, node, ] #----------------------------------------------------------------------------------------------------------- @$rn_one_by_one = -> on_data = ( [ record, node, ]) -> @emit 'data', record @emit 'data', node return P.through on_data, null # #----------------------------------------------------------------------------------------------------------- # @$add_id = -> # idx = 0 # return $ ( node, handler ) -> # id = node[ 'id' ] # label = node[ '~label' ] # return handler new Error "ID already set: #{rpr node}" if id? # return handler new Error "unable to set ID on node without label: #{rpr node}" unless label? # node[ 'id' ] = "#{label}-#{idx}" # idx += 1 # handler null, node #----------------------------------------------------------------------------------------------------------- @$rn_add_ids_etc = ( label ) -> idx = 0 return $ ( [ record, node, ], handler ) -> node[ '~isa' ] = 'node' node[ '~label' ] = label record[ 'node-id' ] = \ node_id = \ node[ 'id' ] = "timetable/#{label}/#{idx}" node[ 'record-id' ] = record[ 'id' ] delete node[ 'gtfs-id' ] delete node[ 'gtfs-type' ] idx += 1 handler null, [ record, node, ] #=========================================================================================================== # AGENCIES #----------------------------------------------------------------------------------------------------------- @read_agency_nodes = ( registry, handler ) -> input = registry.createReadStream keys: no, gte: 'gtfs/agency', lte: 'gtfs/agency\xff' #......................................................................................................... input .pipe @$side_by_side() .pipe @$rn_add_agency_id_etc() .pipe P.$collect_sample 1, ( _, sample ) -> whisper 'agency', sample .pipe @$rn_one_by_one() # .pipe @$remove_gtfs_fields() # .pipe P.$show() .pipe REGISTRY.$register registry .pipe P.$on_end -> handler null #----------------------------------------------------------------------------------------------------------- @$rn_add_agency_id_etc = -> return $ ( [ record, node, ], handler ) -> node[ '~isa' ] = 'node' node[ '~label' ] = 'agency' record[ 'node-id' ] = \ node_id = \ node[ 'id' ] = \ record[ 'id' ].replace /^gtfs\/([^-_]+)[-_]+$/, 'timetable/$1' delete node[ 'gtfs-id' ] node[ 'record-id' ] = record[ 'id' ] delete node[ 'gtfs-type' ] handler null, [ record, node, ] #=========================================================================================================== # STATIONS #----------------------------------------------------------------------------------------------------------- @read_station_nodes = ( registry, handler ) -> ratio = if DEV then 1 / 5000 else 1 input = registry.createReadStream keys: no, gte: 'gtfs/stops', lte: 'gtfs/stops\xff' #......................................................................................................... input .pipe P.$sample ratio, headers: true, seed: 5 # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< .pipe @$side_by_side() .pipe @$rn_normalize_station_name 'name' .pipe @$rn_add_ids_etc 'station' .pipe P.$collect_sample 1, ( _, sample ) -> whisper 'station', sample .pipe @$rn_one_by_one() # .pipe @$remove_gtfs_fields() # .pipe P.$show() .pipe REGISTRY.$register registry .pipe P.$on_end -> handler null #=========================================================================================================== # ROUTES #----------------------------------------------------------------------------------------------------------- @read_route_nodes = ( registry, handler ) -> input = registry.createReadStream keys: no, gte: 'gtfs/routes', lte: 'gtfs/routes\xff' #......................................................................................................... input .pipe @$side_by_side() .pipe @$rn_add_ids_etc 'route' .pipe P.$collect_sample 1, ( _, sample ) -> whisper 'route', sample .pipe @$rn_agency_id_from_gtfs registry .pipe @$rn_one_by_one() # .pipe P.$show() .pipe REGISTRY.$register registry .pipe P.$on_end -> handler null #----------------------------------------------------------------------------------------------------------- @$rn_agency_id_from_gtfs = ( registry ) -> return $ ( [ record, node, ], handler ) -> gtfs_agency_id = node[ 'gtfs-agency-id' ] registry.get "gtfs/agency/#{gtfs_agency_id}", ( error, gtfs_agency_record ) -> return handler error if error? node[ 'agency-id' ] = gtfs_agency_record[ 'node-id' ] delete node[ 'gtfs-agency-id' ] handler null, [ record, node, ] #=========================================================================================================== # COURSES AND TOURS #----------------------------------------------------------------------------------------------------------- @read_tour_nodes = ( registry, handler ) -> ### OBS implies reading courses and halts. ### ratio = if DEV then 1 / 5000 else 1 input = registry.createReadStream keys: no, gte: 'gtfs/trips', lte: 'gtfs/trips\xff' #......................................................................................................... input .pipe @$side_by_side() .pipe P.$sample ratio, headers: true, seed: 5 # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< # .pipe @$rn_normalize_station_name 'name' # .pipe @$rn_add_ids_etc 'station' .pipe P.$collect_sample 1, ( _, sample ) -> whisper 'station', sample .pipe @$rn_one_by_one() # .pipe @$remove_gtfs_fields() # .pipe P.$show() # .pipe @$rn_add_n4j_system_properties 'tour' # .pipe @$clean_trip_arr_dep() # .pipe @$tour_from_trip registry # .pipe @$add_tour_id() # .pipe @$remove_gtfs_fields() # .pipe REGISTRY.$register registry .pipe P.$on_end -> handler null #----------------------------------------------------------------------------------------------------------- @$clean_trip_arr_dep = -> ### Replace the first stoptime's arrival and the last stoptime's departure time from the trip. ### return $ ( node, handler ) -> last_idx = node[ '%gtfs-stoptimes' ].length - 1 node[ '%gtfs-stoptimes' ][ 0 ][ 'arr' ] = null node[ '%gtfs-stoptimes' ][ last_idx ][ 'dep' ] = null handler null, node #----------------------------------------------------------------------------------------------------------- @$tour_from_trip = ( registry ) -> return $ ( node, handler ) => reltrip_info = COURSES.reltrip_info_from_abstrip node course = COURSES.registered_course_from_reltrip_info registry, reltrip_info headsign = @normalize_berlin_station_name reltrip_info[ 'headsign' ] gtfs_routes_id = node[ '%gtfs-routes-id' ] route = registry[ '%gtfs' ][ 'routes' ][ gtfs_routes_id ] route_id = route[ 'id' ] #....................................................................................................... tour = '~isa': 'node' '~label': 'tour' 'course-id': reltrip_info[ 'course-id' ] 'route-id': route_id 'headsign': headsign 'offset.hhmmss': reltrip_info[ 'offset.hhmmss' ] 'offset.s': reltrip_info[ 'offset.s' ] #....................................................................................................... handler null, tour #----------------------------------------------------------------------------------------------------------- @$add_tour_id = -> idxs = {} return $ ( node, handler ) => route_id = node[ 'route-id' ] idx = idxs[ route_id ] = ( idxs[ route_id ]?= 0 ) + 1 node[ 'id' ] = "tour/#{route_id}/#{idx}" handler null, node #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- @main = ( registry, handler ) -> # debug '©7u9', 'skipping' # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # return handler null, registry # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t0 = 1 * new Date() # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tasks = [] no_source = [] no_method = [] ok_types = [] #....................................................................................................... for node_type in options[ 'data' ][ 'node-types' ] if node_type not in [ 'agency', 'station', 'route', 'tour', ] # <<<<<<<<<< warn "skipping #{node_type}" # <<<<<<<<<< continue # #..................................................................................................... method_name = "read_#{node_type}_nodes" method = @[ method_name ] unless method? no_method.push "no method to read nodes of type #{rpr node_type}; skipping" continue method = method.bind @ ok_types.push node_type #..................................................................................................... do ( method_name, method ) => tasks.push ( async_handler ) => help "#{badge}/#{method_name}" method registry, ( P... ) => info "#{badge}/#{method_name}" async_handler P... #....................................................................................................... for messages in [ no_source, no_method, ] for message in messages warn message #....................................................................................................... info "reading data for #{ok_types.length} type(s)" info " (#{ok_types.join ', '})" #......................................................................................................... ASYNC.series tasks, ( error ) => throw error if error? t1 = 1 * new Date() # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! urge 'dt:', ( t1 - t0 ) / 1000 # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! handler null, registry #......................................................................................................... return null
[ { "context": "M-based Routing\n# Based on http://goo.gl/EUTi53 by Paul Irish\n#\n# Only fires on body classes that match. If a b", "end": 142, "score": 0.9997883439064026, "start": 132, "tag": "NAME", "value": "Paul Irish" } ]
assets/coffee/main.coffee
christopherbruce/christopher-sage
0
### ======================================================================== # DOM-based Routing # Based on http://goo.gl/EUTi53 by Paul Irish # # Only fires on body classes that match. If a body class contains a dash, # replace the dash with an underscore when adding it to the object below. # # .noConflict() # The routing is enclosed within an anonymous function so that you can # always reference jQuery with $, even when in .noConflict() mode. # # Google CDN, Latest jQuery # To use the default WordPress version of jQuery, go to lib/config.php and # remove or comment out: add_theme_support('jquery-cdn'); # ======================================================================== ### (($) -> # Use this variable to set up the common and page specific functions. If you # rename this variable, you will also need to rename the namespace below. Sage = 'common': init: -> # JavaScript to be fired on all pages return finalize: -> # JavaScript to be fired on all pages, after page specific JS is fired return 'home': init: -> # JavaScript to be fired on the home page return finalize: -> # JavaScript to be fired on the home page, after the init JS return 'about_us': init: -> # JavaScript to be fired on the about us page return # The routing fires all common scripts, followed by the page specific scripts. # Add additional events for more control over timing e.g. a finalize event UTIL = fire: (func, funcname, args) -> fire = undefined namespace = Sage funcname = if funcname == undefined then 'init' else funcname fire = func != '' fire = fire and namespace[func] fire = fire and typeof namespace[func][funcname] == 'function' if fire namespace[func][funcname] args return loadEvents: -> # Fire common init JS UTIL.fire 'common' # Fire page-specific init JS, and then finalize JS $.each document.body.className.replace(/-/g, '_').split(/\s+/), (i, classnm) -> UTIL.fire classnm UTIL.fire classnm, 'finalize' return # Fire common finalize JS UTIL.fire 'common', 'finalize' return # Load Events $(document).ready UTIL.loadEvents return ) jQuery # Fully reference jQuery after this point.
171863
### ======================================================================== # DOM-based Routing # Based on http://goo.gl/EUTi53 by <NAME> # # Only fires on body classes that match. If a body class contains a dash, # replace the dash with an underscore when adding it to the object below. # # .noConflict() # The routing is enclosed within an anonymous function so that you can # always reference jQuery with $, even when in .noConflict() mode. # # Google CDN, Latest jQuery # To use the default WordPress version of jQuery, go to lib/config.php and # remove or comment out: add_theme_support('jquery-cdn'); # ======================================================================== ### (($) -> # Use this variable to set up the common and page specific functions. If you # rename this variable, you will also need to rename the namespace below. Sage = 'common': init: -> # JavaScript to be fired on all pages return finalize: -> # JavaScript to be fired on all pages, after page specific JS is fired return 'home': init: -> # JavaScript to be fired on the home page return finalize: -> # JavaScript to be fired on the home page, after the init JS return 'about_us': init: -> # JavaScript to be fired on the about us page return # The routing fires all common scripts, followed by the page specific scripts. # Add additional events for more control over timing e.g. a finalize event UTIL = fire: (func, funcname, args) -> fire = undefined namespace = Sage funcname = if funcname == undefined then 'init' else funcname fire = func != '' fire = fire and namespace[func] fire = fire and typeof namespace[func][funcname] == 'function' if fire namespace[func][funcname] args return loadEvents: -> # Fire common init JS UTIL.fire 'common' # Fire page-specific init JS, and then finalize JS $.each document.body.className.replace(/-/g, '_').split(/\s+/), (i, classnm) -> UTIL.fire classnm UTIL.fire classnm, 'finalize' return # Fire common finalize JS UTIL.fire 'common', 'finalize' return # Load Events $(document).ready UTIL.loadEvents return ) jQuery # Fully reference jQuery after this point.
true
### ======================================================================== # DOM-based Routing # Based on http://goo.gl/EUTi53 by PI:NAME:<NAME>END_PI # # Only fires on body classes that match. If a body class contains a dash, # replace the dash with an underscore when adding it to the object below. # # .noConflict() # The routing is enclosed within an anonymous function so that you can # always reference jQuery with $, even when in .noConflict() mode. # # Google CDN, Latest jQuery # To use the default WordPress version of jQuery, go to lib/config.php and # remove or comment out: add_theme_support('jquery-cdn'); # ======================================================================== ### (($) -> # Use this variable to set up the common and page specific functions. If you # rename this variable, you will also need to rename the namespace below. Sage = 'common': init: -> # JavaScript to be fired on all pages return finalize: -> # JavaScript to be fired on all pages, after page specific JS is fired return 'home': init: -> # JavaScript to be fired on the home page return finalize: -> # JavaScript to be fired on the home page, after the init JS return 'about_us': init: -> # JavaScript to be fired on the about us page return # The routing fires all common scripts, followed by the page specific scripts. # Add additional events for more control over timing e.g. a finalize event UTIL = fire: (func, funcname, args) -> fire = undefined namespace = Sage funcname = if funcname == undefined then 'init' else funcname fire = func != '' fire = fire and namespace[func] fire = fire and typeof namespace[func][funcname] == 'function' if fire namespace[func][funcname] args return loadEvents: -> # Fire common init JS UTIL.fire 'common' # Fire page-specific init JS, and then finalize JS $.each document.body.className.replace(/-/g, '_').split(/\s+/), (i, classnm) -> UTIL.fire classnm UTIL.fire classnm, 'finalize' return # Fire common finalize JS UTIL.fire 'common', 'finalize' return # Load Events $(document).ready UTIL.loadEvents return ) jQuery # Fully reference jQuery after this point.
[ { "context": "overview Tests for callback return rule.\n# @author Jamund Ferguson\n###\n'use strict'\n\n#------------------------------", "end": 78, "score": 0.9998418092727661, "start": 63, "tag": "NAME", "value": "Jamund Ferguson" }, { "context": " ,\n # allow object methods (ht...
src/tests/rules/callback-return.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for callback return rule. # @author Jamund Ferguson ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/callback-return' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'callback-return', rule, valid: [ # callbacks inside of functions should return ''' (err) -> if err return callback(err) ''' ''' (err) -> if err return callback err callback() ''' ''' (err) -> if err return ### confusing comment ### callback(err) callback() ''' ''' (err) -> if err callback() return ''' ''' (err) -> if err log() callback() return ''' ''' (err) -> if err callback() return return callback() ''' ''' (err) -> if err return callback() else return callback() ''' ''' (err) -> if err return callback() else if x return callback() ''' ''' (cb) -> cb and cb() ''' ''' (next) -> typeof next isnt 'undefined' and next() ''' ''' (next) -> return next() if typeof next is 'function' ''' ''' -> switch x when 'a' return next() ''' ''' -> while x return next() ''' ''' (err) -> if err obj.method err ''' # callback() all you want outside of a function 'callback()' ''' callback() callback() ''' ''' while x move() ''' ''' if x callback() ''' # arrow functions ''' x = (err) => if err callback() return ''' ''' x = (err) => callback(err) ''' ''' x = (err) => setTimeout => callback() ''' # classes ''' class x horse: -> callback() ''' ''' class x horse: -> if err return callback() callback() ''' , # options (only warns with the correct callback name) code: ''' (err) -> if err callback err ''' options: [['cb']] , code: ''' (err) -> if err callback err next() ''' options: [['cb', 'next']] , code: ''' a = (err) -> if err then return next err else callback() ''' options: [['cb', 'next']] , # allow object methods (https://github.com/eslint/eslint/issues/4711) code: ''' (err) -> if err return obj.method err ''' options: [['obj.method']] , code: ''' (err) -> if err return obj.prop.method err ''' options: [['obj.prop.method']] , code: ''' (err) -> if err return obj.prop.method err otherObj.prop.method() ''' options: [['obj.prop.method', 'otherObj.prop.method']] , code: ''' (err) -> if err then callback err ''' options: [['obj.method']] , code: ''' (err) -> otherObj.method err if err ''' options: [['obj.method']] , code: ''' (err) -> if err #comment return obj.method(err) ''' options: [['obj.method']] , code: ''' (err) -> if err return obj.method err #comment ''' options: [['obj.method']] , code: ''' (err) -> if err return obj.method err ###comment### ''' options: [['obj.method']] , # only warns if object of MemberExpression is an Identifier code: ''' (err) -> if err obj().method err ''' options: [['obj().method']] , code: ''' (err) -> if err obj.prop().method err ''' options: [['obj.prop().method']] , code: ''' (err) -> if (err) then obj().prop.method(err) ''' options: [['obj().prop.method']] , # does not warn if object of MemberExpression is invoked code: ''' (err) -> if (err) then obj().method(err) ''' options: [['obj.method']] , code: ''' (err) -> if err obj().method(err) obj.method() ''' options: [['obj.method']] , # known bad examples that we know we are ignoring ''' (err) -> if err setTimeout callback, 0 callback() ''' # callback() called twice ''' (err) -> if err process.nextTick (err) -> callback() callback() ''' # callback() called twice # implicit returns ''' (err) -> if err callback(err) ''' ] invalid: [ code: ''' (err) -> if err callback err null ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (callback) -> if typeof callback isnt 'undefined' callback() null ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (callback) -> if err callback() horse && horse() ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' x = x: (err) -> if err callback err null ''' errors: [ messageId: 'missingReturn' line: 4 column: 7 nodeType: 'CallExpression' ] , code: ''' (err) -> if err log() callback err null ''' errors: [ messageId: 'missingReturn' line: 4 column: 5 nodeType: 'CallExpression' ] , code: ''' x = { x: (err) -> if err callback && callback(err) } ''' errors: [ messageId: 'missingReturn' line: 4 column: 19 nodeType: 'CallExpression' ] , code: ''' (err) -> callback(err) callback() ''' errors: [ messageId: 'missingReturn' line: 2 column: 3 nodeType: 'CallExpression' ] , code: ''' (err) -> callback(err) horse() ''' errors: [ messageId: 'missingReturn' line: 2 column: 3 nodeType: 'CallExpression' ] , code: ''' (err) -> if err callback(err) horse() return ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err callback(err) else if x callback(err) return null ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if (err) return callback() else if (abc) callback() else return callback() null ''' errors: [ messageId: 'missingReturn' line: 5 column: 5 nodeType: 'CallExpression' ] , code: ''' class x horse: -> if err callback() callback() ''' errors: [ messageId: 'missingReturn' line: 4 column: 7 nodeType: 'CallExpression' ] , # generally good behavior which we must not allow to keep the rule simple code: ''' (err) -> if err callback() else callback() null ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' , messageId: 'missingReturn' line: 5 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err return callback() else callback() null ''' errors: [ messageId: 'missingReturn' line: 5 column: 5 nodeType: 'CallExpression' ] , code: ''' -> switch x when 'horse' callback() null ''' errors: [ messageId: 'missingReturn' line: 4 column: 7 nodeType: 'CallExpression' ] , code: ''' a = -> switch x when 'horse' move() null ''' options: [['move']] errors: [ messageId: 'missingReturn' line: 4 column: 7 nodeType: 'CallExpression' ] , # loops code: ''' x = -> while x move() null ''' options: [['move']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err obj.method err null ''' options: [['obj.method']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> obj.prop.method err if err null ''' options: [['obj.prop.method']] errors: [ messageId: 'missingReturn' line: 2 column: 3 nodeType: 'CallExpression' ] , code: ''' (err) -> if err obj.prop.method err otherObj.prop.method() ''' options: [['obj.prop.method', 'otherObj.prop.method']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if (err) #comment obj.method err null ''' options: [['obj.method']] errors: [ messageId: 'missingReturn' line: 4 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err obj.method err ###comment### null ''' options: [['obj.method']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err obj.method err #comment null ''' options: [['obj.method']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] ]
147442
###* # @fileoverview Tests for callback return rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/callback-return' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'callback-return', rule, valid: [ # callbacks inside of functions should return ''' (err) -> if err return callback(err) ''' ''' (err) -> if err return callback err callback() ''' ''' (err) -> if err return ### confusing comment ### callback(err) callback() ''' ''' (err) -> if err callback() return ''' ''' (err) -> if err log() callback() return ''' ''' (err) -> if err callback() return return callback() ''' ''' (err) -> if err return callback() else return callback() ''' ''' (err) -> if err return callback() else if x return callback() ''' ''' (cb) -> cb and cb() ''' ''' (next) -> typeof next isnt 'undefined' and next() ''' ''' (next) -> return next() if typeof next is 'function' ''' ''' -> switch x when 'a' return next() ''' ''' -> while x return next() ''' ''' (err) -> if err obj.method err ''' # callback() all you want outside of a function 'callback()' ''' callback() callback() ''' ''' while x move() ''' ''' if x callback() ''' # arrow functions ''' x = (err) => if err callback() return ''' ''' x = (err) => callback(err) ''' ''' x = (err) => setTimeout => callback() ''' # classes ''' class x horse: -> callback() ''' ''' class x horse: -> if err return callback() callback() ''' , # options (only warns with the correct callback name) code: ''' (err) -> if err callback err ''' options: [['cb']] , code: ''' (err) -> if err callback err next() ''' options: [['cb', 'next']] , code: ''' a = (err) -> if err then return next err else callback() ''' options: [['cb', 'next']] , # allow object methods (https://github.com/eslint/eslint/issues/4711) code: ''' (err) -> if err return obj.method err ''' options: [['obj.method']] , code: ''' (err) -> if err return obj.prop.method err ''' options: [['obj.prop.method']] , code: ''' (err) -> if err return obj.prop.method err otherObj.prop.method() ''' options: [['obj.prop.method', 'otherObj.prop.method']] , code: ''' (err) -> if err then callback err ''' options: [['obj.method']] , code: ''' (err) -> otherObj.method err if err ''' options: [['obj.method']] , code: ''' (err) -> if err #comment return obj.method(err) ''' options: [['obj.method']] , code: ''' (err) -> if err return obj.method err #comment ''' options: [['obj.method']] , code: ''' (err) -> if err return obj.method err ###comment### ''' options: [['obj.method']] , # only warns if object of MemberExpression is an Identifier code: ''' (err) -> if err obj().method err ''' options: [['obj().method']] , code: ''' (err) -> if err obj.prop().method err ''' options: [['obj.prop().method']] , code: ''' (err) -> if (err) then obj().prop.method(err) ''' options: [['obj().prop.method']] , # does not warn if object of MemberExpression is invoked code: ''' (err) -> if (err) then obj().method(err) ''' options: [['obj.method']] , code: ''' (err) -> if err obj().method(err) obj.method() ''' options: [['obj.method']] , # known bad examples that we know we are ignoring ''' (err) -> if err setTimeout callback, 0 callback() ''' # callback() called twice ''' (err) -> if err process.nextTick (err) -> callback() callback() ''' # callback() called twice # implicit returns ''' (err) -> if err callback(err) ''' ] invalid: [ code: ''' (err) -> if err callback err null ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (callback) -> if typeof callback isnt 'undefined' callback() null ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (callback) -> if err callback() horse && horse() ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' x = x: (err) -> if err callback err null ''' errors: [ messageId: 'missingReturn' line: 4 column: 7 nodeType: 'CallExpression' ] , code: ''' (err) -> if err log() callback err null ''' errors: [ messageId: 'missingReturn' line: 4 column: 5 nodeType: 'CallExpression' ] , code: ''' x = { x: (err) -> if err callback && callback(err) } ''' errors: [ messageId: 'missingReturn' line: 4 column: 19 nodeType: 'CallExpression' ] , code: ''' (err) -> callback(err) callback() ''' errors: [ messageId: 'missingReturn' line: 2 column: 3 nodeType: 'CallExpression' ] , code: ''' (err) -> callback(err) horse() ''' errors: [ messageId: 'missingReturn' line: 2 column: 3 nodeType: 'CallExpression' ] , code: ''' (err) -> if err callback(err) horse() return ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err callback(err) else if x callback(err) return null ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if (err) return callback() else if (abc) callback() else return callback() null ''' errors: [ messageId: 'missingReturn' line: 5 column: 5 nodeType: 'CallExpression' ] , code: ''' class x horse: -> if err callback() callback() ''' errors: [ messageId: 'missingReturn' line: 4 column: 7 nodeType: 'CallExpression' ] , # generally good behavior which we must not allow to keep the rule simple code: ''' (err) -> if err callback() else callback() null ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' , messageId: 'missingReturn' line: 5 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err return callback() else callback() null ''' errors: [ messageId: 'missingReturn' line: 5 column: 5 nodeType: 'CallExpression' ] , code: ''' -> switch x when 'horse' callback() null ''' errors: [ messageId: 'missingReturn' line: 4 column: 7 nodeType: 'CallExpression' ] , code: ''' a = -> switch x when 'horse' move() null ''' options: [['move']] errors: [ messageId: 'missingReturn' line: 4 column: 7 nodeType: 'CallExpression' ] , # loops code: ''' x = -> while x move() null ''' options: [['move']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err obj.method err null ''' options: [['obj.method']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> obj.prop.method err if err null ''' options: [['obj.prop.method']] errors: [ messageId: 'missingReturn' line: 2 column: 3 nodeType: 'CallExpression' ] , code: ''' (err) -> if err obj.prop.method err otherObj.prop.method() ''' options: [['obj.prop.method', 'otherObj.prop.method']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if (err) #comment obj.method err null ''' options: [['obj.method']] errors: [ messageId: 'missingReturn' line: 4 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err obj.method err ###comment### null ''' options: [['obj.method']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err obj.method err #comment null ''' options: [['obj.method']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] ]
true
###* # @fileoverview Tests for callback return rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/callback-return' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'callback-return', rule, valid: [ # callbacks inside of functions should return ''' (err) -> if err return callback(err) ''' ''' (err) -> if err return callback err callback() ''' ''' (err) -> if err return ### confusing comment ### callback(err) callback() ''' ''' (err) -> if err callback() return ''' ''' (err) -> if err log() callback() return ''' ''' (err) -> if err callback() return return callback() ''' ''' (err) -> if err return callback() else return callback() ''' ''' (err) -> if err return callback() else if x return callback() ''' ''' (cb) -> cb and cb() ''' ''' (next) -> typeof next isnt 'undefined' and next() ''' ''' (next) -> return next() if typeof next is 'function' ''' ''' -> switch x when 'a' return next() ''' ''' -> while x return next() ''' ''' (err) -> if err obj.method err ''' # callback() all you want outside of a function 'callback()' ''' callback() callback() ''' ''' while x move() ''' ''' if x callback() ''' # arrow functions ''' x = (err) => if err callback() return ''' ''' x = (err) => callback(err) ''' ''' x = (err) => setTimeout => callback() ''' # classes ''' class x horse: -> callback() ''' ''' class x horse: -> if err return callback() callback() ''' , # options (only warns with the correct callback name) code: ''' (err) -> if err callback err ''' options: [['cb']] , code: ''' (err) -> if err callback err next() ''' options: [['cb', 'next']] , code: ''' a = (err) -> if err then return next err else callback() ''' options: [['cb', 'next']] , # allow object methods (https://github.com/eslint/eslint/issues/4711) code: ''' (err) -> if err return obj.method err ''' options: [['obj.method']] , code: ''' (err) -> if err return obj.prop.method err ''' options: [['obj.prop.method']] , code: ''' (err) -> if err return obj.prop.method err otherObj.prop.method() ''' options: [['obj.prop.method', 'otherObj.prop.method']] , code: ''' (err) -> if err then callback err ''' options: [['obj.method']] , code: ''' (err) -> otherObj.method err if err ''' options: [['obj.method']] , code: ''' (err) -> if err #comment return obj.method(err) ''' options: [['obj.method']] , code: ''' (err) -> if err return obj.method err #comment ''' options: [['obj.method']] , code: ''' (err) -> if err return obj.method err ###comment### ''' options: [['obj.method']] , # only warns if object of MemberExpression is an Identifier code: ''' (err) -> if err obj().method err ''' options: [['obj().method']] , code: ''' (err) -> if err obj.prop().method err ''' options: [['obj.prop().method']] , code: ''' (err) -> if (err) then obj().prop.method(err) ''' options: [['obj().prop.method']] , # does not warn if object of MemberExpression is invoked code: ''' (err) -> if (err) then obj().method(err) ''' options: [['obj.method']] , code: ''' (err) -> if err obj().method(err) obj.method() ''' options: [['obj.method']] , # known bad examples that we know we are ignoring ''' (err) -> if err setTimeout callback, 0 callback() ''' # callback() called twice ''' (err) -> if err process.nextTick (err) -> callback() callback() ''' # callback() called twice # implicit returns ''' (err) -> if err callback(err) ''' ] invalid: [ code: ''' (err) -> if err callback err null ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (callback) -> if typeof callback isnt 'undefined' callback() null ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (callback) -> if err callback() horse && horse() ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' x = x: (err) -> if err callback err null ''' errors: [ messageId: 'missingReturn' line: 4 column: 7 nodeType: 'CallExpression' ] , code: ''' (err) -> if err log() callback err null ''' errors: [ messageId: 'missingReturn' line: 4 column: 5 nodeType: 'CallExpression' ] , code: ''' x = { x: (err) -> if err callback && callback(err) } ''' errors: [ messageId: 'missingReturn' line: 4 column: 19 nodeType: 'CallExpression' ] , code: ''' (err) -> callback(err) callback() ''' errors: [ messageId: 'missingReturn' line: 2 column: 3 nodeType: 'CallExpression' ] , code: ''' (err) -> callback(err) horse() ''' errors: [ messageId: 'missingReturn' line: 2 column: 3 nodeType: 'CallExpression' ] , code: ''' (err) -> if err callback(err) horse() return ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err callback(err) else if x callback(err) return null ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if (err) return callback() else if (abc) callback() else return callback() null ''' errors: [ messageId: 'missingReturn' line: 5 column: 5 nodeType: 'CallExpression' ] , code: ''' class x horse: -> if err callback() callback() ''' errors: [ messageId: 'missingReturn' line: 4 column: 7 nodeType: 'CallExpression' ] , # generally good behavior which we must not allow to keep the rule simple code: ''' (err) -> if err callback() else callback() null ''' errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' , messageId: 'missingReturn' line: 5 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err return callback() else callback() null ''' errors: [ messageId: 'missingReturn' line: 5 column: 5 nodeType: 'CallExpression' ] , code: ''' -> switch x when 'horse' callback() null ''' errors: [ messageId: 'missingReturn' line: 4 column: 7 nodeType: 'CallExpression' ] , code: ''' a = -> switch x when 'horse' move() null ''' options: [['move']] errors: [ messageId: 'missingReturn' line: 4 column: 7 nodeType: 'CallExpression' ] , # loops code: ''' x = -> while x move() null ''' options: [['move']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err obj.method err null ''' options: [['obj.method']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> obj.prop.method err if err null ''' options: [['obj.prop.method']] errors: [ messageId: 'missingReturn' line: 2 column: 3 nodeType: 'CallExpression' ] , code: ''' (err) -> if err obj.prop.method err otherObj.prop.method() ''' options: [['obj.prop.method', 'otherObj.prop.method']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if (err) #comment obj.method err null ''' options: [['obj.method']] errors: [ messageId: 'missingReturn' line: 4 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err obj.method err ###comment### null ''' options: [['obj.method']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] , code: ''' (err) -> if err obj.method err #comment null ''' options: [['obj.method']] errors: [ messageId: 'missingReturn' line: 3 column: 5 nodeType: 'CallExpression' ] ]
[ { "context": " ','\nordCards = 's,sw,w,nw,n,ne,e,se'.split ','\n\n# Zonard\nclass @Zonard extends Backbone.View\n classN", "end": 87, "score": 0.5378297567367554, "start": 86, "tag": "NAME", "value": "Z" } ]
assets/js/Zonard.coffee
af83/Zonard
0
Cards = 'n,s,e,w,nw,ne,se,sw'.split ',' ordCards = 's,sw,w,nw,n,ne,e,se'.split ',' # Zonard class @Zonard extends Backbone.View className: 'zonard' # @params options {object} # @params options.box {left, top, width, height, rotate} # @params options.workspace {div element} # @params options.centralHandle {bool} (optional) # @params options.preserveRatio {bool} (optional) initialize: (options)-> @box = options.box @needCentralHandle = options.centralHandle @workspaceAngle = options.workspaceAngle or 0 @handlerContainer = new HandlerContainerView options @displayContainer = new DisplayContainerView @visibility = on # set tranform-origin css property @$el.css 'transform-origin': 'left top' @workspace = options.workspace @$workspace = $ @workspace # if this option is set to true, the zonard will keep the ratio # it was initialized with on resize interactions # it will also hide the dragbars and the n e s w handles if @preserveRatio = options.preserveRatio || off @setRatio @box.width / @box.height @togglePreserveRatio @preserveRatio # initialize _state object, that will hold informations # necessary to determines the block position and rotation @_state = {} angleDeg = @box.rotate angleRad = angleDeg * (2 * Math.PI) /360 @_state.angle = rad: angleRad deg: angleDeg cos: Math.cos(angleRad) sin: Math.sin(angleRad) # Caution: can't call getClientBoundingRectangle in IE9 if element not # in the DOM # @_setState() @assignCursor() assignCursor: -> workspaceAngleRad = @workspaceAngle * (2 * Math.PI) /360 angle = @_state.angle.rad + workspaceAngleRad handle.assignCursor(angle) for i, handle of @handlerContainer.handles dragbar.assignCursor(angle) for i, dragbar of @handlerContainer.dragbars # in the case we want to preserve the ratio, we also need # to change the size boundaries accordingly setRatio: (@ratio)-> @sizeBounds.hMin = @sizeBounds.wMin / @ratio @sizeBounds.hMax = @sizeBounds.wMax / @ratio togglePreserveRatio: (condition)-> @$el.toggleClass 'preserve-ratio', condition listenFocus: -> @listenToOnce @handlerContainer.tracker, 'focus', => @trigger 'focus' listenDoubleClick: -> @listenToOnce @handlerContainer.tracker, 'dblclick', => @trigger 'dblclick' toggle: (visibility)-> @$el.toggleClass "zonard-hidden", !visibility @ # @chainable listenToDragStart: -> for handle in @handlerContainer.handles @listenTo handle, 'drag:start', (data)=> @startTransform data, 'start:resize' @setTransform fn: => box = @_calculateResize @_latestEvent @setBox(box) @trigger 'change:resize', box end: => @releaseMouse() @box = @_calculateResize @_latestEvent @setBox(@box) @trigger 'end:resize', @_setState() @listenMouse() for dragbar in @handlerContainer.dragbars @listenTo dragbar, 'drag:start', (data)=> @startTransform data, 'start:resize' @setTransform fn: => box = @_calculateResize @_latestEvent @setBox(box) @trigger 'change:resize', box end: => @releaseMouse() @box = @_calculateResize @_latestEvent @setBox @box @trigger 'end:resize', @_setState() @listenMouse() @listenTo @handlerContainer.tracker, 'drag:start', (data)=> @startTransform data,'start:move' @_moved = no @setTransform fn: => @_moved = yes box = @_calculateMove @_latestEvent @setBox(box) @trigger 'change:move', box end: => @releaseMouse() # if the mouse has not moved, do not attempt to calculate # a displacement (and avoid snapping) if @_moved @box = @_calculateMove @_latestEvent @setBox @box @trigger 'end:move', @_setState() @listenMouse() @listenTo @handlerContainer.rotateHandle, 'drag:start', (data)=> @startTransform data, 'start:rotate' @setTransform fn: => box = @_calculateRotate @_latestEvent @setBox box @trigger 'change:rotate', box end: => @box = @_calculateRotate @_latestEvent @setBox @box @releaseMouse() @trigger 'end:rotate', @_setState() @assignCursor() @listenMouse() if @needCentralHandle @listenTo @handlerContainer.centralHandle, 'drag:start', (data)=> @startTransform data, 'start:centralDrag' @setTransform fn: => box = @_calculateCentralDrag @_latestEvent @trigger 'info:centralDrag', box end: => @releaseMouse() @trigger 'end:centralDrag', @_calculateCentralDrag @_latestEvent @listenMouse() @ listenMouse: -> $('body').on('mousemove', @debouncer) .on('mouseup', @endTransform) .on('mouseleave', @endTransform) releaseMouse: => $('body').off('mousemove', @debouncer) .off('mouseup', @endTransform) .off('mouseleave', @endTransform) setTransform: (@_transform)-> startTransform: (data, eventName)-> @_setState data @_rafIndex = null @trigger eventName #check if there is already a call waiting debouncer: (@_latestEvent)=> if !@_rafIndex @updateTransform() else updateTransform: => @_rafIndex = requestAnimationFrame => @_transform.fn() @_rafIndex = null endTransform: (@_latestEvent)=> cancelAnimationFrame @_rafIndex @_transform.end @_latestEvent @_rafIndex = @_latestEvent = null # Method to set the position and rotation of the zonard the properties of box # are optionals # box: {left: x, top: y, width: w, height:h, rotate, angle(degrès)} setBox: (box = @getBox())-> box.transform = "rotate3d(0, 0, 1, #{box.rotate}deg)" box.left = Math.round box.left box.top = Math.round box.top box.width = Math.round box.width box.height = Math.round box.height @$el.css box # return position information stored in state getBox:=> @_setState() unless @_state.elPosition? # we return the main informations of position left : @_state.elPosition.left top : @_state.elPosition.top width : @_state.elDimension.width height : @_state.elDimension.height rotate : @_state.angle.deg center: x: @_state.rotatedCenter.x y: @_state.rotatedCenter.y bBox: width : @_state.bBox.width height: @_state.bBox.height # we build a coefficient table, wich indicates the modication pattern # corresponding to each cardinal # * the first 2 are the direction on which to project in the local base to # obtain the top & left movement # * the last 2 are for the width & height modification coefs: n : [ 0, 1, 0, -1] s : [ 0, 0, 0, 1] e : [ 0, 0, 1, 0] w : [ 1, 0, -1, 0] nw : [ 1, 1, -1, -1] ne : [ 0, 1, 1, -1] se : [ 0, 0, 1, 1] sw : [ 1, 0, -1, 1] sizeBounds: wMin: 80 wMax: Infinity hMin: 80 hMax: Infinity # @chainable render: -> @$el.append @displayContainer.render().el, @handlerContainer.render().el # initializes css from the model attributes @setBox _.pick @box, ['left', 'top', 'width', 'height', 'rotate'] @ remove: -> @handlerContainer.remove() @displayContainer.remove() @releaseMouse() if @_transform? super() # we apply the calculator mixin calculators @Zonard.prototype
81816
Cards = 'n,s,e,w,nw,ne,se,sw'.split ',' ordCards = 's,sw,w,nw,n,ne,e,se'.split ',' # <NAME>onard class @Zonard extends Backbone.View className: 'zonard' # @params options {object} # @params options.box {left, top, width, height, rotate} # @params options.workspace {div element} # @params options.centralHandle {bool} (optional) # @params options.preserveRatio {bool} (optional) initialize: (options)-> @box = options.box @needCentralHandle = options.centralHandle @workspaceAngle = options.workspaceAngle or 0 @handlerContainer = new HandlerContainerView options @displayContainer = new DisplayContainerView @visibility = on # set tranform-origin css property @$el.css 'transform-origin': 'left top' @workspace = options.workspace @$workspace = $ @workspace # if this option is set to true, the zonard will keep the ratio # it was initialized with on resize interactions # it will also hide the dragbars and the n e s w handles if @preserveRatio = options.preserveRatio || off @setRatio @box.width / @box.height @togglePreserveRatio @preserveRatio # initialize _state object, that will hold informations # necessary to determines the block position and rotation @_state = {} angleDeg = @box.rotate angleRad = angleDeg * (2 * Math.PI) /360 @_state.angle = rad: angleRad deg: angleDeg cos: Math.cos(angleRad) sin: Math.sin(angleRad) # Caution: can't call getClientBoundingRectangle in IE9 if element not # in the DOM # @_setState() @assignCursor() assignCursor: -> workspaceAngleRad = @workspaceAngle * (2 * Math.PI) /360 angle = @_state.angle.rad + workspaceAngleRad handle.assignCursor(angle) for i, handle of @handlerContainer.handles dragbar.assignCursor(angle) for i, dragbar of @handlerContainer.dragbars # in the case we want to preserve the ratio, we also need # to change the size boundaries accordingly setRatio: (@ratio)-> @sizeBounds.hMin = @sizeBounds.wMin / @ratio @sizeBounds.hMax = @sizeBounds.wMax / @ratio togglePreserveRatio: (condition)-> @$el.toggleClass 'preserve-ratio', condition listenFocus: -> @listenToOnce @handlerContainer.tracker, 'focus', => @trigger 'focus' listenDoubleClick: -> @listenToOnce @handlerContainer.tracker, 'dblclick', => @trigger 'dblclick' toggle: (visibility)-> @$el.toggleClass "zonard-hidden", !visibility @ # @chainable listenToDragStart: -> for handle in @handlerContainer.handles @listenTo handle, 'drag:start', (data)=> @startTransform data, 'start:resize' @setTransform fn: => box = @_calculateResize @_latestEvent @setBox(box) @trigger 'change:resize', box end: => @releaseMouse() @box = @_calculateResize @_latestEvent @setBox(@box) @trigger 'end:resize', @_setState() @listenMouse() for dragbar in @handlerContainer.dragbars @listenTo dragbar, 'drag:start', (data)=> @startTransform data, 'start:resize' @setTransform fn: => box = @_calculateResize @_latestEvent @setBox(box) @trigger 'change:resize', box end: => @releaseMouse() @box = @_calculateResize @_latestEvent @setBox @box @trigger 'end:resize', @_setState() @listenMouse() @listenTo @handlerContainer.tracker, 'drag:start', (data)=> @startTransform data,'start:move' @_moved = no @setTransform fn: => @_moved = yes box = @_calculateMove @_latestEvent @setBox(box) @trigger 'change:move', box end: => @releaseMouse() # if the mouse has not moved, do not attempt to calculate # a displacement (and avoid snapping) if @_moved @box = @_calculateMove @_latestEvent @setBox @box @trigger 'end:move', @_setState() @listenMouse() @listenTo @handlerContainer.rotateHandle, 'drag:start', (data)=> @startTransform data, 'start:rotate' @setTransform fn: => box = @_calculateRotate @_latestEvent @setBox box @trigger 'change:rotate', box end: => @box = @_calculateRotate @_latestEvent @setBox @box @releaseMouse() @trigger 'end:rotate', @_setState() @assignCursor() @listenMouse() if @needCentralHandle @listenTo @handlerContainer.centralHandle, 'drag:start', (data)=> @startTransform data, 'start:centralDrag' @setTransform fn: => box = @_calculateCentralDrag @_latestEvent @trigger 'info:centralDrag', box end: => @releaseMouse() @trigger 'end:centralDrag', @_calculateCentralDrag @_latestEvent @listenMouse() @ listenMouse: -> $('body').on('mousemove', @debouncer) .on('mouseup', @endTransform) .on('mouseleave', @endTransform) releaseMouse: => $('body').off('mousemove', @debouncer) .off('mouseup', @endTransform) .off('mouseleave', @endTransform) setTransform: (@_transform)-> startTransform: (data, eventName)-> @_setState data @_rafIndex = null @trigger eventName #check if there is already a call waiting debouncer: (@_latestEvent)=> if !@_rafIndex @updateTransform() else updateTransform: => @_rafIndex = requestAnimationFrame => @_transform.fn() @_rafIndex = null endTransform: (@_latestEvent)=> cancelAnimationFrame @_rafIndex @_transform.end @_latestEvent @_rafIndex = @_latestEvent = null # Method to set the position and rotation of the zonard the properties of box # are optionals # box: {left: x, top: y, width: w, height:h, rotate, angle(degrès)} setBox: (box = @getBox())-> box.transform = "rotate3d(0, 0, 1, #{box.rotate}deg)" box.left = Math.round box.left box.top = Math.round box.top box.width = Math.round box.width box.height = Math.round box.height @$el.css box # return position information stored in state getBox:=> @_setState() unless @_state.elPosition? # we return the main informations of position left : @_state.elPosition.left top : @_state.elPosition.top width : @_state.elDimension.width height : @_state.elDimension.height rotate : @_state.angle.deg center: x: @_state.rotatedCenter.x y: @_state.rotatedCenter.y bBox: width : @_state.bBox.width height: @_state.bBox.height # we build a coefficient table, wich indicates the modication pattern # corresponding to each cardinal # * the first 2 are the direction on which to project in the local base to # obtain the top & left movement # * the last 2 are for the width & height modification coefs: n : [ 0, 1, 0, -1] s : [ 0, 0, 0, 1] e : [ 0, 0, 1, 0] w : [ 1, 0, -1, 0] nw : [ 1, 1, -1, -1] ne : [ 0, 1, 1, -1] se : [ 0, 0, 1, 1] sw : [ 1, 0, -1, 1] sizeBounds: wMin: 80 wMax: Infinity hMin: 80 hMax: Infinity # @chainable render: -> @$el.append @displayContainer.render().el, @handlerContainer.render().el # initializes css from the model attributes @setBox _.pick @box, ['left', 'top', 'width', 'height', 'rotate'] @ remove: -> @handlerContainer.remove() @displayContainer.remove() @releaseMouse() if @_transform? super() # we apply the calculator mixin calculators @Zonard.prototype
true
Cards = 'n,s,e,w,nw,ne,se,sw'.split ',' ordCards = 's,sw,w,nw,n,ne,e,se'.split ',' # PI:NAME:<NAME>END_PIonard class @Zonard extends Backbone.View className: 'zonard' # @params options {object} # @params options.box {left, top, width, height, rotate} # @params options.workspace {div element} # @params options.centralHandle {bool} (optional) # @params options.preserveRatio {bool} (optional) initialize: (options)-> @box = options.box @needCentralHandle = options.centralHandle @workspaceAngle = options.workspaceAngle or 0 @handlerContainer = new HandlerContainerView options @displayContainer = new DisplayContainerView @visibility = on # set tranform-origin css property @$el.css 'transform-origin': 'left top' @workspace = options.workspace @$workspace = $ @workspace # if this option is set to true, the zonard will keep the ratio # it was initialized with on resize interactions # it will also hide the dragbars and the n e s w handles if @preserveRatio = options.preserveRatio || off @setRatio @box.width / @box.height @togglePreserveRatio @preserveRatio # initialize _state object, that will hold informations # necessary to determines the block position and rotation @_state = {} angleDeg = @box.rotate angleRad = angleDeg * (2 * Math.PI) /360 @_state.angle = rad: angleRad deg: angleDeg cos: Math.cos(angleRad) sin: Math.sin(angleRad) # Caution: can't call getClientBoundingRectangle in IE9 if element not # in the DOM # @_setState() @assignCursor() assignCursor: -> workspaceAngleRad = @workspaceAngle * (2 * Math.PI) /360 angle = @_state.angle.rad + workspaceAngleRad handle.assignCursor(angle) for i, handle of @handlerContainer.handles dragbar.assignCursor(angle) for i, dragbar of @handlerContainer.dragbars # in the case we want to preserve the ratio, we also need # to change the size boundaries accordingly setRatio: (@ratio)-> @sizeBounds.hMin = @sizeBounds.wMin / @ratio @sizeBounds.hMax = @sizeBounds.wMax / @ratio togglePreserveRatio: (condition)-> @$el.toggleClass 'preserve-ratio', condition listenFocus: -> @listenToOnce @handlerContainer.tracker, 'focus', => @trigger 'focus' listenDoubleClick: -> @listenToOnce @handlerContainer.tracker, 'dblclick', => @trigger 'dblclick' toggle: (visibility)-> @$el.toggleClass "zonard-hidden", !visibility @ # @chainable listenToDragStart: -> for handle in @handlerContainer.handles @listenTo handle, 'drag:start', (data)=> @startTransform data, 'start:resize' @setTransform fn: => box = @_calculateResize @_latestEvent @setBox(box) @trigger 'change:resize', box end: => @releaseMouse() @box = @_calculateResize @_latestEvent @setBox(@box) @trigger 'end:resize', @_setState() @listenMouse() for dragbar in @handlerContainer.dragbars @listenTo dragbar, 'drag:start', (data)=> @startTransform data, 'start:resize' @setTransform fn: => box = @_calculateResize @_latestEvent @setBox(box) @trigger 'change:resize', box end: => @releaseMouse() @box = @_calculateResize @_latestEvent @setBox @box @trigger 'end:resize', @_setState() @listenMouse() @listenTo @handlerContainer.tracker, 'drag:start', (data)=> @startTransform data,'start:move' @_moved = no @setTransform fn: => @_moved = yes box = @_calculateMove @_latestEvent @setBox(box) @trigger 'change:move', box end: => @releaseMouse() # if the mouse has not moved, do not attempt to calculate # a displacement (and avoid snapping) if @_moved @box = @_calculateMove @_latestEvent @setBox @box @trigger 'end:move', @_setState() @listenMouse() @listenTo @handlerContainer.rotateHandle, 'drag:start', (data)=> @startTransform data, 'start:rotate' @setTransform fn: => box = @_calculateRotate @_latestEvent @setBox box @trigger 'change:rotate', box end: => @box = @_calculateRotate @_latestEvent @setBox @box @releaseMouse() @trigger 'end:rotate', @_setState() @assignCursor() @listenMouse() if @needCentralHandle @listenTo @handlerContainer.centralHandle, 'drag:start', (data)=> @startTransform data, 'start:centralDrag' @setTransform fn: => box = @_calculateCentralDrag @_latestEvent @trigger 'info:centralDrag', box end: => @releaseMouse() @trigger 'end:centralDrag', @_calculateCentralDrag @_latestEvent @listenMouse() @ listenMouse: -> $('body').on('mousemove', @debouncer) .on('mouseup', @endTransform) .on('mouseleave', @endTransform) releaseMouse: => $('body').off('mousemove', @debouncer) .off('mouseup', @endTransform) .off('mouseleave', @endTransform) setTransform: (@_transform)-> startTransform: (data, eventName)-> @_setState data @_rafIndex = null @trigger eventName #check if there is already a call waiting debouncer: (@_latestEvent)=> if !@_rafIndex @updateTransform() else updateTransform: => @_rafIndex = requestAnimationFrame => @_transform.fn() @_rafIndex = null endTransform: (@_latestEvent)=> cancelAnimationFrame @_rafIndex @_transform.end @_latestEvent @_rafIndex = @_latestEvent = null # Method to set the position and rotation of the zonard the properties of box # are optionals # box: {left: x, top: y, width: w, height:h, rotate, angle(degrès)} setBox: (box = @getBox())-> box.transform = "rotate3d(0, 0, 1, #{box.rotate}deg)" box.left = Math.round box.left box.top = Math.round box.top box.width = Math.round box.width box.height = Math.round box.height @$el.css box # return position information stored in state getBox:=> @_setState() unless @_state.elPosition? # we return the main informations of position left : @_state.elPosition.left top : @_state.elPosition.top width : @_state.elDimension.width height : @_state.elDimension.height rotate : @_state.angle.deg center: x: @_state.rotatedCenter.x y: @_state.rotatedCenter.y bBox: width : @_state.bBox.width height: @_state.bBox.height # we build a coefficient table, wich indicates the modication pattern # corresponding to each cardinal # * the first 2 are the direction on which to project in the local base to # obtain the top & left movement # * the last 2 are for the width & height modification coefs: n : [ 0, 1, 0, -1] s : [ 0, 0, 0, 1] e : [ 0, 0, 1, 0] w : [ 1, 0, -1, 0] nw : [ 1, 1, -1, -1] ne : [ 0, 1, 1, -1] se : [ 0, 0, 1, 1] sw : [ 1, 0, -1, 1] sizeBounds: wMin: 80 wMax: Infinity hMin: 80 hMax: Infinity # @chainable render: -> @$el.append @displayContainer.render().el, @handlerContainer.render().el # initializes css from the model attributes @setBox _.pick @box, ['left', 'top', 'width', 'height', 'rotate'] @ remove: -> @handlerContainer.remove() @displayContainer.remove() @releaseMouse() if @_transform? super() # we apply the calculator mixin calculators @Zonard.prototype
[ { "context": "nonymous = $anonymousT;\r\n $this->username = $usernameT;\r\n $this->password = $passwordT;\r\n $thi", "end": 31658, "score": 0.7834665775299072, "start": 31649, "tag": "USERNAME", "value": "usernameT" }, { "context": ">username = $usernameT;\r\n $th...
chrome/content/zotero-opds/icecoldapps_syncronizeultimate.coffee
AllThatIsTheCase/zotero-opds
8
### * Ice Cold Apps * * GENERAL SETTINGS * * Warning: if you have problems to read, create or edit files/folder try to change the permissions to a higher octal number. This normally solves the problems. * ### class ICASync constructor: (@query) -> serve: -> return @["_#{@query.action}"].call(@) case "download": if(!$current_user->permissions->allow_read || !$current_user->permissions->allow_download) { mssgError("permission", "Permission error"); exit(); } doDownloadFile(get_received_variable("from")); break; case "upload": if(!$current_user->permissions->allow_write || !$current_user->permissions->allow_upload) { mssgError("permission", "Permission error"); exit(); } doUploadFile(); break; case "deletefile": if(!$current_user->permissions->allow_write || !$current_user->permissions->allow_delete) { mssgError("permission", "Permission error"); exit(); } doDeleteFile(get_received_variable("from")); break; case "deletedir": if(!$current_user->permissions->allow_write || !$current_user->permissions->allow_delete) { mssgError("permission", "Permission error"); exit(); } doDeleteDir(get_received_variable("from")); break; case "copyfile": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doCopyFile(get_received_variable("from"), get_received_variable("to")); break; case "copydir": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doCopyDir(get_received_variable("from"), get_received_variable("to")); break; case "renamefile": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doRenameFile(get_received_variable("from"), get_received_variable("to")); break; case "renamedir": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doRenameDir(get_received_variable("from"), get_received_variable("to")); break; case "createdir": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doCreateDir(get_received_variable("from")); break; case "existsfile": doExistsFile(get_received_variable("from")); break; case "existsdir": doExistsDir(get_received_variable("from")); break; case "serverinformation": if(!$current_user->permissions->allow_read || !$current_user->permissions->allow_serverinformation) { mssgError("permission", "Permission error"); exit(); } serverInformation(); break; case "chgrp": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doChgrp(get_received_variable("from"), get_received_variable("id")); break; case "chown": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doChown(get_received_variable("from"), get_received_variable("id")); break; case "chmod": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doChmod(get_received_variable("from"), get_received_variable("id")); break; case "clearstatcache": doClearstatcache(); break; case "lchgrp": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doLchgrp(get_received_variable("from"), get_received_variable("id")); break; case "lchown": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doLchown(get_received_variable("from"), get_received_variable("id")); break; case "link": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doLink(get_received_variable("from"), get_received_variable("link")); break; case "symlink": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doSymlink(get_received_variable("from"), get_received_variable("link")); break; case "touch": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doTouch(get_received_variable("from"), get_received_variable("time"), get_received_variable("atime")); break; case "umask": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doUmask(get_received_variable("from"), get_received_variable("id")); break; case "unlink": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doUnlink(get_received_variable("from")); break; case "server2server": if(!$current_user->permissions->allow_server2server) { mssgError("permission", "Permission error"); exit(); } doServer2Server(); break; } return; # general information _generalinformation: -> data_return = {} data_return.version = "1.0.2" data_return.version_code = 2 # data_return['phpversion'] = @phpversion(); data_return.functions_available = {} for k of @ continue unless k[0] == '_' data_return.functions_available[k.slice(1)] = true data_return.status = "ok" return JSON.stringify(data_return) listfiles: -> if !@query.path # user library else # compute location from path # if path doesn't exist, throw error all_files = [] counter = 0; $handler = @opendir($_path); while($file = @readdir($handler)) { # checks if(($file == ".") || ($file == "..")) { continue; } $full_path = convertPathFile(get_absolute_path($_path.DIRECTORY_SEPARATOR.$file)); if($full_path == convertPathFile(__FILE__)) { continue; } $docontinue = false; foreach($config_files_exclude as $file_exclude) { if(isBaseDir($file_exclude) && startsWith($full_path, $file_exclude)) { $docontinue = true; } else if(!isBaseDir($file_exclude) && (strpos($file_exclude,DIRECTORY_SEPARATOR) !== true) && ($file == $file_exclude)) { $docontinue = true; } else if(!isBaseDir($file_exclude) && (strpos($file_exclude,DIRECTORY_SEPARATOR) !== false) && startsWith($_path, DIRECTORY_SEPARATOR.$file_exclude)) { $docontinue = true; } } if($docontinue) { continue; } # get file info $file_data = array(); $file_data['filename'] = $file; $file_data['path'] = $full_path; if(function_exists('realpath')) { $file_data['realpath'] = realpath($full_path); } if(function_exists('fileatime')) { $file_data['fileatime'] = @fileatime($full_path); } if(function_exists('filectime')) { $file_data['filectime'] = @filectime($full_path); } if(function_exists('fileinode')) { $file_data['fileinode'] = @fileinode($full_path); } if(function_exists('filemtime')) { $file_data['filemtime'] = @filemtime($full_path); } if(function_exists('fileperms')) { $file_data['fileperms'] = @fileperms($full_path); $file_data['fileperms_octal'] = @substr(sprintf('%o', @fileperms($full_path)), -4); $file_data['fileperms_readable'] = get_readable_permission(@fileperms($full_path)); } if(function_exists('filesize')) { $file_data['filesize'] = @filesize($full_path); if(function_exists('is_file') && @is_file($full_path)) { if(@filesize($full_path) < (1024 * 1024 * 10)) { $file_data['md5_file'] = @md5_file($full_path); $file_data['sha1_file'] = @sha1_file($full_path); } } } if(function_exists('filetype')) { $file_data['filetype'] = @filetype($full_path); } if(function_exists('is_dir')) { $file_data['is_dir'] = @is_dir($full_path); } if(function_exists('is_executable')) { $file_data['is_executable'] = @is_executable($full_path); } if(function_exists('is_file')) { $file_data['is_file'] = @is_file($full_path); } if(function_exists('is_link')) { $file_data['is_link'] = @is_link($full_path); } if(function_exists('is_readable')) { $file_data['is_readable'] = @is_readable($full_path); } if(function_exists('is_uploaded_file')) { $file_data['is_uploaded_file'] = @is_uploaded_file($full_path); } if(function_exists('is_writable')) { $file_data['is_writable'] = @is_writable($full_path); } if(function_exists('linkinfo')) { $file_data['linkinfo'] = @linkinfo($full_path); } if(function_exists('readlink')) { $link_path = @readlink($full_path); if(function_exists('is_dir') && @is_dir($full_path)) { $link_path = convertPathDir($link_path); } else if(function_exists('is_file') && @is_file($full_path)) { $link_path = convertPathFile($link_path); } else { $link_path = convertPathStartSlash($link_path); } if(startsWith($link_path, getBaseDir())) { $link_path = @substr($link_path, @strlen(getBaseDir())); } $link_path = convertPathStartSlash($link_path); $file_data['readlink'] = $link_path; } if(function_exists('stat')) { $stat = @stat($full_path); $file_data['stat_data'] = $stat; } if(function_exists('filegroup')) { $file_data['filegroup'] = @filegroup($full_path); if(function_exists('posix_getgrgid')) { $filegroup = @posix_getgrgid(@filegroup($full_path)); $file_data['filegroup_data'] = $filegroup; } } if(function_exists('fileowner')) { $file_data['fileowner'] = @fileowner($full_path); if(function_exists('posix_getpwuid')) { $fileowner = @posix_getpwuid(@fileowner($full_path)); $file_data['fileowner_data'] = $fileowner; } } $counter++; $all_files[] = $file_data; } @closedir($handler); $data_return = array(); $data_return['data'] = $all_files; $data_return['counter'] = $counter; $data_return['path'] = $_path; $data_return['status'] = "ok"; # var_dump($return_files); echo @json_encode($data_return); } # download function doDownloadFile($from) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); @readfile($from); } # upload function doUploadFile() { $to = get_received_variable("to"); $time_lastmodified = get_received_variable("time_lastmodified"); $time_accessed = get_received_variable("time_accessed"); $chmod = get_received_variable("chmod"); $chown = get_received_variable("chown"); $chgrp = get_received_variable("chgrp"); $to = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); if(@move_uploaded_file($_FILES['filename1']['tmp_name'], $to)) { if(function_exists('touch') && (($time_lastmodified != "") || ($time_accessed != ""))) { if($time_accessed == "") { @touch($to, $time_lastmodified); } else { @touch($to, $time_lastmodified, $time_accessed); } } if(function_exists('chmod') && ($chmod != "")) { @chmod($to, octdec($chmod)); } if(function_exists('chown') && ($chown != "")) { @chown($to, $chown); } if(function_exists('chgrp') && ($chgrp != "")) { @chgrp($to, $chgrp); } mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # delete function doDeleteFile($from) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@unlink($from)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } function doDeleteDir($from) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); rmdir_recursive($from); mssgOk("done", "Done"); } # copy function doCopyFile($from, $to) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $to = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); if(@copy($from, $to)) { set_same_times($from, $to); mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } function doCopyDir($from, $to) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $to = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); recurse_copy($from, $to); mssgOk("done", "Done"); } # rename function doRenameFile($from, $to) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $to = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); if(@rename($from, $to)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } function doRenameDir($from, $to) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $to = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); if(@rename($from, $to)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # create dir function doCreateDir($from) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@mkdir($from, 0777, true)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # exists function doExistsFile($from) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@file_exists($from)) { mssgOk("exists", "Exists"); } else { mssgOk("notexists", "Not exists"); } } function doExistsDir($from) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@file_exists($from)) { mssgOk("exists", "Exists"); } else { mssgOk("notexists", "Not exists"); } } # server information function serverInformation() { global $config, $current_user, $_SERVER, $_GET, $_POST, $_SESSION, $_ENV, $_FILES, $_COOKIE; $data_return = array(); if(function_exists('disk_free_space')) { $data_return['disk_free_space'] = @disk_free_space(getBaseDir()); } if(function_exists('disk_total_space')) { $data_return['disk_total_space'] = @disk_total_space(getBaseDir()); } $data_return['basedir'] = getBaseDir(); if(function_exists('phpversion')) { $data_return['phpversion'] = @phpversion(); } if(function_exists('curl_version')) { $data_return['curl_version'] = @curl_version(); } if(function_exists('sys_getloadavg')) { $data_return['sys_getloadavg'] = @sys_getloadavg(); } $data_return['config'] = $config; $data_return['current_user'] = $current_user; $data_return['status'] = "ok"; $data_return['phpinfo'] = phpinfo_array(true); $data_return['_SERVER'] = @$_SERVER; $data_return['_GET'] = @$_GET; $_POST['password'] = "*"; $data_return['_POST'] = @$_POST; $data_return['_SESSION'] = @$_SESSION; $data_return['_ENV'] = @$_ENV; # $data_return['_FILES'] = @$_FILES; # $data_return['_COOKIE'] = @$_COOKIE; echo @json_encode($data_return); } # chgrp function doChgrp($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@chgrp($from, $id)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # chmod function doChmod($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@chmod($from, octdec($id))) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # chown function doChown($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@chown($from, $id)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # clearstatcache function doClearstatcache() { @clearstatcache(); mssgOk("done", "Done"); } # lchgrp function doLchgrp($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@lchgrp($from, $id)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # lchown function doLchown($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@lchown($from, $id)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # link function doLink($from, $link) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $link = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$link)); if(@link($from, $link)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # symlink function doSymlink($from, $link) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $link = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$link)); if(@symlink($from, $link)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # touch function doTouch($from, $time, $atime) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if($atime == "") { if(@touch($from, $time)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } else { if(@touch($from, $time, $atime)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } } # umask function doUmask($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $umaskT = @umask($from, $id); mssgOk($umaskT, "Done"); } # unlink function doUnlink($from) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@unlink($from)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # server 2 server function doServer2Server() { # get_token1 # token1 # token2 # username # password # htpasswd # htpasswd username # htpasswd password # from # to $target_url = get_received_variable("dest_url"); $array_post = array( 'token1' => get_received_variable("dest_token1"), 'token2' => get_received_variable("dest_token2"), 'username' => get_received_variable("dest_username"), 'password' => get_received_variable("dest_password"), 'action' => get_received_variable("dest_action"), 'from' => get_received_variable("dest_from"), 'to' => get_received_variable("dest_to"), 'path' => get_received_variable("dest_path"), 'time_lastmodified' => get_received_variable("dest_time_lastmodified"), 'time_accessed' => get_received_variable("dest_time_accessed"), 'chmod' => get_received_variable("dest_chmod"), 'chown' => get_received_variable("dest_chown"), 'chgrp' => get_received_variable("dest_chgrp"), 'id' => get_received_variable("dest_id"), 'link' => get_received_variable("dest_link"), 'time' => get_received_variable("dest_time"), 'atime' => get_received_variable("dest_atime") ); if(get_received_variable("dest_action") == "upload") { $array_post_add1 = array( 'filename1'=>'@'.convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.get_received_variable("from"))) ); $array_post = array_merge($array_post, $array_post_add1); } $_curl = curl_init(); curl_setopt($_curl, CURLOPT_URL, $target_url); curl_setopt($_curl, CURLOPT_POST, 1); curl_setopt($_curl, CURLOPT_POSTFIELDS, $array_post); if(get_received_variable("dest_httpauth") != "") { curl_setopt($_curl, CURLOPT_USERPWD, get_received_variable("dest_httpauth_username").":".get_received_variable("dest_httpauth_password")); } # curl_setopt($_curl, CURLOPT_RETURNTRANSFER, 1); # $result = curl_exec($_curl); curl_exec($_curl); curl_close($_curl); # echo $result; } function mssgOk($_id, $_message) { $data_return = array(); $data_return['status'] = "ok"; $data_return['id'] = $_id; $data_return['message'] = $_message; echo @json_encode($data_return); } function mssgError($_id, $_message) { $data_return = array(); $data_return['status'] = "error"; $data_return['id'] = $_id; $data_return['message'] = $_message; echo @json_encode($data_return); } ### * OTHER ### function is_dir_allowed($_path) { global $config, $current_user; # if(!$current_user->path_forcestay) { # return true; # } $temp_basedir = convertPathDir($_path); if(startsWith($temp_basedir, getBaseDir())) { return true; } return false; } function getBaseDir() { global $config, $current_user; $return_path = DIRECTORY_SEPARATOR; if(@is_empty($config['path_default'])) { $return_path = pathinfo(__FILE__, PATHINFO_DIRNAME); } else { if(isBaseDir($config['path_default'])) { $return_path = $config['path_default']; } else { $return_path = pathinfo(__FILE__, PATHINFO_DIRNAME).DIRECTORY_SEPARATOR.$config['path_default']; } } if(!@is_empty($current_user->path_default)) { if(isBaseDir($current_user->path_default)) { $return_path = $current_user->path_default; } else { $return_path = $return_path.DIRECTORY_SEPARATOR.$current_user->path_default; } } $return_path = get_absolute_path($return_path); return convertPathDir($return_path); } function isBaseDir($_path) { if(!base_with_slash()) { if(strpos($_path,':') !== false) { return true; } else { return false; } } else { if(startsWith($_path, DIRECTORY_SEPARATOR)) { return true; } else { return false; } } } function convertPathDir($_path) { if(!endsWith($_path, DIRECTORY_SEPARATOR)) { $_path = $_path.DIRECTORY_SEPARATOR; } if(base_with_slash()) { if(!startsWith($_path, DIRECTORY_SEPARATOR)) { $_path = DIRECTORY_SEPARATOR.$_path; } } return $_path; } function convertPathFile($_path) { if(endsWith($_path, DIRECTORY_SEPARATOR)) { $_path = substr($_path, 0, -1); } if(base_with_slash()) { if(!startsWith($_path, DIRECTORY_SEPARATOR)) { $_path = DIRECTORY_SEPARATOR.$_path; } } return $_path; } function convertPathStartSlash($_path) { if(base_with_slash()) { if(!startsWith($_path, DIRECTORY_SEPARATOR)) { $_path = DIRECTORY_SEPARATOR.$_path; } } return $_path; } function base_with_slash() { if(startsWith(__FILE__, DIRECTORY_SEPARATOR)) { return true; } else { return false; } } function is_empty($_variable) { if(($_variable == null) || (empty($_variable)) || ($_variable = "")) { return true; } return false; } function get_received_variable($_variable) { global $config, $_POST, $_GET; # if($config['variables_post']) { return $_POST[$_variable]; # } else { # return $_GET[$_variable]; # } } function startsWith($haystack, $needle){ return $needle === "" || @strpos($haystack, $needle) === 0; } function endsWith($haystack, $needle){ return $needle === "" || @substr($haystack, -@strlen($needle)) === $needle; } function get_absolute_path($path) { $path = @str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path); $parts = @array_filter(@explode(DIRECTORY_SEPARATOR, $path), 'strlen'); $absolutes = array(); foreach ($parts as $part) { if ('.' == $part) continue; if ('..' == $part) { @array_pop($absolutes); } else { $absolutes[] = $part; } } return @implode(DIRECTORY_SEPARATOR, $absolutes); } function get_client_ip() { global $_SERVER; $ipaddress = ''; if ($_SERVER['HTTP_CLIENT_IP']) { $ipaddress = $_SERVER['HTTP_CLIENT_IP']; } else if($_SERVER['HTTP_X_FORWARDED_FOR']) { $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR']; } else if($_SERVER['HTTP_X_FORWARDED']) { $ipaddress = $_SERVER['HTTP_X_FORWARDED']; } else if($_SERVER['HTTP_FORWARDED_FOR']) { $ipaddress = $_SERVER['HTTP_FORWARDED_FOR']; } else if($_SERVER['HTTP_FORWARDED']) { $ipaddress = $_SERVER['HTTP_FORWARDED']; } else if($_SERVER['REMOTE_ADDR']) { $ipaddress = $_SERVER['REMOTE_ADDR']; } else { $ipaddress = 'UNKNOWN'; } return $ipaddress; } function get_readable_permission($perms) { if (($perms & 0xC000) == 0xC000) { # Socket $info = 's'; } elseif (($perms & 0xA000) == 0xA000) { # Symbolic Link $info = 'l'; } elseif (($perms & 0x8000) == 0x8000) { # Regular $info = '-'; } elseif (($perms & 0x6000) == 0x6000) { # Block special $info = 'b'; } elseif (($perms & 0x4000) == 0x4000) { # Directory $info = 'd'; } elseif (($perms & 0x2000) == 0x2000) { # Character special $info = 'c'; } elseif (($perms & 0x1000) == 0x1000) { # FIFO pipe $info = 'p'; } else { # Unknown $info = 'u'; } $info .= (($perms & 0x0100) ? 'r' : '-'); $info .= (($perms & 0x0080) ? 'w' : '-'); $info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-')); $info .= (($perms & 0x0020) ? 'r' : '-'); $info .= (($perms & 0x0010) ? 'w' : '-'); $info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-')); $info .= (($perms & 0x0004) ? 'r' : '-'); $info .= (($perms & 0x0002) ? 'w' : '-'); $info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-')); return $info; } function set_same_times($from, $to) { if(function_exists('touch')) { if(function_exists('filemtime') && function_exists('fileatime')) { @touch($to, @filemtime($from), @fileatime($from)); } else if(function_exists('filemtime')) { @touch($to, @filemtime($from)); } } } function recurse_copy($src,$dst) { $dir = @opendir($src); @mkdir($dst); set_same_times($src, $dst); while(false !== ( $file = @readdir($dir)) ) { if (( $file != '.' ) && ( $file != '..' )) { if ( @is_dir($src .DIRECTORY_SEPARATOR. $file) ) { recurse_copy($src .DIRECTORY_SEPARATOR. $file, $dst .DIRECTORY_SEPARATOR. $file); } else { @copy($src.DIRECTORY_SEPARATOR.$file, $dst.DIRECTORY_SEPARATOR.$file); set_same_times($src.DIRECTORY_SEPARATOR.$file, $dst.DIRECTORY_SEPARATOR.$file); } } } @closedir($dir); } function rmdir_recursive($dir) { foreach(scandir($dir) as $file) { if ('.' === $file || '..' === $file) continue; if (@is_dir($dir.DIRECTORY_SEPARATOR.$file)) rmdir_recursive($dir.DIRECTORY_SEPARATOR.$file); else @unlink($dir.DIRECTORY_SEPARATOR.$file); } @rmdir($dir); } function phpinfo_array($return=false){ @ob_start(); @phpinfo(-1); $pi = @preg_replace( array('#^.*<body>(.*)</body>.*$#ms', '#<h2>PHP License</h2>.*$#ms', '#<h1>Configuration</h1>#', "#\r?\n#", "#</(h1|h2|h3|tr)>#", '# +<#', "#[ \t]+#", '#&nbsp;#', '# +#', '# class=".*?"#', '%&#039;%', '#<tr>(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" /></a>' .'<h1>PHP Version (.*?)</h1>(?:\n+?)</td></tr>#', '#<h1><a href="(?:.*?)\?=(.*?)">PHP Credits</a></h1>#', '#<tr>(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)</tr>#', "# +#", '#<tr>#', '#</tr>#'), array('$1', '', '', '', '</$1>' . "\n", '<', ' ', ' ', ' ', '', ' ', '<h2>PHP Configuration</h2>'."\n".'<tr><td>PHP Version</td><td>$2</td></tr>'. "\n".'<tr><td>PHP Egg</td><td>$1</td></tr>', '<tr><td>PHP Credits Egg</td><td>$1</td></tr>', '<tr><td>Zend Engine</td><td>$2</td></tr>' . "\n" . '<tr><td>Zend Egg</td><td>$1</td></tr>', ' ', '%S%', '%E%'), @ob_get_clean()); $sections = @explode('<h2>', @strip_tags($pi, '<h2><th><td>')); unset($sections[0]); $pi = array(); foreach($sections as $section){ $n = @substr($section, 0, @strpos($section, '</h2>')); @preg_match_all( '#%S%(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?%E%#', $section, $askapache, PREG_SET_ORDER); foreach($askapache as $m) $pi[$n][$m[1]]=(!isset($m[3])||$m[2]==$m[3])?$m[2]:@array_slice($m,2); } return ($return === false) ? @print_r($pi) : $pi; } ### * DATA ### class User { public $anonymous = false; public $username = ""; public $password = ""; public $path_default = ""; public $permissions; public function __construct($anonymousT, $usernameT, $passwordT, $path_defaultT, $permissionsT) { $this->anonymous = $anonymousT; $this->username = $usernameT; $this->password = $passwordT; $this->path_default = $path_defaultT; $this->permissions = $permissionsT; } } class Permissions { public $allow_read = true; public $allow_write = true; public $allow_delete = true; public $allow_download = true; public $allow_upload = true; public $allow_serverinformation = true; public $allow_server2server = true; public function __construct($allow_readT, $allow_writeT, $allow_deleteT, $allow_downloadT, $allow_uploadT, $allow_serverinformationT, $allow_server2serverT) { $this->allow_read = $allow_readT; $this->allow_write = $allow_writeT; $this->allow_delete = $allow_deleteT; $this->allow_download = $allow_downloadT; $this->allow_upload = $allow_uploadT; $this->allow_serverinformation = $allow_serverinformationT; $this->allow_server2server = $allow_server2serverT; } } ?>
205726
### * Ice Cold Apps * * GENERAL SETTINGS * * Warning: if you have problems to read, create or edit files/folder try to change the permissions to a higher octal number. This normally solves the problems. * ### class ICASync constructor: (@query) -> serve: -> return @["_#{@query.action}"].call(@) case "download": if(!$current_user->permissions->allow_read || !$current_user->permissions->allow_download) { mssgError("permission", "Permission error"); exit(); } doDownloadFile(get_received_variable("from")); break; case "upload": if(!$current_user->permissions->allow_write || !$current_user->permissions->allow_upload) { mssgError("permission", "Permission error"); exit(); } doUploadFile(); break; case "deletefile": if(!$current_user->permissions->allow_write || !$current_user->permissions->allow_delete) { mssgError("permission", "Permission error"); exit(); } doDeleteFile(get_received_variable("from")); break; case "deletedir": if(!$current_user->permissions->allow_write || !$current_user->permissions->allow_delete) { mssgError("permission", "Permission error"); exit(); } doDeleteDir(get_received_variable("from")); break; case "copyfile": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doCopyFile(get_received_variable("from"), get_received_variable("to")); break; case "copydir": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doCopyDir(get_received_variable("from"), get_received_variable("to")); break; case "renamefile": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doRenameFile(get_received_variable("from"), get_received_variable("to")); break; case "renamedir": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doRenameDir(get_received_variable("from"), get_received_variable("to")); break; case "createdir": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doCreateDir(get_received_variable("from")); break; case "existsfile": doExistsFile(get_received_variable("from")); break; case "existsdir": doExistsDir(get_received_variable("from")); break; case "serverinformation": if(!$current_user->permissions->allow_read || !$current_user->permissions->allow_serverinformation) { mssgError("permission", "Permission error"); exit(); } serverInformation(); break; case "chgrp": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doChgrp(get_received_variable("from"), get_received_variable("id")); break; case "chown": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doChown(get_received_variable("from"), get_received_variable("id")); break; case "chmod": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doChmod(get_received_variable("from"), get_received_variable("id")); break; case "clearstatcache": doClearstatcache(); break; case "lchgrp": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doLchgrp(get_received_variable("from"), get_received_variable("id")); break; case "lchown": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doLchown(get_received_variable("from"), get_received_variable("id")); break; case "link": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doLink(get_received_variable("from"), get_received_variable("link")); break; case "symlink": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doSymlink(get_received_variable("from"), get_received_variable("link")); break; case "touch": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doTouch(get_received_variable("from"), get_received_variable("time"), get_received_variable("atime")); break; case "umask": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doUmask(get_received_variable("from"), get_received_variable("id")); break; case "unlink": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doUnlink(get_received_variable("from")); break; case "server2server": if(!$current_user->permissions->allow_server2server) { mssgError("permission", "Permission error"); exit(); } doServer2Server(); break; } return; # general information _generalinformation: -> data_return = {} data_return.version = "1.0.2" data_return.version_code = 2 # data_return['phpversion'] = @phpversion(); data_return.functions_available = {} for k of @ continue unless k[0] == '_' data_return.functions_available[k.slice(1)] = true data_return.status = "ok" return JSON.stringify(data_return) listfiles: -> if !@query.path # user library else # compute location from path # if path doesn't exist, throw error all_files = [] counter = 0; $handler = @opendir($_path); while($file = @readdir($handler)) { # checks if(($file == ".") || ($file == "..")) { continue; } $full_path = convertPathFile(get_absolute_path($_path.DIRECTORY_SEPARATOR.$file)); if($full_path == convertPathFile(__FILE__)) { continue; } $docontinue = false; foreach($config_files_exclude as $file_exclude) { if(isBaseDir($file_exclude) && startsWith($full_path, $file_exclude)) { $docontinue = true; } else if(!isBaseDir($file_exclude) && (strpos($file_exclude,DIRECTORY_SEPARATOR) !== true) && ($file == $file_exclude)) { $docontinue = true; } else if(!isBaseDir($file_exclude) && (strpos($file_exclude,DIRECTORY_SEPARATOR) !== false) && startsWith($_path, DIRECTORY_SEPARATOR.$file_exclude)) { $docontinue = true; } } if($docontinue) { continue; } # get file info $file_data = array(); $file_data['filename'] = $file; $file_data['path'] = $full_path; if(function_exists('realpath')) { $file_data['realpath'] = realpath($full_path); } if(function_exists('fileatime')) { $file_data['fileatime'] = @fileatime($full_path); } if(function_exists('filectime')) { $file_data['filectime'] = @filectime($full_path); } if(function_exists('fileinode')) { $file_data['fileinode'] = @fileinode($full_path); } if(function_exists('filemtime')) { $file_data['filemtime'] = @filemtime($full_path); } if(function_exists('fileperms')) { $file_data['fileperms'] = @fileperms($full_path); $file_data['fileperms_octal'] = @substr(sprintf('%o', @fileperms($full_path)), -4); $file_data['fileperms_readable'] = get_readable_permission(@fileperms($full_path)); } if(function_exists('filesize')) { $file_data['filesize'] = @filesize($full_path); if(function_exists('is_file') && @is_file($full_path)) { if(@filesize($full_path) < (1024 * 1024 * 10)) { $file_data['md5_file'] = @md5_file($full_path); $file_data['sha1_file'] = @sha1_file($full_path); } } } if(function_exists('filetype')) { $file_data['filetype'] = @filetype($full_path); } if(function_exists('is_dir')) { $file_data['is_dir'] = @is_dir($full_path); } if(function_exists('is_executable')) { $file_data['is_executable'] = @is_executable($full_path); } if(function_exists('is_file')) { $file_data['is_file'] = @is_file($full_path); } if(function_exists('is_link')) { $file_data['is_link'] = @is_link($full_path); } if(function_exists('is_readable')) { $file_data['is_readable'] = @is_readable($full_path); } if(function_exists('is_uploaded_file')) { $file_data['is_uploaded_file'] = @is_uploaded_file($full_path); } if(function_exists('is_writable')) { $file_data['is_writable'] = @is_writable($full_path); } if(function_exists('linkinfo')) { $file_data['linkinfo'] = @linkinfo($full_path); } if(function_exists('readlink')) { $link_path = @readlink($full_path); if(function_exists('is_dir') && @is_dir($full_path)) { $link_path = convertPathDir($link_path); } else if(function_exists('is_file') && @is_file($full_path)) { $link_path = convertPathFile($link_path); } else { $link_path = convertPathStartSlash($link_path); } if(startsWith($link_path, getBaseDir())) { $link_path = @substr($link_path, @strlen(getBaseDir())); } $link_path = convertPathStartSlash($link_path); $file_data['readlink'] = $link_path; } if(function_exists('stat')) { $stat = @stat($full_path); $file_data['stat_data'] = $stat; } if(function_exists('filegroup')) { $file_data['filegroup'] = @filegroup($full_path); if(function_exists('posix_getgrgid')) { $filegroup = @posix_getgrgid(@filegroup($full_path)); $file_data['filegroup_data'] = $filegroup; } } if(function_exists('fileowner')) { $file_data['fileowner'] = @fileowner($full_path); if(function_exists('posix_getpwuid')) { $fileowner = @posix_getpwuid(@fileowner($full_path)); $file_data['fileowner_data'] = $fileowner; } } $counter++; $all_files[] = $file_data; } @closedir($handler); $data_return = array(); $data_return['data'] = $all_files; $data_return['counter'] = $counter; $data_return['path'] = $_path; $data_return['status'] = "ok"; # var_dump($return_files); echo @json_encode($data_return); } # download function doDownloadFile($from) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); @readfile($from); } # upload function doUploadFile() { $to = get_received_variable("to"); $time_lastmodified = get_received_variable("time_lastmodified"); $time_accessed = get_received_variable("time_accessed"); $chmod = get_received_variable("chmod"); $chown = get_received_variable("chown"); $chgrp = get_received_variable("chgrp"); $to = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); if(@move_uploaded_file($_FILES['filename1']['tmp_name'], $to)) { if(function_exists('touch') && (($time_lastmodified != "") || ($time_accessed != ""))) { if($time_accessed == "") { @touch($to, $time_lastmodified); } else { @touch($to, $time_lastmodified, $time_accessed); } } if(function_exists('chmod') && ($chmod != "")) { @chmod($to, octdec($chmod)); } if(function_exists('chown') && ($chown != "")) { @chown($to, $chown); } if(function_exists('chgrp') && ($chgrp != "")) { @chgrp($to, $chgrp); } mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # delete function doDeleteFile($from) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@unlink($from)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } function doDeleteDir($from) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); rmdir_recursive($from); mssgOk("done", "Done"); } # copy function doCopyFile($from, $to) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $to = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); if(@copy($from, $to)) { set_same_times($from, $to); mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } function doCopyDir($from, $to) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $to = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); recurse_copy($from, $to); mssgOk("done", "Done"); } # rename function doRenameFile($from, $to) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $to = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); if(@rename($from, $to)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } function doRenameDir($from, $to) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $to = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); if(@rename($from, $to)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # create dir function doCreateDir($from) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@mkdir($from, 0777, true)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # exists function doExistsFile($from) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@file_exists($from)) { mssgOk("exists", "Exists"); } else { mssgOk("notexists", "Not exists"); } } function doExistsDir($from) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@file_exists($from)) { mssgOk("exists", "Exists"); } else { mssgOk("notexists", "Not exists"); } } # server information function serverInformation() { global $config, $current_user, $_SERVER, $_GET, $_POST, $_SESSION, $_ENV, $_FILES, $_COOKIE; $data_return = array(); if(function_exists('disk_free_space')) { $data_return['disk_free_space'] = @disk_free_space(getBaseDir()); } if(function_exists('disk_total_space')) { $data_return['disk_total_space'] = @disk_total_space(getBaseDir()); } $data_return['basedir'] = getBaseDir(); if(function_exists('phpversion')) { $data_return['phpversion'] = @phpversion(); } if(function_exists('curl_version')) { $data_return['curl_version'] = @curl_version(); } if(function_exists('sys_getloadavg')) { $data_return['sys_getloadavg'] = @sys_getloadavg(); } $data_return['config'] = $config; $data_return['current_user'] = $current_user; $data_return['status'] = "ok"; $data_return['phpinfo'] = phpinfo_array(true); $data_return['_SERVER'] = @$_SERVER; $data_return['_GET'] = @$_GET; $_POST['password'] = "*"; $data_return['_POST'] = @$_POST; $data_return['_SESSION'] = @$_SESSION; $data_return['_ENV'] = @$_ENV; # $data_return['_FILES'] = @$_FILES; # $data_return['_COOKIE'] = @$_COOKIE; echo @json_encode($data_return); } # chgrp function doChgrp($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@chgrp($from, $id)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # chmod function doChmod($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@chmod($from, octdec($id))) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # chown function doChown($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@chown($from, $id)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # clearstatcache function doClearstatcache() { @clearstatcache(); mssgOk("done", "Done"); } # lchgrp function doLchgrp($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@lchgrp($from, $id)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # lchown function doLchown($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@lchown($from, $id)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # link function doLink($from, $link) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $link = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$link)); if(@link($from, $link)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # symlink function doSymlink($from, $link) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $link = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$link)); if(@symlink($from, $link)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # touch function doTouch($from, $time, $atime) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if($atime == "") { if(@touch($from, $time)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } else { if(@touch($from, $time, $atime)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } } # umask function doUmask($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $umaskT = @umask($from, $id); mssgOk($umaskT, "Done"); } # unlink function doUnlink($from) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@unlink($from)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # server 2 server function doServer2Server() { # get_token1 # token1 # token2 # username # password # htpasswd # htpasswd username # htpasswd password # from # to $target_url = get_received_variable("dest_url"); $array_post = array( 'token1' => get_received_variable("dest_token1"), 'token2' => get_received_variable("dest_token2"), 'username' => get_received_variable("dest_username"), 'password' => get_received_variable("dest_password"), 'action' => get_received_variable("dest_action"), 'from' => get_received_variable("dest_from"), 'to' => get_received_variable("dest_to"), 'path' => get_received_variable("dest_path"), 'time_lastmodified' => get_received_variable("dest_time_lastmodified"), 'time_accessed' => get_received_variable("dest_time_accessed"), 'chmod' => get_received_variable("dest_chmod"), 'chown' => get_received_variable("dest_chown"), 'chgrp' => get_received_variable("dest_chgrp"), 'id' => get_received_variable("dest_id"), 'link' => get_received_variable("dest_link"), 'time' => get_received_variable("dest_time"), 'atime' => get_received_variable("dest_atime") ); if(get_received_variable("dest_action") == "upload") { $array_post_add1 = array( 'filename1'=>'@'.convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.get_received_variable("from"))) ); $array_post = array_merge($array_post, $array_post_add1); } $_curl = curl_init(); curl_setopt($_curl, CURLOPT_URL, $target_url); curl_setopt($_curl, CURLOPT_POST, 1); curl_setopt($_curl, CURLOPT_POSTFIELDS, $array_post); if(get_received_variable("dest_httpauth") != "") { curl_setopt($_curl, CURLOPT_USERPWD, get_received_variable("dest_httpauth_username").":".get_received_variable("dest_httpauth_password")); } # curl_setopt($_curl, CURLOPT_RETURNTRANSFER, 1); # $result = curl_exec($_curl); curl_exec($_curl); curl_close($_curl); # echo $result; } function mssgOk($_id, $_message) { $data_return = array(); $data_return['status'] = "ok"; $data_return['id'] = $_id; $data_return['message'] = $_message; echo @json_encode($data_return); } function mssgError($_id, $_message) { $data_return = array(); $data_return['status'] = "error"; $data_return['id'] = $_id; $data_return['message'] = $_message; echo @json_encode($data_return); } ### * OTHER ### function is_dir_allowed($_path) { global $config, $current_user; # if(!$current_user->path_forcestay) { # return true; # } $temp_basedir = convertPathDir($_path); if(startsWith($temp_basedir, getBaseDir())) { return true; } return false; } function getBaseDir() { global $config, $current_user; $return_path = DIRECTORY_SEPARATOR; if(@is_empty($config['path_default'])) { $return_path = pathinfo(__FILE__, PATHINFO_DIRNAME); } else { if(isBaseDir($config['path_default'])) { $return_path = $config['path_default']; } else { $return_path = pathinfo(__FILE__, PATHINFO_DIRNAME).DIRECTORY_SEPARATOR.$config['path_default']; } } if(!@is_empty($current_user->path_default)) { if(isBaseDir($current_user->path_default)) { $return_path = $current_user->path_default; } else { $return_path = $return_path.DIRECTORY_SEPARATOR.$current_user->path_default; } } $return_path = get_absolute_path($return_path); return convertPathDir($return_path); } function isBaseDir($_path) { if(!base_with_slash()) { if(strpos($_path,':') !== false) { return true; } else { return false; } } else { if(startsWith($_path, DIRECTORY_SEPARATOR)) { return true; } else { return false; } } } function convertPathDir($_path) { if(!endsWith($_path, DIRECTORY_SEPARATOR)) { $_path = $_path.DIRECTORY_SEPARATOR; } if(base_with_slash()) { if(!startsWith($_path, DIRECTORY_SEPARATOR)) { $_path = DIRECTORY_SEPARATOR.$_path; } } return $_path; } function convertPathFile($_path) { if(endsWith($_path, DIRECTORY_SEPARATOR)) { $_path = substr($_path, 0, -1); } if(base_with_slash()) { if(!startsWith($_path, DIRECTORY_SEPARATOR)) { $_path = DIRECTORY_SEPARATOR.$_path; } } return $_path; } function convertPathStartSlash($_path) { if(base_with_slash()) { if(!startsWith($_path, DIRECTORY_SEPARATOR)) { $_path = DIRECTORY_SEPARATOR.$_path; } } return $_path; } function base_with_slash() { if(startsWith(__FILE__, DIRECTORY_SEPARATOR)) { return true; } else { return false; } } function is_empty($_variable) { if(($_variable == null) || (empty($_variable)) || ($_variable = "")) { return true; } return false; } function get_received_variable($_variable) { global $config, $_POST, $_GET; # if($config['variables_post']) { return $_POST[$_variable]; # } else { # return $_GET[$_variable]; # } } function startsWith($haystack, $needle){ return $needle === "" || @strpos($haystack, $needle) === 0; } function endsWith($haystack, $needle){ return $needle === "" || @substr($haystack, -@strlen($needle)) === $needle; } function get_absolute_path($path) { $path = @str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path); $parts = @array_filter(@explode(DIRECTORY_SEPARATOR, $path), 'strlen'); $absolutes = array(); foreach ($parts as $part) { if ('.' == $part) continue; if ('..' == $part) { @array_pop($absolutes); } else { $absolutes[] = $part; } } return @implode(DIRECTORY_SEPARATOR, $absolutes); } function get_client_ip() { global $_SERVER; $ipaddress = ''; if ($_SERVER['HTTP_CLIENT_IP']) { $ipaddress = $_SERVER['HTTP_CLIENT_IP']; } else if($_SERVER['HTTP_X_FORWARDED_FOR']) { $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR']; } else if($_SERVER['HTTP_X_FORWARDED']) { $ipaddress = $_SERVER['HTTP_X_FORWARDED']; } else if($_SERVER['HTTP_FORWARDED_FOR']) { $ipaddress = $_SERVER['HTTP_FORWARDED_FOR']; } else if($_SERVER['HTTP_FORWARDED']) { $ipaddress = $_SERVER['HTTP_FORWARDED']; } else if($_SERVER['REMOTE_ADDR']) { $ipaddress = $_SERVER['REMOTE_ADDR']; } else { $ipaddress = 'UNKNOWN'; } return $ipaddress; } function get_readable_permission($perms) { if (($perms & 0xC000) == 0xC000) { # Socket $info = 's'; } elseif (($perms & 0xA000) == 0xA000) { # Symbolic Link $info = 'l'; } elseif (($perms & 0x8000) == 0x8000) { # Regular $info = '-'; } elseif (($perms & 0x6000) == 0x6000) { # Block special $info = 'b'; } elseif (($perms & 0x4000) == 0x4000) { # Directory $info = 'd'; } elseif (($perms & 0x2000) == 0x2000) { # Character special $info = 'c'; } elseif (($perms & 0x1000) == 0x1000) { # FIFO pipe $info = 'p'; } else { # Unknown $info = 'u'; } $info .= (($perms & 0x0100) ? 'r' : '-'); $info .= (($perms & 0x0080) ? 'w' : '-'); $info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-')); $info .= (($perms & 0x0020) ? 'r' : '-'); $info .= (($perms & 0x0010) ? 'w' : '-'); $info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-')); $info .= (($perms & 0x0004) ? 'r' : '-'); $info .= (($perms & 0x0002) ? 'w' : '-'); $info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-')); return $info; } function set_same_times($from, $to) { if(function_exists('touch')) { if(function_exists('filemtime') && function_exists('fileatime')) { @touch($to, @filemtime($from), @fileatime($from)); } else if(function_exists('filemtime')) { @touch($to, @filemtime($from)); } } } function recurse_copy($src,$dst) { $dir = @opendir($src); @mkdir($dst); set_same_times($src, $dst); while(false !== ( $file = @readdir($dir)) ) { if (( $file != '.' ) && ( $file != '..' )) { if ( @is_dir($src .DIRECTORY_SEPARATOR. $file) ) { recurse_copy($src .DIRECTORY_SEPARATOR. $file, $dst .DIRECTORY_SEPARATOR. $file); } else { @copy($src.DIRECTORY_SEPARATOR.$file, $dst.DIRECTORY_SEPARATOR.$file); set_same_times($src.DIRECTORY_SEPARATOR.$file, $dst.DIRECTORY_SEPARATOR.$file); } } } @closedir($dir); } function rmdir_recursive($dir) { foreach(scandir($dir) as $file) { if ('.' === $file || '..' === $file) continue; if (@is_dir($dir.DIRECTORY_SEPARATOR.$file)) rmdir_recursive($dir.DIRECTORY_SEPARATOR.$file); else @unlink($dir.DIRECTORY_SEPARATOR.$file); } @rmdir($dir); } function phpinfo_array($return=false){ @ob_start(); @phpinfo(-1); $pi = @preg_replace( array('#^.*<body>(.*)</body>.*$#ms', '#<h2>PHP License</h2>.*$#ms', '#<h1>Configuration</h1>#', "#\r?\n#", "#</(h1|h2|h3|tr)>#", '# +<#', "#[ \t]+#", '#&nbsp;#', '# +#', '# class=".*?"#', '%&#039;%', '#<tr>(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" /></a>' .'<h1>PHP Version (.*?)</h1>(?:\n+?)</td></tr>#', '#<h1><a href="(?:.*?)\?=(.*?)">PHP Credits</a></h1>#', '#<tr>(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)</tr>#', "# +#", '#<tr>#', '#</tr>#'), array('$1', '', '', '', '</$1>' . "\n", '<', ' ', ' ', ' ', '', ' ', '<h2>PHP Configuration</h2>'."\n".'<tr><td>PHP Version</td><td>$2</td></tr>'. "\n".'<tr><td>PHP Egg</td><td>$1</td></tr>', '<tr><td>PHP Credits Egg</td><td>$1</td></tr>', '<tr><td>Zend Engine</td><td>$2</td></tr>' . "\n" . '<tr><td>Zend Egg</td><td>$1</td></tr>', ' ', '%S%', '%E%'), @ob_get_clean()); $sections = @explode('<h2>', @strip_tags($pi, '<h2><th><td>')); unset($sections[0]); $pi = array(); foreach($sections as $section){ $n = @substr($section, 0, @strpos($section, '</h2>')); @preg_match_all( '#%S%(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?%E%#', $section, $askapache, PREG_SET_ORDER); foreach($askapache as $m) $pi[$n][$m[1]]=(!isset($m[3])||$m[2]==$m[3])?$m[2]:@array_slice($m,2); } return ($return === false) ? @print_r($pi) : $pi; } ### * DATA ### class User { public $anonymous = false; public $username = ""; public $password = ""; public $path_default = ""; public $permissions; public function __construct($anonymousT, $usernameT, $passwordT, $path_defaultT, $permissionsT) { $this->anonymous = $anonymousT; $this->username = $usernameT; $this->password = $<PASSWORD>; $this->path_default = $path_defaultT; $this->permissions = $permissionsT; } } class Permissions { public $allow_read = true; public $allow_write = true; public $allow_delete = true; public $allow_download = true; public $allow_upload = true; public $allow_serverinformation = true; public $allow_server2server = true; public function __construct($allow_readT, $allow_writeT, $allow_deleteT, $allow_downloadT, $allow_uploadT, $allow_serverinformationT, $allow_server2serverT) { $this->allow_read = $allow_readT; $this->allow_write = $allow_writeT; $this->allow_delete = $allow_deleteT; $this->allow_download = $allow_downloadT; $this->allow_upload = $allow_uploadT; $this->allow_serverinformation = $allow_serverinformationT; $this->allow_server2server = $allow_server2serverT; } } ?>
true
### * Ice Cold Apps * * GENERAL SETTINGS * * Warning: if you have problems to read, create or edit files/folder try to change the permissions to a higher octal number. This normally solves the problems. * ### class ICASync constructor: (@query) -> serve: -> return @["_#{@query.action}"].call(@) case "download": if(!$current_user->permissions->allow_read || !$current_user->permissions->allow_download) { mssgError("permission", "Permission error"); exit(); } doDownloadFile(get_received_variable("from")); break; case "upload": if(!$current_user->permissions->allow_write || !$current_user->permissions->allow_upload) { mssgError("permission", "Permission error"); exit(); } doUploadFile(); break; case "deletefile": if(!$current_user->permissions->allow_write || !$current_user->permissions->allow_delete) { mssgError("permission", "Permission error"); exit(); } doDeleteFile(get_received_variable("from")); break; case "deletedir": if(!$current_user->permissions->allow_write || !$current_user->permissions->allow_delete) { mssgError("permission", "Permission error"); exit(); } doDeleteDir(get_received_variable("from")); break; case "copyfile": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doCopyFile(get_received_variable("from"), get_received_variable("to")); break; case "copydir": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doCopyDir(get_received_variable("from"), get_received_variable("to")); break; case "renamefile": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doRenameFile(get_received_variable("from"), get_received_variable("to")); break; case "renamedir": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doRenameDir(get_received_variable("from"), get_received_variable("to")); break; case "createdir": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doCreateDir(get_received_variable("from")); break; case "existsfile": doExistsFile(get_received_variable("from")); break; case "existsdir": doExistsDir(get_received_variable("from")); break; case "serverinformation": if(!$current_user->permissions->allow_read || !$current_user->permissions->allow_serverinformation) { mssgError("permission", "Permission error"); exit(); } serverInformation(); break; case "chgrp": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doChgrp(get_received_variable("from"), get_received_variable("id")); break; case "chown": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doChown(get_received_variable("from"), get_received_variable("id")); break; case "chmod": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doChmod(get_received_variable("from"), get_received_variable("id")); break; case "clearstatcache": doClearstatcache(); break; case "lchgrp": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doLchgrp(get_received_variable("from"), get_received_variable("id")); break; case "lchown": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doLchown(get_received_variable("from"), get_received_variable("id")); break; case "link": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doLink(get_received_variable("from"), get_received_variable("link")); break; case "symlink": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doSymlink(get_received_variable("from"), get_received_variable("link")); break; case "touch": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doTouch(get_received_variable("from"), get_received_variable("time"), get_received_variable("atime")); break; case "umask": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doUmask(get_received_variable("from"), get_received_variable("id")); break; case "unlink": if(!$current_user->permissions->allow_write) { mssgError("permission", "Permission error"); exit(); } doUnlink(get_received_variable("from")); break; case "server2server": if(!$current_user->permissions->allow_server2server) { mssgError("permission", "Permission error"); exit(); } doServer2Server(); break; } return; # general information _generalinformation: -> data_return = {} data_return.version = "1.0.2" data_return.version_code = 2 # data_return['phpversion'] = @phpversion(); data_return.functions_available = {} for k of @ continue unless k[0] == '_' data_return.functions_available[k.slice(1)] = true data_return.status = "ok" return JSON.stringify(data_return) listfiles: -> if !@query.path # user library else # compute location from path # if path doesn't exist, throw error all_files = [] counter = 0; $handler = @opendir($_path); while($file = @readdir($handler)) { # checks if(($file == ".") || ($file == "..")) { continue; } $full_path = convertPathFile(get_absolute_path($_path.DIRECTORY_SEPARATOR.$file)); if($full_path == convertPathFile(__FILE__)) { continue; } $docontinue = false; foreach($config_files_exclude as $file_exclude) { if(isBaseDir($file_exclude) && startsWith($full_path, $file_exclude)) { $docontinue = true; } else if(!isBaseDir($file_exclude) && (strpos($file_exclude,DIRECTORY_SEPARATOR) !== true) && ($file == $file_exclude)) { $docontinue = true; } else if(!isBaseDir($file_exclude) && (strpos($file_exclude,DIRECTORY_SEPARATOR) !== false) && startsWith($_path, DIRECTORY_SEPARATOR.$file_exclude)) { $docontinue = true; } } if($docontinue) { continue; } # get file info $file_data = array(); $file_data['filename'] = $file; $file_data['path'] = $full_path; if(function_exists('realpath')) { $file_data['realpath'] = realpath($full_path); } if(function_exists('fileatime')) { $file_data['fileatime'] = @fileatime($full_path); } if(function_exists('filectime')) { $file_data['filectime'] = @filectime($full_path); } if(function_exists('fileinode')) { $file_data['fileinode'] = @fileinode($full_path); } if(function_exists('filemtime')) { $file_data['filemtime'] = @filemtime($full_path); } if(function_exists('fileperms')) { $file_data['fileperms'] = @fileperms($full_path); $file_data['fileperms_octal'] = @substr(sprintf('%o', @fileperms($full_path)), -4); $file_data['fileperms_readable'] = get_readable_permission(@fileperms($full_path)); } if(function_exists('filesize')) { $file_data['filesize'] = @filesize($full_path); if(function_exists('is_file') && @is_file($full_path)) { if(@filesize($full_path) < (1024 * 1024 * 10)) { $file_data['md5_file'] = @md5_file($full_path); $file_data['sha1_file'] = @sha1_file($full_path); } } } if(function_exists('filetype')) { $file_data['filetype'] = @filetype($full_path); } if(function_exists('is_dir')) { $file_data['is_dir'] = @is_dir($full_path); } if(function_exists('is_executable')) { $file_data['is_executable'] = @is_executable($full_path); } if(function_exists('is_file')) { $file_data['is_file'] = @is_file($full_path); } if(function_exists('is_link')) { $file_data['is_link'] = @is_link($full_path); } if(function_exists('is_readable')) { $file_data['is_readable'] = @is_readable($full_path); } if(function_exists('is_uploaded_file')) { $file_data['is_uploaded_file'] = @is_uploaded_file($full_path); } if(function_exists('is_writable')) { $file_data['is_writable'] = @is_writable($full_path); } if(function_exists('linkinfo')) { $file_data['linkinfo'] = @linkinfo($full_path); } if(function_exists('readlink')) { $link_path = @readlink($full_path); if(function_exists('is_dir') && @is_dir($full_path)) { $link_path = convertPathDir($link_path); } else if(function_exists('is_file') && @is_file($full_path)) { $link_path = convertPathFile($link_path); } else { $link_path = convertPathStartSlash($link_path); } if(startsWith($link_path, getBaseDir())) { $link_path = @substr($link_path, @strlen(getBaseDir())); } $link_path = convertPathStartSlash($link_path); $file_data['readlink'] = $link_path; } if(function_exists('stat')) { $stat = @stat($full_path); $file_data['stat_data'] = $stat; } if(function_exists('filegroup')) { $file_data['filegroup'] = @filegroup($full_path); if(function_exists('posix_getgrgid')) { $filegroup = @posix_getgrgid(@filegroup($full_path)); $file_data['filegroup_data'] = $filegroup; } } if(function_exists('fileowner')) { $file_data['fileowner'] = @fileowner($full_path); if(function_exists('posix_getpwuid')) { $fileowner = @posix_getpwuid(@fileowner($full_path)); $file_data['fileowner_data'] = $fileowner; } } $counter++; $all_files[] = $file_data; } @closedir($handler); $data_return = array(); $data_return['data'] = $all_files; $data_return['counter'] = $counter; $data_return['path'] = $_path; $data_return['status'] = "ok"; # var_dump($return_files); echo @json_encode($data_return); } # download function doDownloadFile($from) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); @readfile($from); } # upload function doUploadFile() { $to = get_received_variable("to"); $time_lastmodified = get_received_variable("time_lastmodified"); $time_accessed = get_received_variable("time_accessed"); $chmod = get_received_variable("chmod"); $chown = get_received_variable("chown"); $chgrp = get_received_variable("chgrp"); $to = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); if(@move_uploaded_file($_FILES['filename1']['tmp_name'], $to)) { if(function_exists('touch') && (($time_lastmodified != "") || ($time_accessed != ""))) { if($time_accessed == "") { @touch($to, $time_lastmodified); } else { @touch($to, $time_lastmodified, $time_accessed); } } if(function_exists('chmod') && ($chmod != "")) { @chmod($to, octdec($chmod)); } if(function_exists('chown') && ($chown != "")) { @chown($to, $chown); } if(function_exists('chgrp') && ($chgrp != "")) { @chgrp($to, $chgrp); } mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # delete function doDeleteFile($from) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@unlink($from)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } function doDeleteDir($from) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); rmdir_recursive($from); mssgOk("done", "Done"); } # copy function doCopyFile($from, $to) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $to = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); if(@copy($from, $to)) { set_same_times($from, $to); mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } function doCopyDir($from, $to) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $to = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); recurse_copy($from, $to); mssgOk("done", "Done"); } # rename function doRenameFile($from, $to) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $to = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); if(@rename($from, $to)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } function doRenameDir($from, $to) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $to = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$to)); if(@rename($from, $to)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # create dir function doCreateDir($from) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@mkdir($from, 0777, true)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # exists function doExistsFile($from) { $from = convertPathFile(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@file_exists($from)) { mssgOk("exists", "Exists"); } else { mssgOk("notexists", "Not exists"); } } function doExistsDir($from) { $from = convertPathDir(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@file_exists($from)) { mssgOk("exists", "Exists"); } else { mssgOk("notexists", "Not exists"); } } # server information function serverInformation() { global $config, $current_user, $_SERVER, $_GET, $_POST, $_SESSION, $_ENV, $_FILES, $_COOKIE; $data_return = array(); if(function_exists('disk_free_space')) { $data_return['disk_free_space'] = @disk_free_space(getBaseDir()); } if(function_exists('disk_total_space')) { $data_return['disk_total_space'] = @disk_total_space(getBaseDir()); } $data_return['basedir'] = getBaseDir(); if(function_exists('phpversion')) { $data_return['phpversion'] = @phpversion(); } if(function_exists('curl_version')) { $data_return['curl_version'] = @curl_version(); } if(function_exists('sys_getloadavg')) { $data_return['sys_getloadavg'] = @sys_getloadavg(); } $data_return['config'] = $config; $data_return['current_user'] = $current_user; $data_return['status'] = "ok"; $data_return['phpinfo'] = phpinfo_array(true); $data_return['_SERVER'] = @$_SERVER; $data_return['_GET'] = @$_GET; $_POST['password'] = "*"; $data_return['_POST'] = @$_POST; $data_return['_SESSION'] = @$_SESSION; $data_return['_ENV'] = @$_ENV; # $data_return['_FILES'] = @$_FILES; # $data_return['_COOKIE'] = @$_COOKIE; echo @json_encode($data_return); } # chgrp function doChgrp($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@chgrp($from, $id)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # chmod function doChmod($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@chmod($from, octdec($id))) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # chown function doChown($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@chown($from, $id)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # clearstatcache function doClearstatcache() { @clearstatcache(); mssgOk("done", "Done"); } # lchgrp function doLchgrp($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@lchgrp($from, $id)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # lchown function doLchown($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@lchown($from, $id)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # link function doLink($from, $link) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $link = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$link)); if(@link($from, $link)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # symlink function doSymlink($from, $link) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $link = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$link)); if(@symlink($from, $link)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # touch function doTouch($from, $time, $atime) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if($atime == "") { if(@touch($from, $time)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } else { if(@touch($from, $time, $atime)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } } # umask function doUmask($from, $id) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); $umaskT = @umask($from, $id); mssgOk($umaskT, "Done"); } # unlink function doUnlink($from) { $from = convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.$from)); if(@unlink($from)) { mssgOk("done", "Done"); } else { mssgError("error", "Error"); } } # server 2 server function doServer2Server() { # get_token1 # token1 # token2 # username # password # htpasswd # htpasswd username # htpasswd password # from # to $target_url = get_received_variable("dest_url"); $array_post = array( 'token1' => get_received_variable("dest_token1"), 'token2' => get_received_variable("dest_token2"), 'username' => get_received_variable("dest_username"), 'password' => get_received_variable("dest_password"), 'action' => get_received_variable("dest_action"), 'from' => get_received_variable("dest_from"), 'to' => get_received_variable("dest_to"), 'path' => get_received_variable("dest_path"), 'time_lastmodified' => get_received_variable("dest_time_lastmodified"), 'time_accessed' => get_received_variable("dest_time_accessed"), 'chmod' => get_received_variable("dest_chmod"), 'chown' => get_received_variable("dest_chown"), 'chgrp' => get_received_variable("dest_chgrp"), 'id' => get_received_variable("dest_id"), 'link' => get_received_variable("dest_link"), 'time' => get_received_variable("dest_time"), 'atime' => get_received_variable("dest_atime") ); if(get_received_variable("dest_action") == "upload") { $array_post_add1 = array( 'filename1'=>'@'.convertPathStartSlash(get_absolute_path(getBaseDir().DIRECTORY_SEPARATOR.get_received_variable("from"))) ); $array_post = array_merge($array_post, $array_post_add1); } $_curl = curl_init(); curl_setopt($_curl, CURLOPT_URL, $target_url); curl_setopt($_curl, CURLOPT_POST, 1); curl_setopt($_curl, CURLOPT_POSTFIELDS, $array_post); if(get_received_variable("dest_httpauth") != "") { curl_setopt($_curl, CURLOPT_USERPWD, get_received_variable("dest_httpauth_username").":".get_received_variable("dest_httpauth_password")); } # curl_setopt($_curl, CURLOPT_RETURNTRANSFER, 1); # $result = curl_exec($_curl); curl_exec($_curl); curl_close($_curl); # echo $result; } function mssgOk($_id, $_message) { $data_return = array(); $data_return['status'] = "ok"; $data_return['id'] = $_id; $data_return['message'] = $_message; echo @json_encode($data_return); } function mssgError($_id, $_message) { $data_return = array(); $data_return['status'] = "error"; $data_return['id'] = $_id; $data_return['message'] = $_message; echo @json_encode($data_return); } ### * OTHER ### function is_dir_allowed($_path) { global $config, $current_user; # if(!$current_user->path_forcestay) { # return true; # } $temp_basedir = convertPathDir($_path); if(startsWith($temp_basedir, getBaseDir())) { return true; } return false; } function getBaseDir() { global $config, $current_user; $return_path = DIRECTORY_SEPARATOR; if(@is_empty($config['path_default'])) { $return_path = pathinfo(__FILE__, PATHINFO_DIRNAME); } else { if(isBaseDir($config['path_default'])) { $return_path = $config['path_default']; } else { $return_path = pathinfo(__FILE__, PATHINFO_DIRNAME).DIRECTORY_SEPARATOR.$config['path_default']; } } if(!@is_empty($current_user->path_default)) { if(isBaseDir($current_user->path_default)) { $return_path = $current_user->path_default; } else { $return_path = $return_path.DIRECTORY_SEPARATOR.$current_user->path_default; } } $return_path = get_absolute_path($return_path); return convertPathDir($return_path); } function isBaseDir($_path) { if(!base_with_slash()) { if(strpos($_path,':') !== false) { return true; } else { return false; } } else { if(startsWith($_path, DIRECTORY_SEPARATOR)) { return true; } else { return false; } } } function convertPathDir($_path) { if(!endsWith($_path, DIRECTORY_SEPARATOR)) { $_path = $_path.DIRECTORY_SEPARATOR; } if(base_with_slash()) { if(!startsWith($_path, DIRECTORY_SEPARATOR)) { $_path = DIRECTORY_SEPARATOR.$_path; } } return $_path; } function convertPathFile($_path) { if(endsWith($_path, DIRECTORY_SEPARATOR)) { $_path = substr($_path, 0, -1); } if(base_with_slash()) { if(!startsWith($_path, DIRECTORY_SEPARATOR)) { $_path = DIRECTORY_SEPARATOR.$_path; } } return $_path; } function convertPathStartSlash($_path) { if(base_with_slash()) { if(!startsWith($_path, DIRECTORY_SEPARATOR)) { $_path = DIRECTORY_SEPARATOR.$_path; } } return $_path; } function base_with_slash() { if(startsWith(__FILE__, DIRECTORY_SEPARATOR)) { return true; } else { return false; } } function is_empty($_variable) { if(($_variable == null) || (empty($_variable)) || ($_variable = "")) { return true; } return false; } function get_received_variable($_variable) { global $config, $_POST, $_GET; # if($config['variables_post']) { return $_POST[$_variable]; # } else { # return $_GET[$_variable]; # } } function startsWith($haystack, $needle){ return $needle === "" || @strpos($haystack, $needle) === 0; } function endsWith($haystack, $needle){ return $needle === "" || @substr($haystack, -@strlen($needle)) === $needle; } function get_absolute_path($path) { $path = @str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path); $parts = @array_filter(@explode(DIRECTORY_SEPARATOR, $path), 'strlen'); $absolutes = array(); foreach ($parts as $part) { if ('.' == $part) continue; if ('..' == $part) { @array_pop($absolutes); } else { $absolutes[] = $part; } } return @implode(DIRECTORY_SEPARATOR, $absolutes); } function get_client_ip() { global $_SERVER; $ipaddress = ''; if ($_SERVER['HTTP_CLIENT_IP']) { $ipaddress = $_SERVER['HTTP_CLIENT_IP']; } else if($_SERVER['HTTP_X_FORWARDED_FOR']) { $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR']; } else if($_SERVER['HTTP_X_FORWARDED']) { $ipaddress = $_SERVER['HTTP_X_FORWARDED']; } else if($_SERVER['HTTP_FORWARDED_FOR']) { $ipaddress = $_SERVER['HTTP_FORWARDED_FOR']; } else if($_SERVER['HTTP_FORWARDED']) { $ipaddress = $_SERVER['HTTP_FORWARDED']; } else if($_SERVER['REMOTE_ADDR']) { $ipaddress = $_SERVER['REMOTE_ADDR']; } else { $ipaddress = 'UNKNOWN'; } return $ipaddress; } function get_readable_permission($perms) { if (($perms & 0xC000) == 0xC000) { # Socket $info = 's'; } elseif (($perms & 0xA000) == 0xA000) { # Symbolic Link $info = 'l'; } elseif (($perms & 0x8000) == 0x8000) { # Regular $info = '-'; } elseif (($perms & 0x6000) == 0x6000) { # Block special $info = 'b'; } elseif (($perms & 0x4000) == 0x4000) { # Directory $info = 'd'; } elseif (($perms & 0x2000) == 0x2000) { # Character special $info = 'c'; } elseif (($perms & 0x1000) == 0x1000) { # FIFO pipe $info = 'p'; } else { # Unknown $info = 'u'; } $info .= (($perms & 0x0100) ? 'r' : '-'); $info .= (($perms & 0x0080) ? 'w' : '-'); $info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-')); $info .= (($perms & 0x0020) ? 'r' : '-'); $info .= (($perms & 0x0010) ? 'w' : '-'); $info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-')); $info .= (($perms & 0x0004) ? 'r' : '-'); $info .= (($perms & 0x0002) ? 'w' : '-'); $info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-')); return $info; } function set_same_times($from, $to) { if(function_exists('touch')) { if(function_exists('filemtime') && function_exists('fileatime')) { @touch($to, @filemtime($from), @fileatime($from)); } else if(function_exists('filemtime')) { @touch($to, @filemtime($from)); } } } function recurse_copy($src,$dst) { $dir = @opendir($src); @mkdir($dst); set_same_times($src, $dst); while(false !== ( $file = @readdir($dir)) ) { if (( $file != '.' ) && ( $file != '..' )) { if ( @is_dir($src .DIRECTORY_SEPARATOR. $file) ) { recurse_copy($src .DIRECTORY_SEPARATOR. $file, $dst .DIRECTORY_SEPARATOR. $file); } else { @copy($src.DIRECTORY_SEPARATOR.$file, $dst.DIRECTORY_SEPARATOR.$file); set_same_times($src.DIRECTORY_SEPARATOR.$file, $dst.DIRECTORY_SEPARATOR.$file); } } } @closedir($dir); } function rmdir_recursive($dir) { foreach(scandir($dir) as $file) { if ('.' === $file || '..' === $file) continue; if (@is_dir($dir.DIRECTORY_SEPARATOR.$file)) rmdir_recursive($dir.DIRECTORY_SEPARATOR.$file); else @unlink($dir.DIRECTORY_SEPARATOR.$file); } @rmdir($dir); } function phpinfo_array($return=false){ @ob_start(); @phpinfo(-1); $pi = @preg_replace( array('#^.*<body>(.*)</body>.*$#ms', '#<h2>PHP License</h2>.*$#ms', '#<h1>Configuration</h1>#', "#\r?\n#", "#</(h1|h2|h3|tr)>#", '# +<#', "#[ \t]+#", '#&nbsp;#', '# +#', '# class=".*?"#', '%&#039;%', '#<tr>(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" /></a>' .'<h1>PHP Version (.*?)</h1>(?:\n+?)</td></tr>#', '#<h1><a href="(?:.*?)\?=(.*?)">PHP Credits</a></h1>#', '#<tr>(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)</tr>#', "# +#", '#<tr>#', '#</tr>#'), array('$1', '', '', '', '</$1>' . "\n", '<', ' ', ' ', ' ', '', ' ', '<h2>PHP Configuration</h2>'."\n".'<tr><td>PHP Version</td><td>$2</td></tr>'. "\n".'<tr><td>PHP Egg</td><td>$1</td></tr>', '<tr><td>PHP Credits Egg</td><td>$1</td></tr>', '<tr><td>Zend Engine</td><td>$2</td></tr>' . "\n" . '<tr><td>Zend Egg</td><td>$1</td></tr>', ' ', '%S%', '%E%'), @ob_get_clean()); $sections = @explode('<h2>', @strip_tags($pi, '<h2><th><td>')); unset($sections[0]); $pi = array(); foreach($sections as $section){ $n = @substr($section, 0, @strpos($section, '</h2>')); @preg_match_all( '#%S%(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?%E%#', $section, $askapache, PREG_SET_ORDER); foreach($askapache as $m) $pi[$n][$m[1]]=(!isset($m[3])||$m[2]==$m[3])?$m[2]:@array_slice($m,2); } return ($return === false) ? @print_r($pi) : $pi; } ### * DATA ### class User { public $anonymous = false; public $username = ""; public $password = ""; public $path_default = ""; public $permissions; public function __construct($anonymousT, $usernameT, $passwordT, $path_defaultT, $permissionsT) { $this->anonymous = $anonymousT; $this->username = $usernameT; $this->password = $PI:PASSWORD:<PASSWORD>END_PI; $this->path_default = $path_defaultT; $this->permissions = $permissionsT; } } class Permissions { public $allow_read = true; public $allow_write = true; public $allow_delete = true; public $allow_download = true; public $allow_upload = true; public $allow_serverinformation = true; public $allow_server2server = true; public function __construct($allow_readT, $allow_writeT, $allow_deleteT, $allow_downloadT, $allow_uploadT, $allow_serverinformationT, $allow_server2serverT) { $this->allow_read = $allow_readT; $this->allow_write = $allow_writeT; $this->allow_delete = $allow_deleteT; $this->allow_download = $allow_downloadT; $this->allow_upload = $allow_uploadT; $this->allow_serverinformation = $allow_serverinformationT; $this->allow_server2server = $allow_server2serverT; } } ?>
[ { "context": "# Copyright (c) 2008-2014 Michael Dvorkin and contributors.\n#\n# Fat Free CRM is freely dist", "end": 41, "score": 0.9998655319213867, "start": 26, "tag": "NAME", "value": "Michael Dvorkin" } ]
app/assets/javascripts/crm_select2.js.coffee
hoppinger/free_crm
0
# Copyright (c) 2008-2014 Michael Dvorkin and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ # Any select box with 'select2' class will be transformed (($) -> window.crm ||= {} crm.make_select2 = -> $("select.select2").each -> $(this).select2 'width':'resolve' $("select.select2_clear").each -> $(this).select2 'width': 'resolve' 'allowClear': true 'placeholder': '' $(".select2_tag").each -> $(this).select2 'width':'resolve' tags: $(this).data("tags") placeholder: $(this).data("placeholder") multiple: $(this).data("multiple") $(document).ready -> crm.make_select2() $(document).ajaxComplete -> crm.make_select2() ) jQuery
32062
# Copyright (c) 2008-2014 <NAME> and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ # Any select box with 'select2' class will be transformed (($) -> window.crm ||= {} crm.make_select2 = -> $("select.select2").each -> $(this).select2 'width':'resolve' $("select.select2_clear").each -> $(this).select2 'width': 'resolve' 'allowClear': true 'placeholder': '' $(".select2_tag").each -> $(this).select2 'width':'resolve' tags: $(this).data("tags") placeholder: $(this).data("placeholder") multiple: $(this).data("multiple") $(document).ready -> crm.make_select2() $(document).ajaxComplete -> crm.make_select2() ) jQuery
true
# Copyright (c) 2008-2014 PI:NAME:<NAME>END_PI and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ # Any select box with 'select2' class will be transformed (($) -> window.crm ||= {} crm.make_select2 = -> $("select.select2").each -> $(this).select2 'width':'resolve' $("select.select2_clear").each -> $(this).select2 'width': 'resolve' 'allowClear': true 'placeholder': '' $(".select2_tag").each -> $(this).select2 'width':'resolve' tags: $(this).data("tags") placeholder: $(this).data("placeholder") multiple: $(this).data("multiple") $(document).ready -> crm.make_select2() $(document).ajaxComplete -> crm.make_select2() ) jQuery
[ { "context": "##\n params = {\n title: \"pepe\"\n descripcion: \"lalala\"\n ", "end": 5339, "score": 0.9056947231292725, "start": 5335, "tag": "NAME", "value": "pepe" } ]
public/javascripts/app-backbone.coffee
develvad/NodeCMS
1
(($) -> #$(document).ready() window.mycms = {} mycms.NoticiaModel = Backbone.Model.extend( urlRoot: '/api/noticia' initialize: -> console.log "init model noticia" parse: (response, options) -> if response.status is 200 return response.noticia return response ) mycms.NoticiasCollection = Backbone.Collection.extend( model: mycms.NoticiaModel url: "/api/noticias" initialize: -> console.log "init collection noticias" parse: (response, options) -> if response.status is 200 return response.noticias return response ) # Test model and collection #noticia = new mycms.NoticiaModel() #noticias = new mycms.NoticiasCollection() #console.log noticia # muestro mi modelo #console.log noticias # muestro mi coleccion de modelos # Main View class. Controlls all events and behaviors of the application. mycms.NoticiasNewView = Backbone.View.extend( el: $('#mainView') # View's contructor. # Initialize event listeners, and update DOM elements state. initialize: (options) -> _.bindAll(@, 'render') console.log "Init NoticiasNewView" @render() render: -> template = _.template( $("#noticiasNewTemplate").html()) $(@el).html(template) ) # Main View class. Controlls all events and behaviors of the application. mycms.PerfilView = Backbone.View.extend( el: $('#mainView') # View's contructor. # Initialize event listeners, and update DOM elements state. initialize: (options) -> _.bindAll(@, 'render') console.log "Init perfilView" @render() render: -> template = _.template( $("#perfilTemplate").html()) $(@el).html(template) ) # Main View class. Controlls all events and behaviors of the application. mycms.NoticiasView = Backbone.View.extend( el: $('#mainView') # View's contructor. # Initialize event listeners, and update DOM elements state. initialize: (options) -> _.bindAll(@, 'render') console.log "Init NoticiasView" @render() render: -> template = _.template($('#noticiasTemplate').html(), {noticias: @collection.toJSON()}) this.$el.html(template) ) # Main View class. Controlls all events and behaviors of the application. mycms.IndexView = Backbone.View.extend( # element el: $('#mainView') # View's contructor. # Initialize event listeners, and update DOM elements state. initialize: (options) -> _.bindAll(@, 'render') console.log "Init IndexView" @render() render: -> template = _.template( $("#indexTemplate").html()) $(@el).html(template) ) mycms.SubheaderView = Backbone.View.extend( el: $('#subheader') events: "click .js-dashboard": "home" "click .js-perfil": "perfil" "click .js-noticias": "noticias" "click .js-noticias_new": "noticias_new" initialize: (options) -> _.bindAll(@, 'render') console.log "Init LinksHeaderView" @render() home: -> console.log "home" app.navigate("/panel", true) perfil: -> console.log "perfil" app.navigate("/panel/perfil", true) noticias: -> console.log "noticias" app.navigate("/panel/noticias", true) noticias_new: -> console.log "noticias_new" app.navigate("/panel/noticias/new", true) render: -> template = _.template( $("#subHeaderTemplate").html()) $(@el).append(template) ) # Creamos el Backbone Router, quien "escuchará los cambios en la URL # y ejecutará las respectivas acciones" mycms.AppRouter = Backbone.Router.extend( # Rutas : accion routes: "panel": "index", "panel/perfil": "perfil", "panel/noticias": "noticias", "panel/noticias/new": "noticias_new" initialize: -> console.log "init router" @SubheaderView = new mycms.SubheaderView() index: -> console.log "router index" @IndexView = new mycms.IndexView() perfil: -> console.log "router perfil" @PerfilView = new mycms.PerfilView() noticias: -> console.log "router noticias" col = new mycms.NoticiasCollection() # Usamos método de Backbone .fetch que lanzará una petición GET ajax a /noticias # Usamos método de Backbone .save que lanzará una petición POST ajax a /noticias # Usamos método de Backbone .save que lanzará una petición PUT ajax a /noticias # Usamos método de Backbone .destroy que lanzará una petición DELETE ajax a /noticias # (si el objeto modelo tiene _id -si no es nuevo) ### params = { title: "pepe" descripcion: "lalala" } # Esto lanza un AJAX POST a /noticias modelo.save(params) # Esto lanza un AJAX PUT a /noticias (Ya existe ese modelo en el server) modelo.save(params) #$.ajax('/api/noticias', ......) ### col.fetch( wait:true, success: (collection, response, options) => console.log "fetched noticias" console.log collection console.log response # Ya tenemos nuestra Collección con 50 noticias # Ahora creamos la vista y le pasamos la colección para que las muestre @NoticiasView = new mycms.NoticiasView( collection: collection ) ) noticias_new: -> console.log "router noticias New" @NoticiasNewView = new mycms.NoticiasNewView() ) # start backbone routing app = new mycms.AppRouter() Backbone.history.start(pushState: true) ) (jQuery)
193912
(($) -> #$(document).ready() window.mycms = {} mycms.NoticiaModel = Backbone.Model.extend( urlRoot: '/api/noticia' initialize: -> console.log "init model noticia" parse: (response, options) -> if response.status is 200 return response.noticia return response ) mycms.NoticiasCollection = Backbone.Collection.extend( model: mycms.NoticiaModel url: "/api/noticias" initialize: -> console.log "init collection noticias" parse: (response, options) -> if response.status is 200 return response.noticias return response ) # Test model and collection #noticia = new mycms.NoticiaModel() #noticias = new mycms.NoticiasCollection() #console.log noticia # muestro mi modelo #console.log noticias # muestro mi coleccion de modelos # Main View class. Controlls all events and behaviors of the application. mycms.NoticiasNewView = Backbone.View.extend( el: $('#mainView') # View's contructor. # Initialize event listeners, and update DOM elements state. initialize: (options) -> _.bindAll(@, 'render') console.log "Init NoticiasNewView" @render() render: -> template = _.template( $("#noticiasNewTemplate").html()) $(@el).html(template) ) # Main View class. Controlls all events and behaviors of the application. mycms.PerfilView = Backbone.View.extend( el: $('#mainView') # View's contructor. # Initialize event listeners, and update DOM elements state. initialize: (options) -> _.bindAll(@, 'render') console.log "Init perfilView" @render() render: -> template = _.template( $("#perfilTemplate").html()) $(@el).html(template) ) # Main View class. Controlls all events and behaviors of the application. mycms.NoticiasView = Backbone.View.extend( el: $('#mainView') # View's contructor. # Initialize event listeners, and update DOM elements state. initialize: (options) -> _.bindAll(@, 'render') console.log "Init NoticiasView" @render() render: -> template = _.template($('#noticiasTemplate').html(), {noticias: @collection.toJSON()}) this.$el.html(template) ) # Main View class. Controlls all events and behaviors of the application. mycms.IndexView = Backbone.View.extend( # element el: $('#mainView') # View's contructor. # Initialize event listeners, and update DOM elements state. initialize: (options) -> _.bindAll(@, 'render') console.log "Init IndexView" @render() render: -> template = _.template( $("#indexTemplate").html()) $(@el).html(template) ) mycms.SubheaderView = Backbone.View.extend( el: $('#subheader') events: "click .js-dashboard": "home" "click .js-perfil": "perfil" "click .js-noticias": "noticias" "click .js-noticias_new": "noticias_new" initialize: (options) -> _.bindAll(@, 'render') console.log "Init LinksHeaderView" @render() home: -> console.log "home" app.navigate("/panel", true) perfil: -> console.log "perfil" app.navigate("/panel/perfil", true) noticias: -> console.log "noticias" app.navigate("/panel/noticias", true) noticias_new: -> console.log "noticias_new" app.navigate("/panel/noticias/new", true) render: -> template = _.template( $("#subHeaderTemplate").html()) $(@el).append(template) ) # Creamos el Backbone Router, quien "escuchará los cambios en la URL # y ejecutará las respectivas acciones" mycms.AppRouter = Backbone.Router.extend( # Rutas : accion routes: "panel": "index", "panel/perfil": "perfil", "panel/noticias": "noticias", "panel/noticias/new": "noticias_new" initialize: -> console.log "init router" @SubheaderView = new mycms.SubheaderView() index: -> console.log "router index" @IndexView = new mycms.IndexView() perfil: -> console.log "router perfil" @PerfilView = new mycms.PerfilView() noticias: -> console.log "router noticias" col = new mycms.NoticiasCollection() # Usamos método de Backbone .fetch que lanzará una petición GET ajax a /noticias # Usamos método de Backbone .save que lanzará una petición POST ajax a /noticias # Usamos método de Backbone .save que lanzará una petición PUT ajax a /noticias # Usamos método de Backbone .destroy que lanzará una petición DELETE ajax a /noticias # (si el objeto modelo tiene _id -si no es nuevo) ### params = { title: "<NAME>" descripcion: "lalala" } # Esto lanza un AJAX POST a /noticias modelo.save(params) # Esto lanza un AJAX PUT a /noticias (Ya existe ese modelo en el server) modelo.save(params) #$.ajax('/api/noticias', ......) ### col.fetch( wait:true, success: (collection, response, options) => console.log "fetched noticias" console.log collection console.log response # Ya tenemos nuestra Collección con 50 noticias # Ahora creamos la vista y le pasamos la colección para que las muestre @NoticiasView = new mycms.NoticiasView( collection: collection ) ) noticias_new: -> console.log "router noticias New" @NoticiasNewView = new mycms.NoticiasNewView() ) # start backbone routing app = new mycms.AppRouter() Backbone.history.start(pushState: true) ) (jQuery)
true
(($) -> #$(document).ready() window.mycms = {} mycms.NoticiaModel = Backbone.Model.extend( urlRoot: '/api/noticia' initialize: -> console.log "init model noticia" parse: (response, options) -> if response.status is 200 return response.noticia return response ) mycms.NoticiasCollection = Backbone.Collection.extend( model: mycms.NoticiaModel url: "/api/noticias" initialize: -> console.log "init collection noticias" parse: (response, options) -> if response.status is 200 return response.noticias return response ) # Test model and collection #noticia = new mycms.NoticiaModel() #noticias = new mycms.NoticiasCollection() #console.log noticia # muestro mi modelo #console.log noticias # muestro mi coleccion de modelos # Main View class. Controlls all events and behaviors of the application. mycms.NoticiasNewView = Backbone.View.extend( el: $('#mainView') # View's contructor. # Initialize event listeners, and update DOM elements state. initialize: (options) -> _.bindAll(@, 'render') console.log "Init NoticiasNewView" @render() render: -> template = _.template( $("#noticiasNewTemplate").html()) $(@el).html(template) ) # Main View class. Controlls all events and behaviors of the application. mycms.PerfilView = Backbone.View.extend( el: $('#mainView') # View's contructor. # Initialize event listeners, and update DOM elements state. initialize: (options) -> _.bindAll(@, 'render') console.log "Init perfilView" @render() render: -> template = _.template( $("#perfilTemplate").html()) $(@el).html(template) ) # Main View class. Controlls all events and behaviors of the application. mycms.NoticiasView = Backbone.View.extend( el: $('#mainView') # View's contructor. # Initialize event listeners, and update DOM elements state. initialize: (options) -> _.bindAll(@, 'render') console.log "Init NoticiasView" @render() render: -> template = _.template($('#noticiasTemplate').html(), {noticias: @collection.toJSON()}) this.$el.html(template) ) # Main View class. Controlls all events and behaviors of the application. mycms.IndexView = Backbone.View.extend( # element el: $('#mainView') # View's contructor. # Initialize event listeners, and update DOM elements state. initialize: (options) -> _.bindAll(@, 'render') console.log "Init IndexView" @render() render: -> template = _.template( $("#indexTemplate").html()) $(@el).html(template) ) mycms.SubheaderView = Backbone.View.extend( el: $('#subheader') events: "click .js-dashboard": "home" "click .js-perfil": "perfil" "click .js-noticias": "noticias" "click .js-noticias_new": "noticias_new" initialize: (options) -> _.bindAll(@, 'render') console.log "Init LinksHeaderView" @render() home: -> console.log "home" app.navigate("/panel", true) perfil: -> console.log "perfil" app.navigate("/panel/perfil", true) noticias: -> console.log "noticias" app.navigate("/panel/noticias", true) noticias_new: -> console.log "noticias_new" app.navigate("/panel/noticias/new", true) render: -> template = _.template( $("#subHeaderTemplate").html()) $(@el).append(template) ) # Creamos el Backbone Router, quien "escuchará los cambios en la URL # y ejecutará las respectivas acciones" mycms.AppRouter = Backbone.Router.extend( # Rutas : accion routes: "panel": "index", "panel/perfil": "perfil", "panel/noticias": "noticias", "panel/noticias/new": "noticias_new" initialize: -> console.log "init router" @SubheaderView = new mycms.SubheaderView() index: -> console.log "router index" @IndexView = new mycms.IndexView() perfil: -> console.log "router perfil" @PerfilView = new mycms.PerfilView() noticias: -> console.log "router noticias" col = new mycms.NoticiasCollection() # Usamos método de Backbone .fetch que lanzará una petición GET ajax a /noticias # Usamos método de Backbone .save que lanzará una petición POST ajax a /noticias # Usamos método de Backbone .save que lanzará una petición PUT ajax a /noticias # Usamos método de Backbone .destroy que lanzará una petición DELETE ajax a /noticias # (si el objeto modelo tiene _id -si no es nuevo) ### params = { title: "PI:NAME:<NAME>END_PI" descripcion: "lalala" } # Esto lanza un AJAX POST a /noticias modelo.save(params) # Esto lanza un AJAX PUT a /noticias (Ya existe ese modelo en el server) modelo.save(params) #$.ajax('/api/noticias', ......) ### col.fetch( wait:true, success: (collection, response, options) => console.log "fetched noticias" console.log collection console.log response # Ya tenemos nuestra Collección con 50 noticias # Ahora creamos la vista y le pasamos la colección para que las muestre @NoticiasView = new mycms.NoticiasView( collection: collection ) ) noticias_new: -> console.log "router noticias New" @NoticiasNewView = new mycms.NoticiasNewView() ) # start backbone routing app = new mycms.AppRouter() Backbone.history.start(pushState: true) ) (jQuery)
[ { "context": "\t\t@sendingUser =\n\t\t\t_id: @sendingUserId\n\t\t\tname: \"Bob\"\n\t\t@email = \"user@example.com\"\n\t\t@userId = Object", "end": 1408, "score": 0.9994903206825256, "start": 1405, "tag": "NAME", "value": "Bob" }, { "context": "\t\t\t_id: @sendingUserId\n\t\t\tname: \...
test/unit/coffee/Collaborators/CollaboratorsInviteHandlerTests.coffee
dtu-compute/web-sharelatex
0
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Collaborators/CollaboratorsInviteHandler.js" SandboxedModule = require('sandboxed-module') events = require "events" ObjectId = require("mongojs").ObjectId Crypto = require('crypto') describe "CollaboratorsInviteHandler", -> beforeEach -> @ProjectInvite = class ProjectInvite constructor: (options={}) -> this._id = ObjectId() for k,v of options this[k] = v this save: sinon.stub() @findOne: sinon.stub() @find: sinon.stub() @remove: sinon.stub() @count: sinon.stub() @Crypto = Crypto @CollaboratorsInviteHandler = SandboxedModule.require modulePath, requires: 'settings-sharelatex': @settings = {} '../../models/ProjectInvite': {ProjectInvite: @ProjectInvite} 'logger-sharelatex': @logger = {err: sinon.stub(), error: sinon.stub(), log: sinon.stub()} './CollaboratorsEmailHandler': @CollaboratorsEmailHandler = {} "./CollaboratorsHandler": @CollaboratorsHandler = {addUserIdToProject: sinon.stub()} '../User/UserGetter': @UserGetter = {getUser: sinon.stub()} "../Project/ProjectGetter": @ProjectGetter = {} "../Notifications/NotificationsBuilder": @NotificationsBuilder = {} 'crypto': @Crypto @projectId = ObjectId() @sendingUserId = ObjectId() @sendingUser = _id: @sendingUserId name: "Bob" @email = "user@example.com" @userId = ObjectId() @user = _id: @userId email: 'someone@example.com' @inviteId = ObjectId() @token = 'hnhteaosuhtaeosuahs' @privileges = "readAndWrite" @fakeInvite = _id: @inviteId email: @email token: @token sendingUserId: @sendingUserId projectId: @projectId privileges: @privileges createdAt: new Date() describe 'getInviteCount', -> beforeEach -> @ProjectInvite.count.callsArgWith(1, null, 2) @call = (callback) => @CollaboratorsInviteHandler.getInviteCount @projectId, callback it 'should not produce an error', (done) -> @call (err, invites) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should produce the count of documents', (done) -> @call (err, count) => expect(count).to.equal 2 done() describe 'when model.count produces an error', -> beforeEach -> @ProjectInvite.count.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err, count) => expect(err).to.be.instanceof Error done() describe 'getAllInvites', -> beforeEach -> @fakeInvites = [ {_id: ObjectId(), one: 1}, {_id: ObjectId(), two: 2} ] @ProjectInvite.find.callsArgWith(1, null, @fakeInvites) @call = (callback) => @CollaboratorsInviteHandler.getAllInvites @projectId, callback describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err, invites) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should produce a list of invite objects', (done) -> @call (err, invites) => expect(invites).to.not.be.oneOf [null, undefined] expect(invites).to.deep.equal @fakeInvites done() it 'should have called ProjectInvite.find', (done) -> @call (err, invites) => @ProjectInvite.find.callCount.should.equal 1 @ProjectInvite.find.calledWith({projectId: @projectId}).should.equal true done() describe 'when ProjectInvite.find produces an error', -> beforeEach -> @ProjectInvite.find.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err, invites) => expect(err).to.be.instanceof Error done() describe 'inviteToProject', -> beforeEach -> @ProjectInvite::save = sinon.spy (cb) -> cb(null, this) @randomBytesSpy = sinon.spy(@Crypto, 'randomBytes') @CollaboratorsInviteHandler._sendMessages = sinon.stub().callsArgWith(3, null) @call = (callback) => @CollaboratorsInviteHandler.inviteToProject @projectId, @sendingUser, @email, @privileges, callback afterEach -> @randomBytesSpy.restore() describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err, invite) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should produce the invite object', (done) -> @call (err, invite) => expect(invite).to.not.equal null expect(invite).to.not.equal undefined expect(invite).to.be.instanceof Object expect(invite).to.have.all.keys ['_id', 'email', 'token', 'sendingUserId', 'projectId', 'privileges'] done() it 'should have generated a random token', (done) -> @call (err, invite) => @randomBytesSpy.callCount.should.equal 1 done() it 'should have called ProjectInvite.save', (done) -> @call (err, invite) => @ProjectInvite::save.callCount.should.equal 1 done() it 'should have called _sendMessages', (done) -> @call (err, invite) => @CollaboratorsInviteHandler._sendMessages.callCount.should.equal 1 @CollaboratorsInviteHandler._sendMessages.calledWith(@projectId, @sendingUser).should.equal true done() describe 'when saving model produces an error', -> beforeEach -> @ProjectInvite::save = sinon.spy (cb) -> cb(new Error('woops'), this) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() describe '_sendMessages', -> beforeEach -> @CollaboratorsEmailHandler.notifyUserOfProjectInvite = sinon.stub().callsArgWith(4, null) @CollaboratorsInviteHandler._trySendInviteNotification = sinon.stub().callsArgWith(3, null) @call = (callback) => @CollaboratorsInviteHandler._sendMessages @projectId, @sendingUser, @fakeInvite, callback describe 'when all goes well', -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should call CollaboratorsEmailHandler.notifyUserOfProjectInvite', (done) -> @call (err) => @CollaboratorsEmailHandler.notifyUserOfProjectInvite.callCount.should.equal 1 @CollaboratorsEmailHandler.notifyUserOfProjectInvite.calledWith(@projectId, @fakeInvite.email, @fakeInvite).should.equal true done() it 'should call _trySendInviteNotification', (done) -> @call (err) => @CollaboratorsInviteHandler._trySendInviteNotification.callCount.should.equal 1 @CollaboratorsInviteHandler._trySendInviteNotification.calledWith(@projectId, @sendingUser, @fakeInvite).should.equal true done() describe 'when CollaboratorsEmailHandler.notifyUserOfProjectInvite produces an error', -> beforeEach -> @CollaboratorsEmailHandler.notifyUserOfProjectInvite = sinon.stub().callsArgWith(4, new Error('woops')) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() it 'should not call _trySendInviteNotification', (done) -> @call (err) => @CollaboratorsInviteHandler._trySendInviteNotification.callCount.should.equal 0 done() describe 'when _trySendInviteNotification produces an error', -> beforeEach -> @CollaboratorsInviteHandler._trySendInviteNotification = sinon.stub().callsArgWith(3, new Error('woops')) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() describe 'revokeInvite', -> beforeEach -> @ProjectInvite.remove.callsArgWith(1, null) @CollaboratorsInviteHandler._tryCancelInviteNotification = sinon.stub().callsArgWith(1, null) @call = (callback) => @CollaboratorsInviteHandler.revokeInvite @projectId, @inviteId, callback describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should call ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 1 @ProjectInvite.remove.calledWith({projectId: @projectId, _id: @inviteId}).should.equal true done() it 'should call _tryCancelInviteNotification', (done) -> @call (err) => @CollaboratorsInviteHandler._tryCancelInviteNotification.callCount.should.equal 1 @CollaboratorsInviteHandler._tryCancelInviteNotification.calledWith(@inviteId).should.equal true done() describe 'when remove produces an error', -> beforeEach -> @ProjectInvite.remove.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() describe 'resendInvite', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, null, @fakeInvite) @CollaboratorsInviteHandler._sendMessages = sinon.stub().callsArgWith(3, null) @call = (callback) => @CollaboratorsInviteHandler.resendInvite @projectId, @sendingUser, @inviteId, callback describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should call ProjectInvite.findOne', (done) -> @call (err, invite) => @ProjectInvite.findOne.callCount.should.equal 1 @ProjectInvite.findOne.calledWith({_id: @inviteId, projectId: @projectId}).should.equal true done() it 'should have called _sendMessages', (done) -> @call (err, invite) => @CollaboratorsInviteHandler._sendMessages.callCount.should.equal 1 @CollaboratorsInviteHandler._sendMessages.calledWith(@projectId, @sendingUser, @fakeInvite).should.equal true done() describe 'when findOne produces an error', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() it 'should not have called _sendMessages', (done) -> @call (err, invite) => @CollaboratorsInviteHandler._sendMessages.callCount.should.equal 0 done() describe 'when findOne does not find an invite', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, null, null) it 'should not produce an error', (done) -> @call (err, invite) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should not have called _sendMessages', (done) -> @call (err, invite) => @CollaboratorsInviteHandler._sendMessages.callCount.should.equal 0 done() describe 'getInviteByToken', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, null, @fakeInvite) @call = (callback) => @CollaboratorsInviteHandler.getInviteByToken @projectId, @token, callback describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err, invite) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should produce the invite object', (done) -> @call (err, invite) => expect(invite).to.deep.equal @fakeInvite done() it 'should call ProjectInvite.findOne', (done) -> @call (err, invite) => @ProjectInvite.findOne.callCount.should.equal 1 @ProjectInvite.findOne.calledWith({projectId: @projectId, token: @token}).should.equal true done() describe 'when findOne produces an error', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() describe 'when findOne does not find an invite', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, null, null) it 'should not produce an error', (done) -> @call (err, invite) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should not produce an invite object', (done) -> @call (err, invite) => expect(invite).to.not.be.instanceof Error expect(invite).to.be.oneOf [null, undefined] done() describe 'acceptInvite', -> beforeEach -> @fakeProject = _id: @projectId collaberator_refs: [] readOnly_refs: [] @CollaboratorsHandler.addUserIdToProject.callsArgWith(4, null) @_getInviteByToken = sinon.stub(@CollaboratorsInviteHandler, 'getInviteByToken') @_getInviteByToken.callsArgWith(2, null, @fakeInvite) @CollaboratorsInviteHandler._tryCancelInviteNotification = sinon.stub().callsArgWith(1, null) @ProjectInvite.remove.callsArgWith(1, null) @call = (callback) => @CollaboratorsInviteHandler.acceptInvite @projectId, @token, @user, callback afterEach -> @_getInviteByToken.restore() describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 1 @CollaboratorsHandler.addUserIdToProject.calledWith(@projectId, @sendingUserId, @userId, @fakeInvite.privileges).should.equal true done() it 'should have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 1 @ProjectInvite.remove.calledWith({_id: @inviteId}).should.equal true done() describe 'when the invite is for readOnly access', -> beforeEach -> @fakeInvite.privileges = 'readOnly' @_getInviteByToken.callsArgWith(2, null, @fakeInvite) it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 1 @CollaboratorsHandler.addUserIdToProject.calledWith(@projectId, @sendingUserId, @userId, @fakeInvite.privileges).should.equal true done() describe 'when getInviteByToken does not find an invite', -> beforeEach -> @_getInviteByToken.callsArgWith(2, null, null) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error expect(err.name).to.equal "NotFoundError" done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should not have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 0 done() it 'should not have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 0 done() describe 'when getInviteByToken produces an error', -> beforeEach -> @_getInviteByToken.callsArgWith(2, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should not have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 0 done() it 'should not have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 0 done() describe 'when addUserIdToProject produces an error', -> beforeEach -> @CollaboratorsHandler.addUserIdToProject.callsArgWith(4, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 1 @CollaboratorsHandler.addUserIdToProject.calledWith(@projectId, @sendingUserId, @userId, @fakeInvite.privileges).should.equal true done() it 'should not have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 0 done() describe 'when ProjectInvite.remove produces an error', -> beforeEach -> @ProjectInvite.remove.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 1 @CollaboratorsHandler.addUserIdToProject.calledWith(@projectId, @sendingUserId, @userId, @fakeInvite.privileges).should.equal true done() it 'should have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 1 done() describe '_tryCancelInviteNotification', -> beforeEach -> @inviteId = ObjectId() @currentUser = {_id: ObjectId()} @notification = {read: sinon.stub().callsArgWith(0, null)} @NotificationsBuilder.projectInvite = sinon.stub().returns(@notification) @call = (callback) => @CollaboratorsInviteHandler._tryCancelInviteNotification @inviteId, callback it 'should not produce an error', (done) -> @call (err) => expect(err).to.be.oneOf [null, undefined] done() it 'should call notification.read', (done) -> @call (err) => @notification.read.callCount.should.equal 1 done() describe 'when notification.read produces an error', -> beforeEach -> @notification = {read: sinon.stub().callsArgWith(0, new Error('woops'))} @NotificationsBuilder.projectInvite = sinon.stub().returns(@notification) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() describe "_trySendInviteNotification", -> beforeEach -> @invite = _id: ObjectId(), token: "some_token", sendingUserId: ObjectId(), projectId: @project_id, targetEmail: 'user@example.com' createdAt: new Date(), @sendingUser = _id: ObjectId() first_name: "jim" @existingUser = {_id: ObjectId()} @UserGetter.getUser = sinon.stub().callsArgWith(2, null, @existingUser) @fakeProject = _id: @project_id name: "some project" @ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, @fakeProject) @notification = {create: sinon.stub().callsArgWith(0, null)} @NotificationsBuilder.projectInvite = sinon.stub().returns(@notification) @call = (callback) => @CollaboratorsInviteHandler._trySendInviteNotification @project_id, @sendingUser, @invite, callback describe 'when the user exists', -> beforeEach -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.be.oneOf [null, undefined] done() it 'should call getUser', (done) -> @call (err) => @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({email: @invite.email}).should.equal true done() it 'should call getProject', (done) -> @call (err) => @ProjectGetter.getProject.callCount.should.equal 1 @ProjectGetter.getProject.calledWith(@project_id).should.equal true done() it 'should call NotificationsBuilder.projectInvite.create', (done) -> @call (err) => @NotificationsBuilder.projectInvite.callCount.should.equal 1 @notification.create.callCount.should.equal 1 done() describe 'when getProject produces an error', -> beforeEach -> @ProjectGetter.getProject.callsArgWith(2, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should not call NotificationsBuilder.projectInvite.create', (done) -> @call (err) => @NotificationsBuilder.projectInvite.callCount.should.equal 0 @notification.create.callCount.should.equal 0 done() describe 'when projectInvite.create produces an error', -> beforeEach -> @notification.create.callsArgWith(0, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() describe 'when the user does not exist', -> beforeEach -> @UserGetter.getUser = sinon.stub().callsArgWith(2, null, null) it 'should not produce an error', (done) -> @call (err) => expect(err).to.be.oneOf [null, undefined] done() it 'should call getUser', (done) -> @call (err) => @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({email: @invite.email}).should.equal true done() it 'should not call getProject', (done) -> @call (err) => @ProjectGetter.getProject.callCount.should.equal 0 done() it 'should not call NotificationsBuilder.projectInvite.create', (done) -> @call (err) => @NotificationsBuilder.projectInvite.callCount.should.equal 0 @notification.create.callCount.should.equal 0 done() describe 'when the getUser produces an error', -> beforeEach -> @UserGetter.getUser = sinon.stub().callsArgWith(2, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should call getUser', (done) -> @call (err) => @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({email: @invite.email}).should.equal true done() it 'should not call getProject', (done) -> @call (err) => @ProjectGetter.getProject.callCount.should.equal 0 done() it 'should not call NotificationsBuilder.projectInvite.create', (done) -> @call (err) => @NotificationsBuilder.projectInvite.callCount.should.equal 0 @notification.create.callCount.should.equal 0 done()
91429
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Collaborators/CollaboratorsInviteHandler.js" SandboxedModule = require('sandboxed-module') events = require "events" ObjectId = require("mongojs").ObjectId Crypto = require('crypto') describe "CollaboratorsInviteHandler", -> beforeEach -> @ProjectInvite = class ProjectInvite constructor: (options={}) -> this._id = ObjectId() for k,v of options this[k] = v this save: sinon.stub() @findOne: sinon.stub() @find: sinon.stub() @remove: sinon.stub() @count: sinon.stub() @Crypto = Crypto @CollaboratorsInviteHandler = SandboxedModule.require modulePath, requires: 'settings-sharelatex': @settings = {} '../../models/ProjectInvite': {ProjectInvite: @ProjectInvite} 'logger-sharelatex': @logger = {err: sinon.stub(), error: sinon.stub(), log: sinon.stub()} './CollaboratorsEmailHandler': @CollaboratorsEmailHandler = {} "./CollaboratorsHandler": @CollaboratorsHandler = {addUserIdToProject: sinon.stub()} '../User/UserGetter': @UserGetter = {getUser: sinon.stub()} "../Project/ProjectGetter": @ProjectGetter = {} "../Notifications/NotificationsBuilder": @NotificationsBuilder = {} 'crypto': @Crypto @projectId = ObjectId() @sendingUserId = ObjectId() @sendingUser = _id: @sendingUserId name: "<NAME>" @email = "<EMAIL>" @userId = ObjectId() @user = _id: @userId email: '<EMAIL>' @inviteId = ObjectId() @token = '<PASSWORD>' @privileges = "readAndWrite" @fakeInvite = _id: @inviteId email: @email token: @token sendingUserId: @sendingUserId projectId: @projectId privileges: @privileges createdAt: new Date() describe 'getInviteCount', -> beforeEach -> @ProjectInvite.count.callsArgWith(1, null, 2) @call = (callback) => @CollaboratorsInviteHandler.getInviteCount @projectId, callback it 'should not produce an error', (done) -> @call (err, invites) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should produce the count of documents', (done) -> @call (err, count) => expect(count).to.equal 2 done() describe 'when model.count produces an error', -> beforeEach -> @ProjectInvite.count.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err, count) => expect(err).to.be.instanceof Error done() describe 'getAllInvites', -> beforeEach -> @fakeInvites = [ {_id: ObjectId(), one: 1}, {_id: ObjectId(), two: 2} ] @ProjectInvite.find.callsArgWith(1, null, @fakeInvites) @call = (callback) => @CollaboratorsInviteHandler.getAllInvites @projectId, callback describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err, invites) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should produce a list of invite objects', (done) -> @call (err, invites) => expect(invites).to.not.be.oneOf [null, undefined] expect(invites).to.deep.equal @fakeInvites done() it 'should have called ProjectInvite.find', (done) -> @call (err, invites) => @ProjectInvite.find.callCount.should.equal 1 @ProjectInvite.find.calledWith({projectId: @projectId}).should.equal true done() describe 'when ProjectInvite.find produces an error', -> beforeEach -> @ProjectInvite.find.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err, invites) => expect(err).to.be.instanceof Error done() describe 'inviteToProject', -> beforeEach -> @ProjectInvite::save = sinon.spy (cb) -> cb(null, this) @randomBytesSpy = sinon.spy(@Crypto, 'randomBytes') @CollaboratorsInviteHandler._sendMessages = sinon.stub().callsArgWith(3, null) @call = (callback) => @CollaboratorsInviteHandler.inviteToProject @projectId, @sendingUser, @email, @privileges, callback afterEach -> @randomBytesSpy.restore() describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err, invite) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should produce the invite object', (done) -> @call (err, invite) => expect(invite).to.not.equal null expect(invite).to.not.equal undefined expect(invite).to.be.instanceof Object expect(invite).to.have.all.keys ['_id', 'email', 'token', 'sendingUserId', 'projectId', 'privileges'] done() it 'should have generated a random token', (done) -> @call (err, invite) => @randomBytesSpy.callCount.should.equal 1 done() it 'should have called ProjectInvite.save', (done) -> @call (err, invite) => @ProjectInvite::save.callCount.should.equal 1 done() it 'should have called _sendMessages', (done) -> @call (err, invite) => @CollaboratorsInviteHandler._sendMessages.callCount.should.equal 1 @CollaboratorsInviteHandler._sendMessages.calledWith(@projectId, @sendingUser).should.equal true done() describe 'when saving model produces an error', -> beforeEach -> @ProjectInvite::save = sinon.spy (cb) -> cb(new Error('woops'), this) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() describe '_sendMessages', -> beforeEach -> @CollaboratorsEmailHandler.notifyUserOfProjectInvite = sinon.stub().callsArgWith(4, null) @CollaboratorsInviteHandler._trySendInviteNotification = sinon.stub().callsArgWith(3, null) @call = (callback) => @CollaboratorsInviteHandler._sendMessages @projectId, @sendingUser, @fakeInvite, callback describe 'when all goes well', -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should call CollaboratorsEmailHandler.notifyUserOfProjectInvite', (done) -> @call (err) => @CollaboratorsEmailHandler.notifyUserOfProjectInvite.callCount.should.equal 1 @CollaboratorsEmailHandler.notifyUserOfProjectInvite.calledWith(@projectId, @fakeInvite.email, @fakeInvite).should.equal true done() it 'should call _trySendInviteNotification', (done) -> @call (err) => @CollaboratorsInviteHandler._trySendInviteNotification.callCount.should.equal 1 @CollaboratorsInviteHandler._trySendInviteNotification.calledWith(@projectId, @sendingUser, @fakeInvite).should.equal true done() describe 'when CollaboratorsEmailHandler.notifyUserOfProjectInvite produces an error', -> beforeEach -> @CollaboratorsEmailHandler.notifyUserOfProjectInvite = sinon.stub().callsArgWith(4, new Error('woops')) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() it 'should not call _trySendInviteNotification', (done) -> @call (err) => @CollaboratorsInviteHandler._trySendInviteNotification.callCount.should.equal 0 done() describe 'when _trySendInviteNotification produces an error', -> beforeEach -> @CollaboratorsInviteHandler._trySendInviteNotification = sinon.stub().callsArgWith(3, new Error('woops')) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() describe 'revokeInvite', -> beforeEach -> @ProjectInvite.remove.callsArgWith(1, null) @CollaboratorsInviteHandler._tryCancelInviteNotification = sinon.stub().callsArgWith(1, null) @call = (callback) => @CollaboratorsInviteHandler.revokeInvite @projectId, @inviteId, callback describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should call ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 1 @ProjectInvite.remove.calledWith({projectId: @projectId, _id: @inviteId}).should.equal true done() it 'should call _tryCancelInviteNotification', (done) -> @call (err) => @CollaboratorsInviteHandler._tryCancelInviteNotification.callCount.should.equal 1 @CollaboratorsInviteHandler._tryCancelInviteNotification.calledWith(@inviteId).should.equal true done() describe 'when remove produces an error', -> beforeEach -> @ProjectInvite.remove.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() describe 'resendInvite', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, null, @fakeInvite) @CollaboratorsInviteHandler._sendMessages = sinon.stub().callsArgWith(3, null) @call = (callback) => @CollaboratorsInviteHandler.resendInvite @projectId, @sendingUser, @inviteId, callback describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should call ProjectInvite.findOne', (done) -> @call (err, invite) => @ProjectInvite.findOne.callCount.should.equal 1 @ProjectInvite.findOne.calledWith({_id: @inviteId, projectId: @projectId}).should.equal true done() it 'should have called _sendMessages', (done) -> @call (err, invite) => @CollaboratorsInviteHandler._sendMessages.callCount.should.equal 1 @CollaboratorsInviteHandler._sendMessages.calledWith(@projectId, @sendingUser, @fakeInvite).should.equal true done() describe 'when findOne produces an error', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() it 'should not have called _sendMessages', (done) -> @call (err, invite) => @CollaboratorsInviteHandler._sendMessages.callCount.should.equal 0 done() describe 'when findOne does not find an invite', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, null, null) it 'should not produce an error', (done) -> @call (err, invite) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should not have called _sendMessages', (done) -> @call (err, invite) => @CollaboratorsInviteHandler._sendMessages.callCount.should.equal 0 done() describe 'getInviteByToken', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, null, @fakeInvite) @call = (callback) => @CollaboratorsInviteHandler.getInviteByToken @projectId, @token, callback describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err, invite) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should produce the invite object', (done) -> @call (err, invite) => expect(invite).to.deep.equal @fakeInvite done() it 'should call ProjectInvite.findOne', (done) -> @call (err, invite) => @ProjectInvite.findOne.callCount.should.equal 1 @ProjectInvite.findOne.calledWith({projectId: @projectId, token: @token}).should.equal true done() describe 'when findOne produces an error', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() describe 'when findOne does not find an invite', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, null, null) it 'should not produce an error', (done) -> @call (err, invite) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should not produce an invite object', (done) -> @call (err, invite) => expect(invite).to.not.be.instanceof Error expect(invite).to.be.oneOf [null, undefined] done() describe 'acceptInvite', -> beforeEach -> @fakeProject = _id: @projectId collaberator_refs: [] readOnly_refs: [] @CollaboratorsHandler.addUserIdToProject.callsArgWith(4, null) @_getInviteByToken = sinon.stub(@CollaboratorsInviteHandler, 'getInviteByToken') @_getInviteByToken.callsArgWith(2, null, @fakeInvite) @CollaboratorsInviteHandler._tryCancelInviteNotification = sinon.stub().callsArgWith(1, null) @ProjectInvite.remove.callsArgWith(1, null) @call = (callback) => @CollaboratorsInviteHandler.acceptInvite @projectId, @token, @user, callback afterEach -> @_getInviteByToken.restore() describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 1 @CollaboratorsHandler.addUserIdToProject.calledWith(@projectId, @sendingUserId, @userId, @fakeInvite.privileges).should.equal true done() it 'should have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 1 @ProjectInvite.remove.calledWith({_id: @inviteId}).should.equal true done() describe 'when the invite is for readOnly access', -> beforeEach -> @fakeInvite.privileges = 'readOnly' @_getInviteByToken.callsArgWith(2, null, @fakeInvite) it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 1 @CollaboratorsHandler.addUserIdToProject.calledWith(@projectId, @sendingUserId, @userId, @fakeInvite.privileges).should.equal true done() describe 'when getInviteByToken does not find an invite', -> beforeEach -> @_getInviteByToken.callsArgWith(2, null, null) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error expect(err.name).to.equal "NotFoundError" done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should not have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 0 done() it 'should not have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 0 done() describe 'when getInviteByToken produces an error', -> beforeEach -> @_getInviteByToken.callsArgWith(2, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should not have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 0 done() it 'should not have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 0 done() describe 'when addUserIdToProject produces an error', -> beforeEach -> @CollaboratorsHandler.addUserIdToProject.callsArgWith(4, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 1 @CollaboratorsHandler.addUserIdToProject.calledWith(@projectId, @sendingUserId, @userId, @fakeInvite.privileges).should.equal true done() it 'should not have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 0 done() describe 'when ProjectInvite.remove produces an error', -> beforeEach -> @ProjectInvite.remove.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 1 @CollaboratorsHandler.addUserIdToProject.calledWith(@projectId, @sendingUserId, @userId, @fakeInvite.privileges).should.equal true done() it 'should have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 1 done() describe '_tryCancelInviteNotification', -> beforeEach -> @inviteId = ObjectId() @currentUser = {_id: ObjectId()} @notification = {read: sinon.stub().callsArgWith(0, null)} @NotificationsBuilder.projectInvite = sinon.stub().returns(@notification) @call = (callback) => @CollaboratorsInviteHandler._tryCancelInviteNotification @inviteId, callback it 'should not produce an error', (done) -> @call (err) => expect(err).to.be.oneOf [null, undefined] done() it 'should call notification.read', (done) -> @call (err) => @notification.read.callCount.should.equal 1 done() describe 'when notification.read produces an error', -> beforeEach -> @notification = {read: sinon.stub().callsArgWith(0, new Error('woops'))} @NotificationsBuilder.projectInvite = sinon.stub().returns(@notification) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() describe "_trySendInviteNotification", -> beforeEach -> @invite = _id: ObjectId(), token: "<KEY>", sendingUserId: ObjectId(), projectId: @project_id, targetEmail: '<EMAIL>' createdAt: new Date(), @sendingUser = _id: ObjectId() first_name: "<NAME>" @existingUser = {_id: ObjectId()} @UserGetter.getUser = sinon.stub().callsArgWith(2, null, @existingUser) @fakeProject = _id: @project_id name: "some project" @ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, @fakeProject) @notification = {create: sinon.stub().callsArgWith(0, null)} @NotificationsBuilder.projectInvite = sinon.stub().returns(@notification) @call = (callback) => @CollaboratorsInviteHandler._trySendInviteNotification @project_id, @sendingUser, @invite, callback describe 'when the user exists', -> beforeEach -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.be.oneOf [null, undefined] done() it 'should call getUser', (done) -> @call (err) => @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({email: @invite.email}).should.equal true done() it 'should call getProject', (done) -> @call (err) => @ProjectGetter.getProject.callCount.should.equal 1 @ProjectGetter.getProject.calledWith(@project_id).should.equal true done() it 'should call NotificationsBuilder.projectInvite.create', (done) -> @call (err) => @NotificationsBuilder.projectInvite.callCount.should.equal 1 @notification.create.callCount.should.equal 1 done() describe 'when getProject produces an error', -> beforeEach -> @ProjectGetter.getProject.callsArgWith(2, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should not call NotificationsBuilder.projectInvite.create', (done) -> @call (err) => @NotificationsBuilder.projectInvite.callCount.should.equal 0 @notification.create.callCount.should.equal 0 done() describe 'when projectInvite.create produces an error', -> beforeEach -> @notification.create.callsArgWith(0, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() describe 'when the user does not exist', -> beforeEach -> @UserGetter.getUser = sinon.stub().callsArgWith(2, null, null) it 'should not produce an error', (done) -> @call (err) => expect(err).to.be.oneOf [null, undefined] done() it 'should call getUser', (done) -> @call (err) => @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({email: @invite.email}).should.equal true done() it 'should not call getProject', (done) -> @call (err) => @ProjectGetter.getProject.callCount.should.equal 0 done() it 'should not call NotificationsBuilder.projectInvite.create', (done) -> @call (err) => @NotificationsBuilder.projectInvite.callCount.should.equal 0 @notification.create.callCount.should.equal 0 done() describe 'when the getUser produces an error', -> beforeEach -> @UserGetter.getUser = sinon.stub().callsArgWith(2, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should call getUser', (done) -> @call (err) => @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({email: @invite.email}).should.equal true done() it 'should not call getProject', (done) -> @call (err) => @ProjectGetter.getProject.callCount.should.equal 0 done() it 'should not call NotificationsBuilder.projectInvite.create', (done) -> @call (err) => @NotificationsBuilder.projectInvite.callCount.should.equal 0 @notification.create.callCount.should.equal 0 done()
true
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Collaborators/CollaboratorsInviteHandler.js" SandboxedModule = require('sandboxed-module') events = require "events" ObjectId = require("mongojs").ObjectId Crypto = require('crypto') describe "CollaboratorsInviteHandler", -> beforeEach -> @ProjectInvite = class ProjectInvite constructor: (options={}) -> this._id = ObjectId() for k,v of options this[k] = v this save: sinon.stub() @findOne: sinon.stub() @find: sinon.stub() @remove: sinon.stub() @count: sinon.stub() @Crypto = Crypto @CollaboratorsInviteHandler = SandboxedModule.require modulePath, requires: 'settings-sharelatex': @settings = {} '../../models/ProjectInvite': {ProjectInvite: @ProjectInvite} 'logger-sharelatex': @logger = {err: sinon.stub(), error: sinon.stub(), log: sinon.stub()} './CollaboratorsEmailHandler': @CollaboratorsEmailHandler = {} "./CollaboratorsHandler": @CollaboratorsHandler = {addUserIdToProject: sinon.stub()} '../User/UserGetter': @UserGetter = {getUser: sinon.stub()} "../Project/ProjectGetter": @ProjectGetter = {} "../Notifications/NotificationsBuilder": @NotificationsBuilder = {} 'crypto': @Crypto @projectId = ObjectId() @sendingUserId = ObjectId() @sendingUser = _id: @sendingUserId name: "PI:NAME:<NAME>END_PI" @email = "PI:EMAIL:<EMAIL>END_PI" @userId = ObjectId() @user = _id: @userId email: 'PI:EMAIL:<EMAIL>END_PI' @inviteId = ObjectId() @token = 'PI:PASSWORD:<PASSWORD>END_PI' @privileges = "readAndWrite" @fakeInvite = _id: @inviteId email: @email token: @token sendingUserId: @sendingUserId projectId: @projectId privileges: @privileges createdAt: new Date() describe 'getInviteCount', -> beforeEach -> @ProjectInvite.count.callsArgWith(1, null, 2) @call = (callback) => @CollaboratorsInviteHandler.getInviteCount @projectId, callback it 'should not produce an error', (done) -> @call (err, invites) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should produce the count of documents', (done) -> @call (err, count) => expect(count).to.equal 2 done() describe 'when model.count produces an error', -> beforeEach -> @ProjectInvite.count.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err, count) => expect(err).to.be.instanceof Error done() describe 'getAllInvites', -> beforeEach -> @fakeInvites = [ {_id: ObjectId(), one: 1}, {_id: ObjectId(), two: 2} ] @ProjectInvite.find.callsArgWith(1, null, @fakeInvites) @call = (callback) => @CollaboratorsInviteHandler.getAllInvites @projectId, callback describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err, invites) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should produce a list of invite objects', (done) -> @call (err, invites) => expect(invites).to.not.be.oneOf [null, undefined] expect(invites).to.deep.equal @fakeInvites done() it 'should have called ProjectInvite.find', (done) -> @call (err, invites) => @ProjectInvite.find.callCount.should.equal 1 @ProjectInvite.find.calledWith({projectId: @projectId}).should.equal true done() describe 'when ProjectInvite.find produces an error', -> beforeEach -> @ProjectInvite.find.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err, invites) => expect(err).to.be.instanceof Error done() describe 'inviteToProject', -> beforeEach -> @ProjectInvite::save = sinon.spy (cb) -> cb(null, this) @randomBytesSpy = sinon.spy(@Crypto, 'randomBytes') @CollaboratorsInviteHandler._sendMessages = sinon.stub().callsArgWith(3, null) @call = (callback) => @CollaboratorsInviteHandler.inviteToProject @projectId, @sendingUser, @email, @privileges, callback afterEach -> @randomBytesSpy.restore() describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err, invite) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should produce the invite object', (done) -> @call (err, invite) => expect(invite).to.not.equal null expect(invite).to.not.equal undefined expect(invite).to.be.instanceof Object expect(invite).to.have.all.keys ['_id', 'email', 'token', 'sendingUserId', 'projectId', 'privileges'] done() it 'should have generated a random token', (done) -> @call (err, invite) => @randomBytesSpy.callCount.should.equal 1 done() it 'should have called ProjectInvite.save', (done) -> @call (err, invite) => @ProjectInvite::save.callCount.should.equal 1 done() it 'should have called _sendMessages', (done) -> @call (err, invite) => @CollaboratorsInviteHandler._sendMessages.callCount.should.equal 1 @CollaboratorsInviteHandler._sendMessages.calledWith(@projectId, @sendingUser).should.equal true done() describe 'when saving model produces an error', -> beforeEach -> @ProjectInvite::save = sinon.spy (cb) -> cb(new Error('woops'), this) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() describe '_sendMessages', -> beforeEach -> @CollaboratorsEmailHandler.notifyUserOfProjectInvite = sinon.stub().callsArgWith(4, null) @CollaboratorsInviteHandler._trySendInviteNotification = sinon.stub().callsArgWith(3, null) @call = (callback) => @CollaboratorsInviteHandler._sendMessages @projectId, @sendingUser, @fakeInvite, callback describe 'when all goes well', -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should call CollaboratorsEmailHandler.notifyUserOfProjectInvite', (done) -> @call (err) => @CollaboratorsEmailHandler.notifyUserOfProjectInvite.callCount.should.equal 1 @CollaboratorsEmailHandler.notifyUserOfProjectInvite.calledWith(@projectId, @fakeInvite.email, @fakeInvite).should.equal true done() it 'should call _trySendInviteNotification', (done) -> @call (err) => @CollaboratorsInviteHandler._trySendInviteNotification.callCount.should.equal 1 @CollaboratorsInviteHandler._trySendInviteNotification.calledWith(@projectId, @sendingUser, @fakeInvite).should.equal true done() describe 'when CollaboratorsEmailHandler.notifyUserOfProjectInvite produces an error', -> beforeEach -> @CollaboratorsEmailHandler.notifyUserOfProjectInvite = sinon.stub().callsArgWith(4, new Error('woops')) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() it 'should not call _trySendInviteNotification', (done) -> @call (err) => @CollaboratorsInviteHandler._trySendInviteNotification.callCount.should.equal 0 done() describe 'when _trySendInviteNotification produces an error', -> beforeEach -> @CollaboratorsInviteHandler._trySendInviteNotification = sinon.stub().callsArgWith(3, new Error('woops')) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() describe 'revokeInvite', -> beforeEach -> @ProjectInvite.remove.callsArgWith(1, null) @CollaboratorsInviteHandler._tryCancelInviteNotification = sinon.stub().callsArgWith(1, null) @call = (callback) => @CollaboratorsInviteHandler.revokeInvite @projectId, @inviteId, callback describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should call ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 1 @ProjectInvite.remove.calledWith({projectId: @projectId, _id: @inviteId}).should.equal true done() it 'should call _tryCancelInviteNotification', (done) -> @call (err) => @CollaboratorsInviteHandler._tryCancelInviteNotification.callCount.should.equal 1 @CollaboratorsInviteHandler._tryCancelInviteNotification.calledWith(@inviteId).should.equal true done() describe 'when remove produces an error', -> beforeEach -> @ProjectInvite.remove.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() describe 'resendInvite', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, null, @fakeInvite) @CollaboratorsInviteHandler._sendMessages = sinon.stub().callsArgWith(3, null) @call = (callback) => @CollaboratorsInviteHandler.resendInvite @projectId, @sendingUser, @inviteId, callback describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should call ProjectInvite.findOne', (done) -> @call (err, invite) => @ProjectInvite.findOne.callCount.should.equal 1 @ProjectInvite.findOne.calledWith({_id: @inviteId, projectId: @projectId}).should.equal true done() it 'should have called _sendMessages', (done) -> @call (err, invite) => @CollaboratorsInviteHandler._sendMessages.callCount.should.equal 1 @CollaboratorsInviteHandler._sendMessages.calledWith(@projectId, @sendingUser, @fakeInvite).should.equal true done() describe 'when findOne produces an error', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() it 'should not have called _sendMessages', (done) -> @call (err, invite) => @CollaboratorsInviteHandler._sendMessages.callCount.should.equal 0 done() describe 'when findOne does not find an invite', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, null, null) it 'should not produce an error', (done) -> @call (err, invite) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should not have called _sendMessages', (done) -> @call (err, invite) => @CollaboratorsInviteHandler._sendMessages.callCount.should.equal 0 done() describe 'getInviteByToken', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, null, @fakeInvite) @call = (callback) => @CollaboratorsInviteHandler.getInviteByToken @projectId, @token, callback describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err, invite) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should produce the invite object', (done) -> @call (err, invite) => expect(invite).to.deep.equal @fakeInvite done() it 'should call ProjectInvite.findOne', (done) -> @call (err, invite) => @ProjectInvite.findOne.callCount.should.equal 1 @ProjectInvite.findOne.calledWith({projectId: @projectId, token: @token}).should.equal true done() describe 'when findOne produces an error', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err, invite) => expect(err).to.be.instanceof Error done() describe 'when findOne does not find an invite', -> beforeEach -> @ProjectInvite.findOne.callsArgWith(1, null, null) it 'should not produce an error', (done) -> @call (err, invite) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should not produce an invite object', (done) -> @call (err, invite) => expect(invite).to.not.be.instanceof Error expect(invite).to.be.oneOf [null, undefined] done() describe 'acceptInvite', -> beforeEach -> @fakeProject = _id: @projectId collaberator_refs: [] readOnly_refs: [] @CollaboratorsHandler.addUserIdToProject.callsArgWith(4, null) @_getInviteByToken = sinon.stub(@CollaboratorsInviteHandler, 'getInviteByToken') @_getInviteByToken.callsArgWith(2, null, @fakeInvite) @CollaboratorsInviteHandler._tryCancelInviteNotification = sinon.stub().callsArgWith(1, null) @ProjectInvite.remove.callsArgWith(1, null) @call = (callback) => @CollaboratorsInviteHandler.acceptInvite @projectId, @token, @user, callback afterEach -> @_getInviteByToken.restore() describe 'when all goes well', -> beforeEach -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 1 @CollaboratorsHandler.addUserIdToProject.calledWith(@projectId, @sendingUserId, @userId, @fakeInvite.privileges).should.equal true done() it 'should have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 1 @ProjectInvite.remove.calledWith({_id: @inviteId}).should.equal true done() describe 'when the invite is for readOnly access', -> beforeEach -> @fakeInvite.privileges = 'readOnly' @_getInviteByToken.callsArgWith(2, null, @fakeInvite) it 'should not produce an error', (done) -> @call (err) => expect(err).to.not.be.instanceof Error expect(err).to.be.oneOf [null, undefined] done() it 'should have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 1 @CollaboratorsHandler.addUserIdToProject.calledWith(@projectId, @sendingUserId, @userId, @fakeInvite.privileges).should.equal true done() describe 'when getInviteByToken does not find an invite', -> beforeEach -> @_getInviteByToken.callsArgWith(2, null, null) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error expect(err.name).to.equal "NotFoundError" done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should not have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 0 done() it 'should not have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 0 done() describe 'when getInviteByToken produces an error', -> beforeEach -> @_getInviteByToken.callsArgWith(2, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should not have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 0 done() it 'should not have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 0 done() describe 'when addUserIdToProject produces an error', -> beforeEach -> @CollaboratorsHandler.addUserIdToProject.callsArgWith(4, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 1 @CollaboratorsHandler.addUserIdToProject.calledWith(@projectId, @sendingUserId, @userId, @fakeInvite.privileges).should.equal true done() it 'should not have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 0 done() describe 'when ProjectInvite.remove produces an error', -> beforeEach -> @ProjectInvite.remove.callsArgWith(1, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should have called getInviteByToken', (done) -> @call (err) => @_getInviteByToken.callCount.should.equal 1 @_getInviteByToken.calledWith(@projectId, @token).should.equal true done() it 'should have called CollaboratorsHandler.addUserIdToProject', (done) -> @call (err) => @CollaboratorsHandler.addUserIdToProject.callCount.should.equal 1 @CollaboratorsHandler.addUserIdToProject.calledWith(@projectId, @sendingUserId, @userId, @fakeInvite.privileges).should.equal true done() it 'should have called ProjectInvite.remove', (done) -> @call (err) => @ProjectInvite.remove.callCount.should.equal 1 done() describe '_tryCancelInviteNotification', -> beforeEach -> @inviteId = ObjectId() @currentUser = {_id: ObjectId()} @notification = {read: sinon.stub().callsArgWith(0, null)} @NotificationsBuilder.projectInvite = sinon.stub().returns(@notification) @call = (callback) => @CollaboratorsInviteHandler._tryCancelInviteNotification @inviteId, callback it 'should not produce an error', (done) -> @call (err) => expect(err).to.be.oneOf [null, undefined] done() it 'should call notification.read', (done) -> @call (err) => @notification.read.callCount.should.equal 1 done() describe 'when notification.read produces an error', -> beforeEach -> @notification = {read: sinon.stub().callsArgWith(0, new Error('woops'))} @NotificationsBuilder.projectInvite = sinon.stub().returns(@notification) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() describe "_trySendInviteNotification", -> beforeEach -> @invite = _id: ObjectId(), token: "PI:KEY:<KEY>END_PI", sendingUserId: ObjectId(), projectId: @project_id, targetEmail: 'PI:EMAIL:<EMAIL>END_PI' createdAt: new Date(), @sendingUser = _id: ObjectId() first_name: "PI:NAME:<NAME>END_PI" @existingUser = {_id: ObjectId()} @UserGetter.getUser = sinon.stub().callsArgWith(2, null, @existingUser) @fakeProject = _id: @project_id name: "some project" @ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, @fakeProject) @notification = {create: sinon.stub().callsArgWith(0, null)} @NotificationsBuilder.projectInvite = sinon.stub().returns(@notification) @call = (callback) => @CollaboratorsInviteHandler._trySendInviteNotification @project_id, @sendingUser, @invite, callback describe 'when the user exists', -> beforeEach -> it 'should not produce an error', (done) -> @call (err) => expect(err).to.be.oneOf [null, undefined] done() it 'should call getUser', (done) -> @call (err) => @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({email: @invite.email}).should.equal true done() it 'should call getProject', (done) -> @call (err) => @ProjectGetter.getProject.callCount.should.equal 1 @ProjectGetter.getProject.calledWith(@project_id).should.equal true done() it 'should call NotificationsBuilder.projectInvite.create', (done) -> @call (err) => @NotificationsBuilder.projectInvite.callCount.should.equal 1 @notification.create.callCount.should.equal 1 done() describe 'when getProject produces an error', -> beforeEach -> @ProjectGetter.getProject.callsArgWith(2, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should not call NotificationsBuilder.projectInvite.create', (done) -> @call (err) => @NotificationsBuilder.projectInvite.callCount.should.equal 0 @notification.create.callCount.should.equal 0 done() describe 'when projectInvite.create produces an error', -> beforeEach -> @notification.create.callsArgWith(0, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() describe 'when the user does not exist', -> beforeEach -> @UserGetter.getUser = sinon.stub().callsArgWith(2, null, null) it 'should not produce an error', (done) -> @call (err) => expect(err).to.be.oneOf [null, undefined] done() it 'should call getUser', (done) -> @call (err) => @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({email: @invite.email}).should.equal true done() it 'should not call getProject', (done) -> @call (err) => @ProjectGetter.getProject.callCount.should.equal 0 done() it 'should not call NotificationsBuilder.projectInvite.create', (done) -> @call (err) => @NotificationsBuilder.projectInvite.callCount.should.equal 0 @notification.create.callCount.should.equal 0 done() describe 'when the getUser produces an error', -> beforeEach -> @UserGetter.getUser = sinon.stub().callsArgWith(2, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.be.instanceof Error done() it 'should call getUser', (done) -> @call (err) => @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith({email: @invite.email}).should.equal true done() it 'should not call getProject', (done) -> @call (err) => @ProjectGetter.getProject.callCount.should.equal 0 done() it 'should not call NotificationsBuilder.projectInvite.create', (done) -> @call (err) => @NotificationsBuilder.projectInvite.callCount.should.equal 0 @notification.create.callCount.should.equal 0 done()
[ { "context": "ally? Hey, you might be able to help me! My name's Amber Denotto.\" She shakes your\n hand. \"I'm one of Mr. Bro", "end": 658, "score": 0.9998873472213745, "start": 645, "tag": "NAME", "value": "Amber Denotto" }, { "context": "notto.\" She shakes your\n hand. ...
src/coffee/game/student.coffee
arashikou/exper3-2015
0
angular.module 'gameDefinition.studentStories', ['qbn.edsl', 'gameDefinition.enums'] .run (qbnEdsl, enums) -> {storylet, choice, reqs, consq} = qbnEdsl {leads} = enums storylet 'clubStudent', 'A nervous-looking student' ''' If they ever throw a rocking chair convention for cats and provide free coffe, it might begin to equal this young lady's level of nerves. You make sure to approach from the front, where she can see you. "What do you want?" she hisses as you slide into the chair opposite. You explain yourself. "Oh— Oh really? Hey, you might be able to help me! My name's Amber Denotto." She shakes your hand. "I'm one of Mr. Brown's students. Or _was_, if the rumors are to be believed. It's enough for the university, anyway. They want to reassign me to a new mentor, and that means giving up the research materials Mr. Brown provided to me." "I'd be willing to part with them to you instead, though. Just… a little tit-for-tat, you know? I need your help with something first." You pointedly continue listening silently. "The seasonal symposium is coming up soon. If I get reassigned and have to start my project over, there's no way I stand a chance of placing for a prize, which means no chance of keeping my scholarship. Unless… Unless I had some way of knowing what competition I'm up against. If I could tailor my new project to the judges and make sure it stands out from the competition, I should at least be able to get an honorable mention." "Do that, and my old project materials from Mr. Brown are yours." ''' consequences: lead: consq.set leads.student student: (quality) -> quality.value++ 'You are helping a student survive the seasonal symposium' progress: consq.set 0 storylet 'student1', 'Research the seasonal symposium' ''' Information is everywhere at the university. The question is, where to start? ''' choices: [ choice 'student1Illusion', 'Research illusions' 'Search the illusion department for information.' visible: progress: reqs.lt 7 active: illusionHunch: reqs.gte 1 choice 'student1Hallucination', 'Research hallucinations' 'Speak with the Dean of Hallucinations.' visible: progress: reqs.lt 7 active: hallucinationHunch: reqs.gte 1 choice 'student1Hypnotism', 'Research hypnotisms' ''' As you recall from your own university days, using hypnotism to cheat is practically mandatory. ''' visible: progress: reqs.lt 7 active: hypnotismHunch: reqs.gte 1 choice 'student1Solve', 'That should be enough' 'You have enough info to give Ms. Denotto a decided edge.' active: progress: reqs.gte 7 ] storylet 'student1Illusion', 'Research illusions' ''' You find several groups of students who are preparing illusion presentations for the symposium, including one presentation that is actually illusory. They might want to work on that further. ''' consequences: illusionHunch: consq.decrease 1 progress: consq.increase 1 storylet 'student1Hallucination', 'Research hallucinations' ''' The dean is tight-lipped at first, but you demonstrate appreciation for some of the finer hallucinations scattering his office and he begins to warm up and talk about who will be featuring at this year's symposium. ''' consequences: hallucinationHunch: consq.decrease 1 progress: consq.increase 1 storylet 'student1Hypnotism', 'Research hypnotisms' ''' Sure enough, several students are already preparing their hypnotisms to try and trick the judges. It was probably never going to work, but turning them in reduces Ms. Denotto's competition and gets you brownie points with people who can leak details of the symposium. ''' consequences: hypnotismHunch: consq.decrease 1 progress: consq.increase 1 storylet 'student1Solve', 'Hope springs eternal' ''' Ms. Denotto seems very pleased with the results you deliver. She's practically licking her lips with excitement at her prospects. "With this much, I could probably even _place_ at the symposium. I should have hired you years ago!" She's all too happy to part with her old research materials. You are shocked to discover that Mr. Brown provided her with a live demon in a cage. The things are exceedingly rare, and just seeing the little fiend's golden compound eyes takes your mind back to times better left forgotten. Ms. Denotto misinterprets your reverie as concern. "Don't worry, this is totally legal. Here—" She hands you a sheaf of papers. "These papers prove that he's legitimate, culled from the old battlefields and not some demonologist's weekend mistake." The other materials are nothing so interesting. Indeed, you'll probably just hock them later. But as she reaches to hand over the last packet, Amber stops. "Can I— Can I keep just one thing? To remember him by. Mr. Brown was actually quite good as a mentor." She opens the packet to reveal two tiny objects. "Go ahead, take either one you like. Just leave the other one for me." ''' choices: [ choice 'studentFinalSealbone', 'Take the sealbone figurine' 'Sealbone carvings like this are often sensitive to hallucinations.' choice 'studentFinalRibbon', 'Take the inscribed ribbon' 'The inscriptions are supposed to protect the bearer against illusions.' ] finalText = ''' Amber nods and closes the packet. "If you ever change your mind, I bet the dealer in the Salamader Club could help you. He's always helping students swap things we've been overallocated for things we can't get." ''' storylet 'studentFinalSealbone', 'A sealbone figurine' finalText consequences: cagedDemon: consq.increase 1 bluebacks: consq.increase 3 sealboneTrinket: consq.increase 1 lead: (quality) -> quality.value = undefined 'Your current lead has ended.' student: (quality) -> quality.value++ 'Your help has been invaluable to Ms. Denotto' progress: consq.set 0 storylet 'studentFinalRibbon', 'An inscribed ribbon' finalText consequences: cagedDemon: consq.increase 1 bluebacks: consq.increase 3 inscribedRibbon: consq.increase 1 lead: (quality) -> quality.value = undefined 'Your current lead has ended.' student: (quality) -> quality.value++ 'Your help has been invaluable to Ms. Denotto' progress: consq.set 0 return
162091
angular.module 'gameDefinition.studentStories', ['qbn.edsl', 'gameDefinition.enums'] .run (qbnEdsl, enums) -> {storylet, choice, reqs, consq} = qbnEdsl {leads} = enums storylet 'clubStudent', 'A nervous-looking student' ''' If they ever throw a rocking chair convention for cats and provide free coffe, it might begin to equal this young lady's level of nerves. You make sure to approach from the front, where she can see you. "What do you want?" she hisses as you slide into the chair opposite. You explain yourself. "Oh— Oh really? Hey, you might be able to help me! My name's <NAME>." She shakes your hand. "I'm one of Mr. <NAME>'s students. Or _was_, if the rumors are to be believed. It's enough for the university, anyway. They want to reassign me to a new mentor, and that means giving up the research materials Mr. <NAME> provided to me." "I'd be willing to part with them to you instead, though. Just… a little tit-for-tat, you know? I need your help with something first." You pointedly continue listening silently. "The seasonal symposium is coming up soon. If I get reassigned and have to start my project over, there's no way I stand a chance of placing for a prize, which means no chance of keeping my scholarship. Unless… Unless I had some way of knowing what competition I'm up against. If I could tailor my new project to the judges and make sure it stands out from the competition, I should at least be able to get an honorable mention." "Do that, and my old project materials from Mr. Brown are yours." ''' consequences: lead: consq.set leads.student student: (quality) -> quality.value++ 'You are helping a student survive the seasonal symposium' progress: consq.set 0 storylet 'student1', 'Research the seasonal symposium' ''' Information is everywhere at the university. The question is, where to start? ''' choices: [ choice 'student1Illusion', 'Research illusions' 'Search the illusion department for information.' visible: progress: reqs.lt 7 active: illusionHunch: reqs.gte 1 choice 'student1Hallucination', 'Research hallucinations' 'Speak with the Dean of Hallucinations.' visible: progress: reqs.lt 7 active: hallucinationHunch: reqs.gte 1 choice 'student1Hypnotism', 'Research hypnotisms' ''' As you recall from your own university days, using hypnotism to cheat is practically mandatory. ''' visible: progress: reqs.lt 7 active: hypnotismHunch: reqs.gte 1 choice 'student1Solve', 'That should be enough' 'You have enough info to give <NAME> a decided edge.' active: progress: reqs.gte 7 ] storylet 'student1Illusion', 'Research illusions' ''' You find several groups of students who are preparing illusion presentations for the symposium, including one presentation that is actually illusory. They might want to work on that further. ''' consequences: illusionHunch: consq.decrease 1 progress: consq.increase 1 storylet 'student1Hallucination', 'Research hallucinations' ''' The dean is tight-lipped at first, but you demonstrate appreciation for some of the finer hallucinations scattering his office and he begins to warm up and talk about who will be featuring at this year's symposium. ''' consequences: hallucinationHunch: consq.decrease 1 progress: consq.increase 1 storylet 'student1Hypnotism', 'Research hypnotisms' ''' Sure enough, several students are already preparing their hypnotisms to try and trick the judges. It was probably never going to work, but turning them in reduces Ms. Denotto's competition and gets you brownie points with people who can leak details of the symposium. ''' consequences: hypnotismHunch: consq.decrease 1 progress: consq.increase 1 storylet 'student1Solve', 'Hope springs eternal' ''' <NAME> seems very pleased with the results you deliver. She's practically licking her lips with excitement at her prospects. "With this much, I could probably even _place_ at the symposium. I should have hired you years ago!" She's all too happy to part with her old research materials. You are shocked to discover that <NAME> provided her with a live demon in a cage. The things are exceedingly rare, and just seeing the little fiend's golden compound eyes takes your mind back to times better left forgotten. <NAME> misinterprets your reverie as concern. "Don't worry, this is totally legal. Here—" She hands you a sheaf of papers. "These papers prove that he's legitimate, culled from the old battlefields and not some demonologist's weekend mistake." The other materials are nothing so interesting. Indeed, you'll probably just hock them later. But as she reaches to hand over the last packet, Amber stops. "Can I— Can I keep just one thing? To remember him by. <NAME> was actually quite good as a mentor." She opens the packet to reveal two tiny objects. "Go ahead, take either one you like. Just leave the other one for me." ''' choices: [ choice 'studentFinalSealbone', 'Take the sealbone figurine' 'Sealbone carvings like this are often sensitive to hallucinations.' choice 'studentFinalRibbon', 'Take the inscribed ribbon' 'The inscriptions are supposed to protect the bearer against illusions.' ] finalText = ''' Amber nods and closes the packet. "If you ever change your mind, I bet the dealer in the Salamader Club could help you. He's always helping students swap things we've been overallocated for things we can't get." ''' storylet 'studentFinalSealbone', 'A sealbone figurine' finalText consequences: cagedDemon: consq.increase 1 bluebacks: consq.increase 3 sealboneTrinket: consq.increase 1 lead: (quality) -> quality.value = undefined 'Your current lead has ended.' student: (quality) -> quality.value++ 'Your help has been invaluable to Ms. <NAME>' progress: consq.set 0 storylet 'studentFinalRibbon', 'An inscribed ribbon' finalText consequences: cagedDemon: consq.increase 1 bluebacks: consq.increase 3 inscribedRibbon: consq.increase 1 lead: (quality) -> quality.value = undefined 'Your current lead has ended.' student: (quality) -> quality.value++ 'Your help has been invaluable to Ms. <NAME>' progress: consq.set 0 return
true
angular.module 'gameDefinition.studentStories', ['qbn.edsl', 'gameDefinition.enums'] .run (qbnEdsl, enums) -> {storylet, choice, reqs, consq} = qbnEdsl {leads} = enums storylet 'clubStudent', 'A nervous-looking student' ''' If they ever throw a rocking chair convention for cats and provide free coffe, it might begin to equal this young lady's level of nerves. You make sure to approach from the front, where she can see you. "What do you want?" she hisses as you slide into the chair opposite. You explain yourself. "Oh— Oh really? Hey, you might be able to help me! My name's PI:NAME:<NAME>END_PI." She shakes your hand. "I'm one of Mr. PI:NAME:<NAME>END_PI's students. Or _was_, if the rumors are to be believed. It's enough for the university, anyway. They want to reassign me to a new mentor, and that means giving up the research materials Mr. PI:NAME:<NAME>END_PI provided to me." "I'd be willing to part with them to you instead, though. Just… a little tit-for-tat, you know? I need your help with something first." You pointedly continue listening silently. "The seasonal symposium is coming up soon. If I get reassigned and have to start my project over, there's no way I stand a chance of placing for a prize, which means no chance of keeping my scholarship. Unless… Unless I had some way of knowing what competition I'm up against. If I could tailor my new project to the judges and make sure it stands out from the competition, I should at least be able to get an honorable mention." "Do that, and my old project materials from Mr. Brown are yours." ''' consequences: lead: consq.set leads.student student: (quality) -> quality.value++ 'You are helping a student survive the seasonal symposium' progress: consq.set 0 storylet 'student1', 'Research the seasonal symposium' ''' Information is everywhere at the university. The question is, where to start? ''' choices: [ choice 'student1Illusion', 'Research illusions' 'Search the illusion department for information.' visible: progress: reqs.lt 7 active: illusionHunch: reqs.gte 1 choice 'student1Hallucination', 'Research hallucinations' 'Speak with the Dean of Hallucinations.' visible: progress: reqs.lt 7 active: hallucinationHunch: reqs.gte 1 choice 'student1Hypnotism', 'Research hypnotisms' ''' As you recall from your own university days, using hypnotism to cheat is practically mandatory. ''' visible: progress: reqs.lt 7 active: hypnotismHunch: reqs.gte 1 choice 'student1Solve', 'That should be enough' 'You have enough info to give PI:NAME:<NAME>END_PI a decided edge.' active: progress: reqs.gte 7 ] storylet 'student1Illusion', 'Research illusions' ''' You find several groups of students who are preparing illusion presentations for the symposium, including one presentation that is actually illusory. They might want to work on that further. ''' consequences: illusionHunch: consq.decrease 1 progress: consq.increase 1 storylet 'student1Hallucination', 'Research hallucinations' ''' The dean is tight-lipped at first, but you demonstrate appreciation for some of the finer hallucinations scattering his office and he begins to warm up and talk about who will be featuring at this year's symposium. ''' consequences: hallucinationHunch: consq.decrease 1 progress: consq.increase 1 storylet 'student1Hypnotism', 'Research hypnotisms' ''' Sure enough, several students are already preparing their hypnotisms to try and trick the judges. It was probably never going to work, but turning them in reduces Ms. Denotto's competition and gets you brownie points with people who can leak details of the symposium. ''' consequences: hypnotismHunch: consq.decrease 1 progress: consq.increase 1 storylet 'student1Solve', 'Hope springs eternal' ''' PI:NAME:<NAME>END_PI seems very pleased with the results you deliver. She's practically licking her lips with excitement at her prospects. "With this much, I could probably even _place_ at the symposium. I should have hired you years ago!" She's all too happy to part with her old research materials. You are shocked to discover that PI:NAME:<NAME>END_PI provided her with a live demon in a cage. The things are exceedingly rare, and just seeing the little fiend's golden compound eyes takes your mind back to times better left forgotten. PI:NAME:<NAME>END_PI misinterprets your reverie as concern. "Don't worry, this is totally legal. Here—" She hands you a sheaf of papers. "These papers prove that he's legitimate, culled from the old battlefields and not some demonologist's weekend mistake." The other materials are nothing so interesting. Indeed, you'll probably just hock them later. But as she reaches to hand over the last packet, Amber stops. "Can I— Can I keep just one thing? To remember him by. PI:NAME:<NAME>END_PI was actually quite good as a mentor." She opens the packet to reveal two tiny objects. "Go ahead, take either one you like. Just leave the other one for me." ''' choices: [ choice 'studentFinalSealbone', 'Take the sealbone figurine' 'Sealbone carvings like this are often sensitive to hallucinations.' choice 'studentFinalRibbon', 'Take the inscribed ribbon' 'The inscriptions are supposed to protect the bearer against illusions.' ] finalText = ''' Amber nods and closes the packet. "If you ever change your mind, I bet the dealer in the Salamader Club could help you. He's always helping students swap things we've been overallocated for things we can't get." ''' storylet 'studentFinalSealbone', 'A sealbone figurine' finalText consequences: cagedDemon: consq.increase 1 bluebacks: consq.increase 3 sealboneTrinket: consq.increase 1 lead: (quality) -> quality.value = undefined 'Your current lead has ended.' student: (quality) -> quality.value++ 'Your help has been invaluable to Ms. PI:NAME:<NAME>END_PI' progress: consq.set 0 storylet 'studentFinalRibbon', 'An inscribed ribbon' finalText consequences: cagedDemon: consq.increase 1 bluebacks: consq.increase 3 inscribedRibbon: consq.increase 1 lead: (quality) -> quality.value = undefined 'Your current lead has ended.' student: (quality) -> quality.value++ 'Your help has been invaluable to Ms. PI:NAME:<NAME>END_PI' progress: consq.set 0 return
[ { "context": "dos_keyvalues.findOne({user:Steedos.userId(),key:\"zoom\"})\n\t\tSession.get(\"base_each_apps_end\")\n\t\tTemplate", "end": 2175, "score": 0.9063722491264343, "start": 2171, "tag": "KEY", "value": "zoom" } ]
creator/packages/steedos-base/client/layout/header/header.coffee
yicone/steedos-platform
42
Template.steedosHeader.helpers appBadge: (appId)-> workflow_categories = _.pluck(db.categories.find({app: appId}).fetch(), '_id') if appId == "workflow" if workflow_categories.length > 0 return '' # return Steedos.getWorkflowCategoriesBadge(workflow_categories, Steedos.getSpaceId()) return Steedos.getBadge("workflow") else if appId == "cms" return Steedos.getBadge("cms") appUrl = db.apps.findOne(appId).url if appUrl == "/calendar" return Steedos.getBadge(appId) else if /^\/?workflow\b/.test(appUrl) # 如果appId不为workflow,但是url为/workflow格式则按workflow这个app来显示badge if workflow_categories.length > 0 return '' # return Steedos.getWorkflowCategoriesBadge(workflow_categories, Steedos.getSpaceId()) return Steedos.getBadge("workflow") return "" subsReady: -> # 增加Meteor.loggingIn()判断的原因是用户在登出系统的短短几秒内,顶部左侧图标有可能会从工作工特定LOGO变成默认的华炎LOGO造成视觉偏差 return Steedos.subsBootstrap.ready("steedos_keyvalues") && Steedos.subsSpaceBase.ready("apps") && !Meteor.loggingIn() eachEnd: (index)-> appCount = Steedos.getSpaceApps().count() if index == appCount - 1 Session.set("base_each_apps_end", (new Date()).getTime()) isShowMenuAppsLink: -> return !Session.get("apps") Template.steedosHeader.events 'click .menu-app-link': (event) -> Steedos.openApp event.currentTarget.dataset.appid 'click .menu-apps-link': (event) -> Modal.show "app_list_box_modal" 'click .steedos-help': (event) -> Steedos.showHelp(); Template.steedosHeader.displayControl = ()-> maxWidth = $(".navbar-nav-apps").width() - 90; sumWidth = 33; last = null $(".navbar-nav-apps").children().each (index)-> sumWidth += $(this).width() isActive = $(this).hasClass("active") if sumWidth >= maxWidth && index < $(".navbar-nav-apps").children().length - 1 && !isActive $(this).hide() else $(this).show() if sumWidth >= maxWidth && !last?.hasClass("active") last?.hide() last = $(this) Template.steedosHeader.onCreated ()-> $(window).resize -> Template.steedosHeader.displayControl() Template.steedosHeader.onRendered ()-> this.autorun (computation)-> db.steedos_keyvalues.findOne({user:Steedos.userId(),key:"zoom"}) Session.get("base_each_apps_end") Template.steedosHeader.displayControl() this.autorun ()-> Steedos.getCurrentAppId() Meteor.defer(Template.steedosHeader.displayControl) $('[data-toggle="offcanvas"]').on "click", ()-> #绑定offcanvas click事件,由于offcanvas过程有300毫秒的动作,此处延时调用header displayControl函数 setTimeout ()-> Template.steedosHeader.displayControl() , 301
50500
Template.steedosHeader.helpers appBadge: (appId)-> workflow_categories = _.pluck(db.categories.find({app: appId}).fetch(), '_id') if appId == "workflow" if workflow_categories.length > 0 return '' # return Steedos.getWorkflowCategoriesBadge(workflow_categories, Steedos.getSpaceId()) return Steedos.getBadge("workflow") else if appId == "cms" return Steedos.getBadge("cms") appUrl = db.apps.findOne(appId).url if appUrl == "/calendar" return Steedos.getBadge(appId) else if /^\/?workflow\b/.test(appUrl) # 如果appId不为workflow,但是url为/workflow格式则按workflow这个app来显示badge if workflow_categories.length > 0 return '' # return Steedos.getWorkflowCategoriesBadge(workflow_categories, Steedos.getSpaceId()) return Steedos.getBadge("workflow") return "" subsReady: -> # 增加Meteor.loggingIn()判断的原因是用户在登出系统的短短几秒内,顶部左侧图标有可能会从工作工特定LOGO变成默认的华炎LOGO造成视觉偏差 return Steedos.subsBootstrap.ready("steedos_keyvalues") && Steedos.subsSpaceBase.ready("apps") && !Meteor.loggingIn() eachEnd: (index)-> appCount = Steedos.getSpaceApps().count() if index == appCount - 1 Session.set("base_each_apps_end", (new Date()).getTime()) isShowMenuAppsLink: -> return !Session.get("apps") Template.steedosHeader.events 'click .menu-app-link': (event) -> Steedos.openApp event.currentTarget.dataset.appid 'click .menu-apps-link': (event) -> Modal.show "app_list_box_modal" 'click .steedos-help': (event) -> Steedos.showHelp(); Template.steedosHeader.displayControl = ()-> maxWidth = $(".navbar-nav-apps").width() - 90; sumWidth = 33; last = null $(".navbar-nav-apps").children().each (index)-> sumWidth += $(this).width() isActive = $(this).hasClass("active") if sumWidth >= maxWidth && index < $(".navbar-nav-apps").children().length - 1 && !isActive $(this).hide() else $(this).show() if sumWidth >= maxWidth && !last?.hasClass("active") last?.hide() last = $(this) Template.steedosHeader.onCreated ()-> $(window).resize -> Template.steedosHeader.displayControl() Template.steedosHeader.onRendered ()-> this.autorun (computation)-> db.steedos_keyvalues.findOne({user:Steedos.userId(),key:"<KEY>"}) Session.get("base_each_apps_end") Template.steedosHeader.displayControl() this.autorun ()-> Steedos.getCurrentAppId() Meteor.defer(Template.steedosHeader.displayControl) $('[data-toggle="offcanvas"]').on "click", ()-> #绑定offcanvas click事件,由于offcanvas过程有300毫秒的动作,此处延时调用header displayControl函数 setTimeout ()-> Template.steedosHeader.displayControl() , 301
true
Template.steedosHeader.helpers appBadge: (appId)-> workflow_categories = _.pluck(db.categories.find({app: appId}).fetch(), '_id') if appId == "workflow" if workflow_categories.length > 0 return '' # return Steedos.getWorkflowCategoriesBadge(workflow_categories, Steedos.getSpaceId()) return Steedos.getBadge("workflow") else if appId == "cms" return Steedos.getBadge("cms") appUrl = db.apps.findOne(appId).url if appUrl == "/calendar" return Steedos.getBadge(appId) else if /^\/?workflow\b/.test(appUrl) # 如果appId不为workflow,但是url为/workflow格式则按workflow这个app来显示badge if workflow_categories.length > 0 return '' # return Steedos.getWorkflowCategoriesBadge(workflow_categories, Steedos.getSpaceId()) return Steedos.getBadge("workflow") return "" subsReady: -> # 增加Meteor.loggingIn()判断的原因是用户在登出系统的短短几秒内,顶部左侧图标有可能会从工作工特定LOGO变成默认的华炎LOGO造成视觉偏差 return Steedos.subsBootstrap.ready("steedos_keyvalues") && Steedos.subsSpaceBase.ready("apps") && !Meteor.loggingIn() eachEnd: (index)-> appCount = Steedos.getSpaceApps().count() if index == appCount - 1 Session.set("base_each_apps_end", (new Date()).getTime()) isShowMenuAppsLink: -> return !Session.get("apps") Template.steedosHeader.events 'click .menu-app-link': (event) -> Steedos.openApp event.currentTarget.dataset.appid 'click .menu-apps-link': (event) -> Modal.show "app_list_box_modal" 'click .steedos-help': (event) -> Steedos.showHelp(); Template.steedosHeader.displayControl = ()-> maxWidth = $(".navbar-nav-apps").width() - 90; sumWidth = 33; last = null $(".navbar-nav-apps").children().each (index)-> sumWidth += $(this).width() isActive = $(this).hasClass("active") if sumWidth >= maxWidth && index < $(".navbar-nav-apps").children().length - 1 && !isActive $(this).hide() else $(this).show() if sumWidth >= maxWidth && !last?.hasClass("active") last?.hide() last = $(this) Template.steedosHeader.onCreated ()-> $(window).resize -> Template.steedosHeader.displayControl() Template.steedosHeader.onRendered ()-> this.autorun (computation)-> db.steedos_keyvalues.findOne({user:Steedos.userId(),key:"PI:KEY:<KEY>END_PI"}) Session.get("base_each_apps_end") Template.steedosHeader.displayControl() this.autorun ()-> Steedos.getCurrentAppId() Meteor.defer(Template.steedosHeader.displayControl) $('[data-toggle="offcanvas"]').on "click", ()-> #绑定offcanvas click事件,由于offcanvas过程有300毫秒的动作,此处延时调用header displayControl函数 setTimeout ()-> Template.steedosHeader.displayControl() , 301
[ { "context": "546'\n desc: 'En face du Mac Do'\n name: 'Saint-Lazare'\n lineType: 'BUS'\n lineName: 'BUS 231'\n", "end": 237, "score": 0.9998216032981873, "start": 225, "tag": "NAME", "value": "Saint-Lazare" }, { "context": "546'\n desc: 'En face du Mac Do'\n...
lib/entity/test/stop.coffee
dorianb/Web-application---Ethylocl-
0
should = require 'should' Stop = require '../stop' describe 'Stop entity', -> it 'Create stop', (next) -> data = id: '0' lat: '48.853611' lon: '2.287546' desc: 'En face du Mac Do' name: 'Saint-Lazare' lineType: 'BUS' lineName: 'BUS 231' stop = Stop data stop.id.should.eql data.id stop.lat.should.eql data.lat stop.lon.should.eql data.lon stop.desc.should.eql data.desc stop.name.should.eql data.name stop.lineType.should.eql data.lineType stop.lineName.should.eql data.lineName next() it 'Get stop', (next) -> data = id: '0' lat: '48.853611' lon: '2.287546' desc: 'En face du Mac Do' name: 'Saint-Lazare' lineType: 'BUS' lineName: 'BUS 231' stop = Stop data stop = stop.get() stop.id.should.eql data.id stop.lat.should.eql data.lat stop.lon.should.eql data.lon stop.desc.should.eql data.desc stop.name.should.eql data.name stop.lineType.should.eql data.lineType stop.lineName.should.eql data.lineName next() it 'Stop toString', (next) -> data = id: '0' lat: '48.853611' lon: '2.287546' stop = Stop data string = stop.toString() string.should.eql "Stop id:0 lat:48.853611 lon:2.287546" next()
42235
should = require 'should' Stop = require '../stop' describe 'Stop entity', -> it 'Create stop', (next) -> data = id: '0' lat: '48.853611' lon: '2.287546' desc: 'En face du Mac Do' name: '<NAME>' lineType: 'BUS' lineName: 'BUS 231' stop = Stop data stop.id.should.eql data.id stop.lat.should.eql data.lat stop.lon.should.eql data.lon stop.desc.should.eql data.desc stop.name.should.eql data.name stop.lineType.should.eql data.lineType stop.lineName.should.eql data.lineName next() it 'Get stop', (next) -> data = id: '0' lat: '48.853611' lon: '2.287546' desc: 'En face du Mac Do' name: '<NAME>' lineType: 'BUS' lineName: 'BUS 231' stop = Stop data stop = stop.get() stop.id.should.eql data.id stop.lat.should.eql data.lat stop.lon.should.eql data.lon stop.desc.should.eql data.desc stop.name.should.eql data.name stop.lineType.should.eql data.lineType stop.lineName.should.eql data.lineName next() it 'Stop toString', (next) -> data = id: '0' lat: '48.853611' lon: '2.287546' stop = Stop data string = stop.toString() string.should.eql "Stop id:0 lat:48.853611 lon:2.287546" next()
true
should = require 'should' Stop = require '../stop' describe 'Stop entity', -> it 'Create stop', (next) -> data = id: '0' lat: '48.853611' lon: '2.287546' desc: 'En face du Mac Do' name: 'PI:NAME:<NAME>END_PI' lineType: 'BUS' lineName: 'BUS 231' stop = Stop data stop.id.should.eql data.id stop.lat.should.eql data.lat stop.lon.should.eql data.lon stop.desc.should.eql data.desc stop.name.should.eql data.name stop.lineType.should.eql data.lineType stop.lineName.should.eql data.lineName next() it 'Get stop', (next) -> data = id: '0' lat: '48.853611' lon: '2.287546' desc: 'En face du Mac Do' name: 'PI:NAME:<NAME>END_PI' lineType: 'BUS' lineName: 'BUS 231' stop = Stop data stop = stop.get() stop.id.should.eql data.id stop.lat.should.eql data.lat stop.lon.should.eql data.lon stop.desc.should.eql data.desc stop.name.should.eql data.name stop.lineType.should.eql data.lineType stop.lineName.should.eql data.lineName next() it 'Stop toString', (next) -> data = id: '0' lat: '48.853611' lon: '2.287546' stop = Stop data string = stop.toString() string.should.eql "Stop id:0 lat:48.853611 lon:2.287546" next()
[ { "context": " user: connection.user\n pass: connection.password || \"\"\n sendImmediatel", "end": 8188, "score": 0.6760265231132507, "start": 8178, "tag": "PASSWORD", "value": "connection" }, { "context": "nection.user\n pas...
lib/existdb-tree-view.coffee
subugoe/atom-existdb
10
TreeView = require "./tree-view.js" XQUtils = require './xquery-helper' {dialog} = require './dialog.js' # EXistEditor = require './editor' request = require 'request' path = require 'path' fs = require 'fs' tmp = require 'tmp' mkdirp = require 'mkdirp' {CompositeDisposable, Emitter} = require 'atom' mime = require 'mime' {exec} = require('child_process') Shell = require('shell') module.exports = class EXistTreeView extends Emitter @tmpDir: null constructor: (@state, @config) -> super mime.define({ "application/xquery": ["xq", "xql", "xquery", "xqm"], "application/xml": ["odd", "xconf"] }) atom.packages.activatePackage('tree-view').then((pkg) => @fileTree = pkg.mainModule.getTreeViewInstance() ) atom.workspace.observeTextEditors((editor) => buffer = editor.getBuffer() p = buffer.getId() match = /^exist:\/\/(.*?)(\/db.*)$/.exec(p) if match and not buffer._remote? server = match[1] p = match[2] console.log("Reopen %s from database %s", p, server) editor.destroy() @open(path: p, server) ) @disposables = new CompositeDisposable() @element = document.createElement("div") @element.classList.add("existdb-tree", "block", "tool-panel", "focusable-panel") @select = document.createElement("select") @select.classList.add("existdb-database-select") @element.appendChild(@select) @treeView = new TreeView() @element.appendChild(@treeView.element) @initServerList() @config.activeServer = @getActiveServer() @select.addEventListener('change', => @populate() @config.activeServer = @getActiveServer() ) @config.onConfigChanged(([configs, globalConfig]) => @initServerList() @checkServer(() => @populate()) ) atom.config.observe 'existdb-tree-view.scrollAnimation', (enabled) => @animationDuration = if enabled then 300 else 0 atom.config.onDidChange('existdb.server', (ev) => @checkServer(() => @populate())) atom.config.onDidChange('existdb.user', (ev) => @checkServer(() => @populate())) atom.config.onDidChange('existdb.password', (ev) => @checkServer(() => @populate())) atom.config.onDidChange('existdb.root', (ev) => @checkServer(() => @populate())) # @disposables.add atom.workspace.addOpener (uri) -> # if uri.startsWith "xmldb:exist:" # new EXistEditor() @toggle() if @state?.show @disposables.add atom.commands.add 'atom-workspace', 'existdb:reindex': (ev) => @reindex(ev.target.item) @disposables.add atom.commands.add 'atom-workspace', 'existdb:reload-tree-view': (ev) => @load(ev.target.item) @disposables.add atom.commands.add 'atom-workspace', 'existdb:new-file': (ev) => @newFile(ev.target.item) @disposables.add atom.commands.add 'atom-workspace', 'existdb:new-collection': (ev) => @newCollection(ev.target.item) @disposables.add atom.commands.add 'atom-workspace', 'existdb:remove-resource': (ev) => selection = @treeView.getSelected() if selection? and selection.length > 0 @removeResource(selection) else @removeResource([ev.target.spacePenView]) @disposables.add atom.commands.add 'atom-workspace', 'existdb:reconnect': => @checkServer(() => @populate()) @disposables.add atom.commands.add 'atom-workspace', 'existdb:upload-current': => @uploadCurrent() @disposables.add atom.commands.add 'atom-workspace', 'existdb:upload-selected': => @uploadSelected() @disposables.add atom.commands.add 'atom-workspace', 'existdb:deploy': @deploy @disposables.add atom.commands.add 'atom-workspace', 'existdb:open-in-browser': @openInBrowser # @disposables.add atom.commands.add 'atom-workspace', 'existdb:sync': # (ev) => @sync(ev.target.spacePenView) @populate() getDefaultLocation: () => 'right' getAllowedLocations: () => ['left', 'right'] getURI: () -> 'atom:existdb/tree-view' getTitle: () -> 'eXist Database' hasParent: () -> @element.parentNode? # Toggle the visibility of this view toggle: -> atom.workspace.toggle(this) initServerList: ()-> configs = @config.getConfig() @select.innerHTML = "" for name, config of configs.servers option = document.createElement("option") option.value = name option.title = config.server if name == @state?.activeServer option.selected = true option.appendChild(document.createTextNode(name)) @select.appendChild(option) getActiveServer: -> @select.options[@select.selectedIndex].value serialize: -> show: @hasParent() activeServer: @getActiveServer() populate: => root = { label: "db", path: "/db", icon: "icon-database", type: "collection", children: [], loaded: true } console.log("populating %o", root) @treeView.setRoot(root, false) @checkServer(() => @load(root)) load: (item, callback) => self = this connection = @config.getConnection(null, @getActiveServer()) console.log("Loading collection contents for item #{item.path} using server #{connection.server}") url = "#{connection.server}/apps/atom-editor/browse.xql?root=#{item.path}" options = uri: url method: "GET" json: true strictSSL: false auth: user: connection.user pass: connection.password || "" sendImmediately: true request( options, (error, response, body) => if error? or response.statusCode != 200 atom.notifications.addWarning("Failed to load database contents", detail: if response? then response.statusMessage else error) else item.view.setChildren(body) for child in body child.view.onSelect(self.onSelect) child.view.onDblClick(self.onDblClick) if child.type == 'collection' child.view.onDrop(self.upload) callback() if callback ) removeResource: (selection) => message = if selection.length == 1 then "resource #{selection[0].path}" else "#{selection.length} resources" atom.confirm message: "Delete resource?" detailedMessage: "Are you sure you want to delete #{message}?" buttons: Yes: => for item in selection @doRemove(item) No: null doRemove: (resource) => connection = @config.getConnection(null, @getActiveServer()) url = "#{connection.server}/rest/#{resource.path}" options = uri: url method: "DELETE" strictSSL: false auth: user: connection.user pass: connection.password || "" sendImmediately: true @emit("status", "Deleting #{resource.path}...") request( options, (error, response, body) => if error? atom.notifications.addError("Failed to delete #{resource.path}", detail: if response? then response.statusMessage else error) else @emit("status", "") resource.view.delete() ) newFile: (item) => dialog.prompt("Enter a name for the new resource:").then((name) => @createFile(item, name) if name?) newCollection: (item) => parent = item.path dialog.prompt("Enter a name for the new collection:").then((name) => if name? query = "xmldb:create-collection('#{parent}', '#{name}')" @runQuery(query, (error, response) -> atom.notifications.addError("Failed to create collection #{parent}/#{name}", detail: if response? then response.statusMessage else error) (body) => atom.notifications.addSuccess("Collection #{parent}/#{name} created") collection = { path: "#{parent}/#{name}" label: name loaded: true type: "collection" icon: "icon-file-directory" } item.view.addChild(collection) collection.view.onSelect(@onSelect) collection.view.onDblClick(@onDblClick) collection.view.onDrop(@upload) ) ) createFile: (item, name) -> self = this collection = item.path resource = path: "#{collection}/#{name}" type: "resource" icon: "icon-file-text" label: name loaded: true tmpDir = @getTempDir(resource.path) tmpFile = path.join(tmpDir, path.basename(resource.path)) promise = atom.workspace.open(null) promise.then((newEditor) -> item.view.addChild(resource) resource.view.onSelect(self.onSelect) resource.view.onDblClick(self.onDblClick) buffer = newEditor.getBuffer() # buffer.getPath = () -> resource.path server = self.getActiveServer() connection = self.config.getConnection(null, server) buffer.getId = () -> self.getXMLDBUri(connection, resource.path) buffer.setPath(tmpFile) resource.editor = newEditor buffer._remote = resource onDidSave = buffer.onDidSave((ev) -> self.save(null, tmpFile, resource, mime.getType(resource.path)) ) onDidDestroy = buffer.onDidDestroy((ev) -> self.disposables.remove(onDidSave) self.disposables.remove(onDidDestroy) onDidDestroy.dispose() onDidSave.dispose() fs.unlink(tmpFile) ) self.disposables.add(onDidSave) self.disposables.add(onDidDestroy) ) open: (resource, server, onOpen) => # switch to existing editor if resource is already open editor = @getOpenEditor(resource) if editor? pane = atom.workspace.paneForItem(editor) pane.activateItem(editor) onOpen?(editor) return self = this server ?= @getActiveServer() connection = @config.getConnection(null, server) url = "#{connection.server}/apps/atom-editor/load.xql?path=#{resource.path}" tmpDir = @getTempDir(resource.path) tmpFile = path.join(tmpDir, path.basename(resource.path)) @emit("status", "Opening #{resource.path} ...") console.log("Downloading %s to %s", resource.path, tmpFile) stream = fs.createWriteStream(tmpFile) options = uri: url method: "GET" strictSSL: false auth: user: connection.user pass: connection.password || "" sendImmediately: true contentType = null request(options) .on("response", (response) -> contentType = response.headers["content-type"] ) .on("error", (err) -> self.emit("status", "") atom.notifications.addError("Failed to download #{resource.path}", detail: err) ) .on("end", () -> self.emit("status", "") promise = atom.workspace.open(null) promise.then((newEditor) -> buffer = newEditor.getBuffer() # buffer.getPath = () -> resource.path buffer.setPath(tmpFile) buffer.getId = () => self.getXMLDBUri(connection, resource.path) buffer.loadSync() resource.editor = newEditor buffer._remote = resource onDidSave = buffer.onDidSave((ev) -> self.save(buffer, tmpFile, resource, contentType) ) onDidDestroy = buffer.onDidDestroy((ev) -> self.disposables.remove(onDidSave) self.disposables.remove(onDidDestroy) onDidDestroy.dispose() onDidSave.dispose() fs.unlink(tmpFile) ) self.disposables.add(onDidSave) self.disposables.add(onDidDestroy) if contentType == "application/xquery" XQUtils.xqlint(newEditor) onOpen?(newEditor) ) ) .pipe(stream) getXMLDBUri: (connection, path) -> return "exist://#{connection.name}#{path}" getOpenEditor: (resource) -> for editor in atom.workspace.getTextEditors() if editor.getBuffer()._remote?.path == resource.path return editor return null save: (buffer, file, resource, contentType) -> return new Promise((resolve, reject) => editor = atom.workspace.getActiveTextEditor() if buffer? connection = @config.getConnection(buffer.getId()) else connection = @config.getConnection(null, @getActiveServer()) url = "#{connection.server}/rest/#{resource.path}" contentType = mime.getType(path.extname(file)) unless contentType console.log("Saving %s to %s using content type %s", resource.path, connection.server, contentType) self = this options = uri: url method: "PUT" strictSSL: false auth: user: connection.user pass: connection.password || "" sendImmediately: true headers: "Content-Type": contentType fs.createReadStream(file).pipe( request( options, (error, response, body) -> if error? atom.notifications.addError("Failed to upload #{resource.path}", detail: if response? then response.statusMessage else error) reject() else resolve() ) ) ) uploadCurrent: () => selected = @treeView.getSelected() if selected.length != 1 or selected[0].item.type == "resource" atom.notifications.addError("Please select a single target collection for the upload in the database tree view") return editor = atom.workspace.getActiveTextEditor() fileName = path.basename(editor.getPath()) @emit("status", "Uploading file #{fileName}...") @save(null, editor.getPath(), path: "#{selected[0].item.path}/#{fileName}", null).then(() => @load(selected[0].item) @emit("status", "") ) uploadSelected: () -> locals = @fileTree.selectedPaths() if locals? and locals.length > 0 selected = @treeView.getSelected() if selected.length != 1 or selected[0].type == "resource" atom.notifications.addError("Please select a single target collection for the upload in the database tree view") return @upload(locals, selected[0]) upload: ({target, files}) => @emit("status", "Uploading #{files.length} files ...") deploy = files.every((file) -> file.endsWith(".xar")) if deploy atom.confirm message: "Install Packages?" detailedMessage: "Would you like to install the packages?" buttons: Yes: -> deploy = true No: -> deploy = false for file in files if (deploy) promise = @deploy(file) root = @treeView.getNode("/db/apps") else fileName = path.basename(file) promise = @save(null, file, path: "#{target.path}/#{fileName}", null) root = target promise.then(() => @load(root) @emit("status", "") ) deploy: (xar) => return new Promise((resolve, reject) => if xar? and typeof xar == "string" then paths = [ xar ] if not paths? paths = @fileTree.selectedPaths() if paths? and paths.length > 0 for file in paths fileName = path.basename(file) targetPath = "/db/system/repo/#{fileName}" @emit("status", "Uploading package ...") @save(null, file, path: targetPath, null).then(() => @emit("status", "Deploying package ...") query = """ xquery version "3.1"; declare namespace expath="http://expath.org/ns/pkg"; declare namespace output="http://www.w3.org/2010/xslt-xquery-serialization"; declare option output:method "json"; declare option output:media-type "application/json"; declare variable $repo := "http://demo.exist-db.org/exist/apps/public-repo/modules/find.xql"; declare function local:remove($package-url as xs:string) as xs:boolean { if ($package-url = repo:list()) then let $undeploy := repo:undeploy($package-url) let $remove := repo:remove($package-url) return $remove else false() }; let $xarPath := "#{targetPath}" let $meta := try { compression:unzip( util:binary-doc($xarPath), function($path as xs:anyURI, $type as xs:string, $param as item()*) as xs:boolean { $path = "expath-pkg.xml" }, (), function($path as xs:anyURI, $type as xs:string, $data as item()?, $param as item()*) { $data }, () ) } catch * { error(xs:QName("local:xar-unpack-error"), "Failed to unpack archive") } let $package := $meta//expath:package/string(@name) let $removed := local:remove($package) let $installed := repo:install-and-deploy-from-db($xarPath, $repo) return repo:get-root() """ @runQuery(query, (error, response) => atom.notifications.addError("Failed to deploy package", detail: if response? then response.body else error) @emit("status", "") reject() (body) => @emit("status", "") resolve() ) ) ) openInBrowser: (ev) => item = ev.target.item target = item.path.replace(/^.*?\/([^\/]+)$/, "$1") connection = @config.getConnection(null, @getActiveServer()) url = "#{connection.server}/apps/#{target}" process_architecture = process.platform switch process_architecture when 'darwin' then exec ('open "' + url + '"') when 'linux' then exec ('xdg-open "' + url + '"') when 'win32' then Shell.openExternal(url) reindex: (item) -> query = "xmldb:reindex('#{item.path}')" @emit("status", "Reindexing #{item.path}...") @runQuery(query, (error, response) -> atom.notifications.addError("Failed to reindex collection #{item.path}", detail: if response? then response.statusMessage else error) (body) => @emit("status", "") atom.notifications.addSuccess("Collection #{item.path} reindexed") ) sync: (item) => dialog.prompt("Path to sync to (server-side):").then( (path) => query = "file:sync('#{item.path}', '#{path}', ())" @emit("status", "Sync to directory...") @runQuery(query, (error, response) -> @emit("status", "") atom.notifications.addError("Failed to sync collection #{item.path}", detail: if response? then response.statusMessage else error) (body) => @emit("status", "") atom.notifications.addSuccess("Collection #{item.path} synched to directory #{path}") ) ) onSelect: ({node, item}) => if not item.loaded @load(item, () -> item.loaded = true item.view.toggleClass('collapsed') ) onDblClick: ({node, item}) => if item.type == "resource" @open(item) destroy: -> @element.remove() @disposables.dispose() @tempDir.removeCallback() if @tempDir remove: -> @destroy() getTempDir: (uri) -> @tempDir = tmp.dirSync({ mode: 0o750, prefix: 'atom-exist_', unsafeCleanup: true }) unless @tempDir tmpPath = path.join(fs.realpathSync(@tempDir.name), path.dirname(uri)) mkdirp.sync(tmpPath) return tmpPath runQuery: (query, onError, onSuccess) => editor = atom.workspace.getActiveTextEditor() connection = @config.getConnection(null, @getActiveServer()) url = "#{connection.server}/rest/db?_query=#{query}&_wrap=no" options = uri: url method: "GET" json: true strictSSL: false auth: user: connection.user pass: connection.password || "" sendImmediately: true request( options, (error, response, body) => if error? or response.statusCode != 200 onError?(error, response) else onSuccess?(body) ) checkServer: (onSuccess) => xar = @getXAR() query = """ xquery version "3.0"; declare namespace expath="http://expath.org/ns/pkg"; declare namespace output="http://www.w3.org/2010/xslt-xquery-serialization"; declare option output:method "json"; declare option output:media-type "application/json"; if ("http://exist-db.org/apps/atom-editor" = repo:list()) then let $data := repo:get-resource("http://exist-db.org/apps/atom-editor", "expath-pkg.xml") let $xml := parse-xml(util:binary-to-string($data)) return if ($xml/expath:package/@version = "#{xar.version}") then true() else $xml/expath:package/@version/string() else false() """ @runQuery(query, (error, response) -> atom.notifications.addWarning("Failed to access database", detail: if response? then response.statusMessage else error) (body) => if body == true onSuccess?() else if typeof body == "string" message = "Installed support app has version #{body}. A newer version (#{xar.version}) is recommended for proper operation. Do you want to install it?" else message = "This package requires a small support app to be installed on the eXistdb server. Do you want to install it?" atom.confirm message: "Install server-side support app?" detailedMessage: message buttons: Yes: => @deploy(xar.path).then(onSuccess) No: -> if typeof body == "string" then onSuccess?() else null ) getXAR: () => pkgDir = atom.packages.resolvePackagePath("existdb") if pkgDir? files = fs.readdirSync(path.join(pkgDir, "resources/db")) for file in files if file.endsWith(".xar") return { version: file.replace(/^.*-([\d\.]+)\.xar/, "$1"), path: path.join(pkgDir, "resources/db", file) }
133968
TreeView = require "./tree-view.js" XQUtils = require './xquery-helper' {dialog} = require './dialog.js' # EXistEditor = require './editor' request = require 'request' path = require 'path' fs = require 'fs' tmp = require 'tmp' mkdirp = require 'mkdirp' {CompositeDisposable, Emitter} = require 'atom' mime = require 'mime' {exec} = require('child_process') Shell = require('shell') module.exports = class EXistTreeView extends Emitter @tmpDir: null constructor: (@state, @config) -> super mime.define({ "application/xquery": ["xq", "xql", "xquery", "xqm"], "application/xml": ["odd", "xconf"] }) atom.packages.activatePackage('tree-view').then((pkg) => @fileTree = pkg.mainModule.getTreeViewInstance() ) atom.workspace.observeTextEditors((editor) => buffer = editor.getBuffer() p = buffer.getId() match = /^exist:\/\/(.*?)(\/db.*)$/.exec(p) if match and not buffer._remote? server = match[1] p = match[2] console.log("Reopen %s from database %s", p, server) editor.destroy() @open(path: p, server) ) @disposables = new CompositeDisposable() @element = document.createElement("div") @element.classList.add("existdb-tree", "block", "tool-panel", "focusable-panel") @select = document.createElement("select") @select.classList.add("existdb-database-select") @element.appendChild(@select) @treeView = new TreeView() @element.appendChild(@treeView.element) @initServerList() @config.activeServer = @getActiveServer() @select.addEventListener('change', => @populate() @config.activeServer = @getActiveServer() ) @config.onConfigChanged(([configs, globalConfig]) => @initServerList() @checkServer(() => @populate()) ) atom.config.observe 'existdb-tree-view.scrollAnimation', (enabled) => @animationDuration = if enabled then 300 else 0 atom.config.onDidChange('existdb.server', (ev) => @checkServer(() => @populate())) atom.config.onDidChange('existdb.user', (ev) => @checkServer(() => @populate())) atom.config.onDidChange('existdb.password', (ev) => @checkServer(() => @populate())) atom.config.onDidChange('existdb.root', (ev) => @checkServer(() => @populate())) # @disposables.add atom.workspace.addOpener (uri) -> # if uri.startsWith "xmldb:exist:" # new EXistEditor() @toggle() if @state?.show @disposables.add atom.commands.add 'atom-workspace', 'existdb:reindex': (ev) => @reindex(ev.target.item) @disposables.add atom.commands.add 'atom-workspace', 'existdb:reload-tree-view': (ev) => @load(ev.target.item) @disposables.add atom.commands.add 'atom-workspace', 'existdb:new-file': (ev) => @newFile(ev.target.item) @disposables.add atom.commands.add 'atom-workspace', 'existdb:new-collection': (ev) => @newCollection(ev.target.item) @disposables.add atom.commands.add 'atom-workspace', 'existdb:remove-resource': (ev) => selection = @treeView.getSelected() if selection? and selection.length > 0 @removeResource(selection) else @removeResource([ev.target.spacePenView]) @disposables.add atom.commands.add 'atom-workspace', 'existdb:reconnect': => @checkServer(() => @populate()) @disposables.add atom.commands.add 'atom-workspace', 'existdb:upload-current': => @uploadCurrent() @disposables.add atom.commands.add 'atom-workspace', 'existdb:upload-selected': => @uploadSelected() @disposables.add atom.commands.add 'atom-workspace', 'existdb:deploy': @deploy @disposables.add atom.commands.add 'atom-workspace', 'existdb:open-in-browser': @openInBrowser # @disposables.add atom.commands.add 'atom-workspace', 'existdb:sync': # (ev) => @sync(ev.target.spacePenView) @populate() getDefaultLocation: () => 'right' getAllowedLocations: () => ['left', 'right'] getURI: () -> 'atom:existdb/tree-view' getTitle: () -> 'eXist Database' hasParent: () -> @element.parentNode? # Toggle the visibility of this view toggle: -> atom.workspace.toggle(this) initServerList: ()-> configs = @config.getConfig() @select.innerHTML = "" for name, config of configs.servers option = document.createElement("option") option.value = name option.title = config.server if name == @state?.activeServer option.selected = true option.appendChild(document.createTextNode(name)) @select.appendChild(option) getActiveServer: -> @select.options[@select.selectedIndex].value serialize: -> show: @hasParent() activeServer: @getActiveServer() populate: => root = { label: "db", path: "/db", icon: "icon-database", type: "collection", children: [], loaded: true } console.log("populating %o", root) @treeView.setRoot(root, false) @checkServer(() => @load(root)) load: (item, callback) => self = this connection = @config.getConnection(null, @getActiveServer()) console.log("Loading collection contents for item #{item.path} using server #{connection.server}") url = "#{connection.server}/apps/atom-editor/browse.xql?root=#{item.path}" options = uri: url method: "GET" json: true strictSSL: false auth: user: connection.user pass: connection.password || "" sendImmediately: true request( options, (error, response, body) => if error? or response.statusCode != 200 atom.notifications.addWarning("Failed to load database contents", detail: if response? then response.statusMessage else error) else item.view.setChildren(body) for child in body child.view.onSelect(self.onSelect) child.view.onDblClick(self.onDblClick) if child.type == 'collection' child.view.onDrop(self.upload) callback() if callback ) removeResource: (selection) => message = if selection.length == 1 then "resource #{selection[0].path}" else "#{selection.length} resources" atom.confirm message: "Delete resource?" detailedMessage: "Are you sure you want to delete #{message}?" buttons: Yes: => for item in selection @doRemove(item) No: null doRemove: (resource) => connection = @config.getConnection(null, @getActiveServer()) url = "#{connection.server}/rest/#{resource.path}" options = uri: url method: "DELETE" strictSSL: false auth: user: connection.user pass: <PASSWORD>.<PASSWORD> || "" sendImmediately: true @emit("status", "Deleting #{resource.path}...") request( options, (error, response, body) => if error? atom.notifications.addError("Failed to delete #{resource.path}", detail: if response? then response.statusMessage else error) else @emit("status", "") resource.view.delete() ) newFile: (item) => dialog.prompt("Enter a name for the new resource:").then((name) => @createFile(item, name) if name?) newCollection: (item) => parent = item.path dialog.prompt("Enter a name for the new collection:").then((name) => if name? query = "xmldb:create-collection('#{parent}', '#{name}')" @runQuery(query, (error, response) -> atom.notifications.addError("Failed to create collection #{parent}/#{name}", detail: if response? then response.statusMessage else error) (body) => atom.notifications.addSuccess("Collection #{parent}/#{name} created") collection = { path: "#{parent}/#{name}" label: name loaded: true type: "collection" icon: "icon-file-directory" } item.view.addChild(collection) collection.view.onSelect(@onSelect) collection.view.onDblClick(@onDblClick) collection.view.onDrop(@upload) ) ) createFile: (item, name) -> self = this collection = item.path resource = path: "#{collection}/#{name}" type: "resource" icon: "icon-file-text" label: name loaded: true tmpDir = @getTempDir(resource.path) tmpFile = path.join(tmpDir, path.basename(resource.path)) promise = atom.workspace.open(null) promise.then((newEditor) -> item.view.addChild(resource) resource.view.onSelect(self.onSelect) resource.view.onDblClick(self.onDblClick) buffer = newEditor.getBuffer() # buffer.getPath = () -> resource.path server = self.getActiveServer() connection = self.config.getConnection(null, server) buffer.getId = () -> self.getXMLDBUri(connection, resource.path) buffer.setPath(tmpFile) resource.editor = newEditor buffer._remote = resource onDidSave = buffer.onDidSave((ev) -> self.save(null, tmpFile, resource, mime.getType(resource.path)) ) onDidDestroy = buffer.onDidDestroy((ev) -> self.disposables.remove(onDidSave) self.disposables.remove(onDidDestroy) onDidDestroy.dispose() onDidSave.dispose() fs.unlink(tmpFile) ) self.disposables.add(onDidSave) self.disposables.add(onDidDestroy) ) open: (resource, server, onOpen) => # switch to existing editor if resource is already open editor = @getOpenEditor(resource) if editor? pane = atom.workspace.paneForItem(editor) pane.activateItem(editor) onOpen?(editor) return self = this server ?= @getActiveServer() connection = @config.getConnection(null, server) url = "#{connection.server}/apps/atom-editor/load.xql?path=#{resource.path}" tmpDir = @getTempDir(resource.path) tmpFile = path.join(tmpDir, path.basename(resource.path)) @emit("status", "Opening #{resource.path} ...") console.log("Downloading %s to %s", resource.path, tmpFile) stream = fs.createWriteStream(tmpFile) options = uri: url method: "GET" strictSSL: false auth: user: connection.user pass: connection.<PASSWORD> || "" sendImmediately: true contentType = null request(options) .on("response", (response) -> contentType = response.headers["content-type"] ) .on("error", (err) -> self.emit("status", "") atom.notifications.addError("Failed to download #{resource.path}", detail: err) ) .on("end", () -> self.emit("status", "") promise = atom.workspace.open(null) promise.then((newEditor) -> buffer = newEditor.getBuffer() # buffer.getPath = () -> resource.path buffer.setPath(tmpFile) buffer.getId = () => self.getXMLDBUri(connection, resource.path) buffer.loadSync() resource.editor = newEditor buffer._remote = resource onDidSave = buffer.onDidSave((ev) -> self.save(buffer, tmpFile, resource, contentType) ) onDidDestroy = buffer.onDidDestroy((ev) -> self.disposables.remove(onDidSave) self.disposables.remove(onDidDestroy) onDidDestroy.dispose() onDidSave.dispose() fs.unlink(tmpFile) ) self.disposables.add(onDidSave) self.disposables.add(onDidDestroy) if contentType == "application/xquery" XQUtils.xqlint(newEditor) onOpen?(newEditor) ) ) .pipe(stream) getXMLDBUri: (connection, path) -> return "exist://#{connection.name}#{path}" getOpenEditor: (resource) -> for editor in atom.workspace.getTextEditors() if editor.getBuffer()._remote?.path == resource.path return editor return null save: (buffer, file, resource, contentType) -> return new Promise((resolve, reject) => editor = atom.workspace.getActiveTextEditor() if buffer? connection = @config.getConnection(buffer.getId()) else connection = @config.getConnection(null, @getActiveServer()) url = "#{connection.server}/rest/#{resource.path}" contentType = mime.getType(path.extname(file)) unless contentType console.log("Saving %s to %s using content type %s", resource.path, connection.server, contentType) self = this options = uri: url method: "PUT" strictSSL: false auth: user: connection.user pass: <PASSWORD> || "" sendImmediately: true headers: "Content-Type": contentType fs.createReadStream(file).pipe( request( options, (error, response, body) -> if error? atom.notifications.addError("Failed to upload #{resource.path}", detail: if response? then response.statusMessage else error) reject() else resolve() ) ) ) uploadCurrent: () => selected = @treeView.getSelected() if selected.length != 1 or selected[0].item.type == "resource" atom.notifications.addError("Please select a single target collection for the upload in the database tree view") return editor = atom.workspace.getActiveTextEditor() fileName = path.basename(editor.getPath()) @emit("status", "Uploading file #{fileName}...") @save(null, editor.getPath(), path: "#{selected[0].item.path}/#{fileName}", null).then(() => @load(selected[0].item) @emit("status", "") ) uploadSelected: () -> locals = @fileTree.selectedPaths() if locals? and locals.length > 0 selected = @treeView.getSelected() if selected.length != 1 or selected[0].type == "resource" atom.notifications.addError("Please select a single target collection for the upload in the database tree view") return @upload(locals, selected[0]) upload: ({target, files}) => @emit("status", "Uploading #{files.length} files ...") deploy = files.every((file) -> file.endsWith(".xar")) if deploy atom.confirm message: "Install Packages?" detailedMessage: "Would you like to install the packages?" buttons: Yes: -> deploy = true No: -> deploy = false for file in files if (deploy) promise = @deploy(file) root = @treeView.getNode("/db/apps") else fileName = path.basename(file) promise = @save(null, file, path: "#{target.path}/#{fileName}", null) root = target promise.then(() => @load(root) @emit("status", "") ) deploy: (xar) => return new Promise((resolve, reject) => if xar? and typeof xar == "string" then paths = [ xar ] if not paths? paths = @fileTree.selectedPaths() if paths? and paths.length > 0 for file in paths fileName = path.basename(file) targetPath = "/db/system/repo/#{fileName}" @emit("status", "Uploading package ...") @save(null, file, path: targetPath, null).then(() => @emit("status", "Deploying package ...") query = """ xquery version "3.1"; declare namespace expath="http://expath.org/ns/pkg"; declare namespace output="http://www.w3.org/2010/xslt-xquery-serialization"; declare option output:method "json"; declare option output:media-type "application/json"; declare variable $repo := "http://demo.exist-db.org/exist/apps/public-repo/modules/find.xql"; declare function local:remove($package-url as xs:string) as xs:boolean { if ($package-url = repo:list()) then let $undeploy := repo:undeploy($package-url) let $remove := repo:remove($package-url) return $remove else false() }; let $xarPath := "#{targetPath}" let $meta := try { compression:unzip( util:binary-doc($xarPath), function($path as xs:anyURI, $type as xs:string, $param as item()*) as xs:boolean { $path = "expath-pkg.xml" }, (), function($path as xs:anyURI, $type as xs:string, $data as item()?, $param as item()*) { $data }, () ) } catch * { error(xs:QName("local:xar-unpack-error"), "Failed to unpack archive") } let $package := $meta//expath:package/string(@name) let $removed := local:remove($package) let $installed := repo:install-and-deploy-from-db($xarPath, $repo) return repo:get-root() """ @runQuery(query, (error, response) => atom.notifications.addError("Failed to deploy package", detail: if response? then response.body else error) @emit("status", "") reject() (body) => @emit("status", "") resolve() ) ) ) openInBrowser: (ev) => item = ev.target.item target = item.path.replace(/^.*?\/([^\/]+)$/, "$1") connection = @config.getConnection(null, @getActiveServer()) url = "#{connection.server}/apps/#{target}" process_architecture = process.platform switch process_architecture when 'darwin' then exec ('open "' + url + '"') when 'linux' then exec ('xdg-open "' + url + '"') when 'win32' then Shell.openExternal(url) reindex: (item) -> query = "xmldb:reindex('#{item.path}')" @emit("status", "Reindexing #{item.path}...") @runQuery(query, (error, response) -> atom.notifications.addError("Failed to reindex collection #{item.path}", detail: if response? then response.statusMessage else error) (body) => @emit("status", "") atom.notifications.addSuccess("Collection #{item.path} reindexed") ) sync: (item) => dialog.prompt("Path to sync to (server-side):").then( (path) => query = "file:sync('#{item.path}', '#{path}', ())" @emit("status", "Sync to directory...") @runQuery(query, (error, response) -> @emit("status", "") atom.notifications.addError("Failed to sync collection #{item.path}", detail: if response? then response.statusMessage else error) (body) => @emit("status", "") atom.notifications.addSuccess("Collection #{item.path} synched to directory #{path}") ) ) onSelect: ({node, item}) => if not item.loaded @load(item, () -> item.loaded = true item.view.toggleClass('collapsed') ) onDblClick: ({node, item}) => if item.type == "resource" @open(item) destroy: -> @element.remove() @disposables.dispose() @tempDir.removeCallback() if @tempDir remove: -> @destroy() getTempDir: (uri) -> @tempDir = tmp.dirSync({ mode: 0o750, prefix: 'atom-exist_', unsafeCleanup: true }) unless @tempDir tmpPath = path.join(fs.realpathSync(@tempDir.name), path.dirname(uri)) mkdirp.sync(tmpPath) return tmpPath runQuery: (query, onError, onSuccess) => editor = atom.workspace.getActiveTextEditor() connection = @config.getConnection(null, @getActiveServer()) url = "#{connection.server}/rest/db?_query=#{query}&_wrap=no" options = uri: url method: "GET" json: true strictSSL: false auth: user: connection.user pass: connection.password || "" sendImmediately: true request( options, (error, response, body) => if error? or response.statusCode != 200 onError?(error, response) else onSuccess?(body) ) checkServer: (onSuccess) => xar = @getXAR() query = """ xquery version "3.0"; declare namespace expath="http://expath.org/ns/pkg"; declare namespace output="http://www.w3.org/2010/xslt-xquery-serialization"; declare option output:method "json"; declare option output:media-type "application/json"; if ("http://exist-db.org/apps/atom-editor" = repo:list()) then let $data := repo:get-resource("http://exist-db.org/apps/atom-editor", "expath-pkg.xml") let $xml := parse-xml(util:binary-to-string($data)) return if ($xml/expath:package/@version = "#{xar.version}") then true() else $xml/expath:package/@version/string() else false() """ @runQuery(query, (error, response) -> atom.notifications.addWarning("Failed to access database", detail: if response? then response.statusMessage else error) (body) => if body == true onSuccess?() else if typeof body == "string" message = "Installed support app has version #{body}. A newer version (#{xar.version}) is recommended for proper operation. Do you want to install it?" else message = "This package requires a small support app to be installed on the eXistdb server. Do you want to install it?" atom.confirm message: "Install server-side support app?" detailedMessage: message buttons: Yes: => @deploy(xar.path).then(onSuccess) No: -> if typeof body == "string" then onSuccess?() else null ) getXAR: () => pkgDir = atom.packages.resolvePackagePath("existdb") if pkgDir? files = fs.readdirSync(path.join(pkgDir, "resources/db")) for file in files if file.endsWith(".xar") return { version: file.replace(/^.*-([\d\.]+)\.xar/, "$1"), path: path.join(pkgDir, "resources/db", file) }
true
TreeView = require "./tree-view.js" XQUtils = require './xquery-helper' {dialog} = require './dialog.js' # EXistEditor = require './editor' request = require 'request' path = require 'path' fs = require 'fs' tmp = require 'tmp' mkdirp = require 'mkdirp' {CompositeDisposable, Emitter} = require 'atom' mime = require 'mime' {exec} = require('child_process') Shell = require('shell') module.exports = class EXistTreeView extends Emitter @tmpDir: null constructor: (@state, @config) -> super mime.define({ "application/xquery": ["xq", "xql", "xquery", "xqm"], "application/xml": ["odd", "xconf"] }) atom.packages.activatePackage('tree-view').then((pkg) => @fileTree = pkg.mainModule.getTreeViewInstance() ) atom.workspace.observeTextEditors((editor) => buffer = editor.getBuffer() p = buffer.getId() match = /^exist:\/\/(.*?)(\/db.*)$/.exec(p) if match and not buffer._remote? server = match[1] p = match[2] console.log("Reopen %s from database %s", p, server) editor.destroy() @open(path: p, server) ) @disposables = new CompositeDisposable() @element = document.createElement("div") @element.classList.add("existdb-tree", "block", "tool-panel", "focusable-panel") @select = document.createElement("select") @select.classList.add("existdb-database-select") @element.appendChild(@select) @treeView = new TreeView() @element.appendChild(@treeView.element) @initServerList() @config.activeServer = @getActiveServer() @select.addEventListener('change', => @populate() @config.activeServer = @getActiveServer() ) @config.onConfigChanged(([configs, globalConfig]) => @initServerList() @checkServer(() => @populate()) ) atom.config.observe 'existdb-tree-view.scrollAnimation', (enabled) => @animationDuration = if enabled then 300 else 0 atom.config.onDidChange('existdb.server', (ev) => @checkServer(() => @populate())) atom.config.onDidChange('existdb.user', (ev) => @checkServer(() => @populate())) atom.config.onDidChange('existdb.password', (ev) => @checkServer(() => @populate())) atom.config.onDidChange('existdb.root', (ev) => @checkServer(() => @populate())) # @disposables.add atom.workspace.addOpener (uri) -> # if uri.startsWith "xmldb:exist:" # new EXistEditor() @toggle() if @state?.show @disposables.add atom.commands.add 'atom-workspace', 'existdb:reindex': (ev) => @reindex(ev.target.item) @disposables.add atom.commands.add 'atom-workspace', 'existdb:reload-tree-view': (ev) => @load(ev.target.item) @disposables.add atom.commands.add 'atom-workspace', 'existdb:new-file': (ev) => @newFile(ev.target.item) @disposables.add atom.commands.add 'atom-workspace', 'existdb:new-collection': (ev) => @newCollection(ev.target.item) @disposables.add atom.commands.add 'atom-workspace', 'existdb:remove-resource': (ev) => selection = @treeView.getSelected() if selection? and selection.length > 0 @removeResource(selection) else @removeResource([ev.target.spacePenView]) @disposables.add atom.commands.add 'atom-workspace', 'existdb:reconnect': => @checkServer(() => @populate()) @disposables.add atom.commands.add 'atom-workspace', 'existdb:upload-current': => @uploadCurrent() @disposables.add atom.commands.add 'atom-workspace', 'existdb:upload-selected': => @uploadSelected() @disposables.add atom.commands.add 'atom-workspace', 'existdb:deploy': @deploy @disposables.add atom.commands.add 'atom-workspace', 'existdb:open-in-browser': @openInBrowser # @disposables.add atom.commands.add 'atom-workspace', 'existdb:sync': # (ev) => @sync(ev.target.spacePenView) @populate() getDefaultLocation: () => 'right' getAllowedLocations: () => ['left', 'right'] getURI: () -> 'atom:existdb/tree-view' getTitle: () -> 'eXist Database' hasParent: () -> @element.parentNode? # Toggle the visibility of this view toggle: -> atom.workspace.toggle(this) initServerList: ()-> configs = @config.getConfig() @select.innerHTML = "" for name, config of configs.servers option = document.createElement("option") option.value = name option.title = config.server if name == @state?.activeServer option.selected = true option.appendChild(document.createTextNode(name)) @select.appendChild(option) getActiveServer: -> @select.options[@select.selectedIndex].value serialize: -> show: @hasParent() activeServer: @getActiveServer() populate: => root = { label: "db", path: "/db", icon: "icon-database", type: "collection", children: [], loaded: true } console.log("populating %o", root) @treeView.setRoot(root, false) @checkServer(() => @load(root)) load: (item, callback) => self = this connection = @config.getConnection(null, @getActiveServer()) console.log("Loading collection contents for item #{item.path} using server #{connection.server}") url = "#{connection.server}/apps/atom-editor/browse.xql?root=#{item.path}" options = uri: url method: "GET" json: true strictSSL: false auth: user: connection.user pass: connection.password || "" sendImmediately: true request( options, (error, response, body) => if error? or response.statusCode != 200 atom.notifications.addWarning("Failed to load database contents", detail: if response? then response.statusMessage else error) else item.view.setChildren(body) for child in body child.view.onSelect(self.onSelect) child.view.onDblClick(self.onDblClick) if child.type == 'collection' child.view.onDrop(self.upload) callback() if callback ) removeResource: (selection) => message = if selection.length == 1 then "resource #{selection[0].path}" else "#{selection.length} resources" atom.confirm message: "Delete resource?" detailedMessage: "Are you sure you want to delete #{message}?" buttons: Yes: => for item in selection @doRemove(item) No: null doRemove: (resource) => connection = @config.getConnection(null, @getActiveServer()) url = "#{connection.server}/rest/#{resource.path}" options = uri: url method: "DELETE" strictSSL: false auth: user: connection.user pass: PI:PASSWORD:<PASSWORD>END_PI.PI:PASSWORD:<PASSWORD>END_PI || "" sendImmediately: true @emit("status", "Deleting #{resource.path}...") request( options, (error, response, body) => if error? atom.notifications.addError("Failed to delete #{resource.path}", detail: if response? then response.statusMessage else error) else @emit("status", "") resource.view.delete() ) newFile: (item) => dialog.prompt("Enter a name for the new resource:").then((name) => @createFile(item, name) if name?) newCollection: (item) => parent = item.path dialog.prompt("Enter a name for the new collection:").then((name) => if name? query = "xmldb:create-collection('#{parent}', '#{name}')" @runQuery(query, (error, response) -> atom.notifications.addError("Failed to create collection #{parent}/#{name}", detail: if response? then response.statusMessage else error) (body) => atom.notifications.addSuccess("Collection #{parent}/#{name} created") collection = { path: "#{parent}/#{name}" label: name loaded: true type: "collection" icon: "icon-file-directory" } item.view.addChild(collection) collection.view.onSelect(@onSelect) collection.view.onDblClick(@onDblClick) collection.view.onDrop(@upload) ) ) createFile: (item, name) -> self = this collection = item.path resource = path: "#{collection}/#{name}" type: "resource" icon: "icon-file-text" label: name loaded: true tmpDir = @getTempDir(resource.path) tmpFile = path.join(tmpDir, path.basename(resource.path)) promise = atom.workspace.open(null) promise.then((newEditor) -> item.view.addChild(resource) resource.view.onSelect(self.onSelect) resource.view.onDblClick(self.onDblClick) buffer = newEditor.getBuffer() # buffer.getPath = () -> resource.path server = self.getActiveServer() connection = self.config.getConnection(null, server) buffer.getId = () -> self.getXMLDBUri(connection, resource.path) buffer.setPath(tmpFile) resource.editor = newEditor buffer._remote = resource onDidSave = buffer.onDidSave((ev) -> self.save(null, tmpFile, resource, mime.getType(resource.path)) ) onDidDestroy = buffer.onDidDestroy((ev) -> self.disposables.remove(onDidSave) self.disposables.remove(onDidDestroy) onDidDestroy.dispose() onDidSave.dispose() fs.unlink(tmpFile) ) self.disposables.add(onDidSave) self.disposables.add(onDidDestroy) ) open: (resource, server, onOpen) => # switch to existing editor if resource is already open editor = @getOpenEditor(resource) if editor? pane = atom.workspace.paneForItem(editor) pane.activateItem(editor) onOpen?(editor) return self = this server ?= @getActiveServer() connection = @config.getConnection(null, server) url = "#{connection.server}/apps/atom-editor/load.xql?path=#{resource.path}" tmpDir = @getTempDir(resource.path) tmpFile = path.join(tmpDir, path.basename(resource.path)) @emit("status", "Opening #{resource.path} ...") console.log("Downloading %s to %s", resource.path, tmpFile) stream = fs.createWriteStream(tmpFile) options = uri: url method: "GET" strictSSL: false auth: user: connection.user pass: connection.PI:PASSWORD:<PASSWORD>END_PI || "" sendImmediately: true contentType = null request(options) .on("response", (response) -> contentType = response.headers["content-type"] ) .on("error", (err) -> self.emit("status", "") atom.notifications.addError("Failed to download #{resource.path}", detail: err) ) .on("end", () -> self.emit("status", "") promise = atom.workspace.open(null) promise.then((newEditor) -> buffer = newEditor.getBuffer() # buffer.getPath = () -> resource.path buffer.setPath(tmpFile) buffer.getId = () => self.getXMLDBUri(connection, resource.path) buffer.loadSync() resource.editor = newEditor buffer._remote = resource onDidSave = buffer.onDidSave((ev) -> self.save(buffer, tmpFile, resource, contentType) ) onDidDestroy = buffer.onDidDestroy((ev) -> self.disposables.remove(onDidSave) self.disposables.remove(onDidDestroy) onDidDestroy.dispose() onDidSave.dispose() fs.unlink(tmpFile) ) self.disposables.add(onDidSave) self.disposables.add(onDidDestroy) if contentType == "application/xquery" XQUtils.xqlint(newEditor) onOpen?(newEditor) ) ) .pipe(stream) getXMLDBUri: (connection, path) -> return "exist://#{connection.name}#{path}" getOpenEditor: (resource) -> for editor in atom.workspace.getTextEditors() if editor.getBuffer()._remote?.path == resource.path return editor return null save: (buffer, file, resource, contentType) -> return new Promise((resolve, reject) => editor = atom.workspace.getActiveTextEditor() if buffer? connection = @config.getConnection(buffer.getId()) else connection = @config.getConnection(null, @getActiveServer()) url = "#{connection.server}/rest/#{resource.path}" contentType = mime.getType(path.extname(file)) unless contentType console.log("Saving %s to %s using content type %s", resource.path, connection.server, contentType) self = this options = uri: url method: "PUT" strictSSL: false auth: user: connection.user pass: PI:PASSWORD:<PASSWORD>END_PI || "" sendImmediately: true headers: "Content-Type": contentType fs.createReadStream(file).pipe( request( options, (error, response, body) -> if error? atom.notifications.addError("Failed to upload #{resource.path}", detail: if response? then response.statusMessage else error) reject() else resolve() ) ) ) uploadCurrent: () => selected = @treeView.getSelected() if selected.length != 1 or selected[0].item.type == "resource" atom.notifications.addError("Please select a single target collection for the upload in the database tree view") return editor = atom.workspace.getActiveTextEditor() fileName = path.basename(editor.getPath()) @emit("status", "Uploading file #{fileName}...") @save(null, editor.getPath(), path: "#{selected[0].item.path}/#{fileName}", null).then(() => @load(selected[0].item) @emit("status", "") ) uploadSelected: () -> locals = @fileTree.selectedPaths() if locals? and locals.length > 0 selected = @treeView.getSelected() if selected.length != 1 or selected[0].type == "resource" atom.notifications.addError("Please select a single target collection for the upload in the database tree view") return @upload(locals, selected[0]) upload: ({target, files}) => @emit("status", "Uploading #{files.length} files ...") deploy = files.every((file) -> file.endsWith(".xar")) if deploy atom.confirm message: "Install Packages?" detailedMessage: "Would you like to install the packages?" buttons: Yes: -> deploy = true No: -> deploy = false for file in files if (deploy) promise = @deploy(file) root = @treeView.getNode("/db/apps") else fileName = path.basename(file) promise = @save(null, file, path: "#{target.path}/#{fileName}", null) root = target promise.then(() => @load(root) @emit("status", "") ) deploy: (xar) => return new Promise((resolve, reject) => if xar? and typeof xar == "string" then paths = [ xar ] if not paths? paths = @fileTree.selectedPaths() if paths? and paths.length > 0 for file in paths fileName = path.basename(file) targetPath = "/db/system/repo/#{fileName}" @emit("status", "Uploading package ...") @save(null, file, path: targetPath, null).then(() => @emit("status", "Deploying package ...") query = """ xquery version "3.1"; declare namespace expath="http://expath.org/ns/pkg"; declare namespace output="http://www.w3.org/2010/xslt-xquery-serialization"; declare option output:method "json"; declare option output:media-type "application/json"; declare variable $repo := "http://demo.exist-db.org/exist/apps/public-repo/modules/find.xql"; declare function local:remove($package-url as xs:string) as xs:boolean { if ($package-url = repo:list()) then let $undeploy := repo:undeploy($package-url) let $remove := repo:remove($package-url) return $remove else false() }; let $xarPath := "#{targetPath}" let $meta := try { compression:unzip( util:binary-doc($xarPath), function($path as xs:anyURI, $type as xs:string, $param as item()*) as xs:boolean { $path = "expath-pkg.xml" }, (), function($path as xs:anyURI, $type as xs:string, $data as item()?, $param as item()*) { $data }, () ) } catch * { error(xs:QName("local:xar-unpack-error"), "Failed to unpack archive") } let $package := $meta//expath:package/string(@name) let $removed := local:remove($package) let $installed := repo:install-and-deploy-from-db($xarPath, $repo) return repo:get-root() """ @runQuery(query, (error, response) => atom.notifications.addError("Failed to deploy package", detail: if response? then response.body else error) @emit("status", "") reject() (body) => @emit("status", "") resolve() ) ) ) openInBrowser: (ev) => item = ev.target.item target = item.path.replace(/^.*?\/([^\/]+)$/, "$1") connection = @config.getConnection(null, @getActiveServer()) url = "#{connection.server}/apps/#{target}" process_architecture = process.platform switch process_architecture when 'darwin' then exec ('open "' + url + '"') when 'linux' then exec ('xdg-open "' + url + '"') when 'win32' then Shell.openExternal(url) reindex: (item) -> query = "xmldb:reindex('#{item.path}')" @emit("status", "Reindexing #{item.path}...") @runQuery(query, (error, response) -> atom.notifications.addError("Failed to reindex collection #{item.path}", detail: if response? then response.statusMessage else error) (body) => @emit("status", "") atom.notifications.addSuccess("Collection #{item.path} reindexed") ) sync: (item) => dialog.prompt("Path to sync to (server-side):").then( (path) => query = "file:sync('#{item.path}', '#{path}', ())" @emit("status", "Sync to directory...") @runQuery(query, (error, response) -> @emit("status", "") atom.notifications.addError("Failed to sync collection #{item.path}", detail: if response? then response.statusMessage else error) (body) => @emit("status", "") atom.notifications.addSuccess("Collection #{item.path} synched to directory #{path}") ) ) onSelect: ({node, item}) => if not item.loaded @load(item, () -> item.loaded = true item.view.toggleClass('collapsed') ) onDblClick: ({node, item}) => if item.type == "resource" @open(item) destroy: -> @element.remove() @disposables.dispose() @tempDir.removeCallback() if @tempDir remove: -> @destroy() getTempDir: (uri) -> @tempDir = tmp.dirSync({ mode: 0o750, prefix: 'atom-exist_', unsafeCleanup: true }) unless @tempDir tmpPath = path.join(fs.realpathSync(@tempDir.name), path.dirname(uri)) mkdirp.sync(tmpPath) return tmpPath runQuery: (query, onError, onSuccess) => editor = atom.workspace.getActiveTextEditor() connection = @config.getConnection(null, @getActiveServer()) url = "#{connection.server}/rest/db?_query=#{query}&_wrap=no" options = uri: url method: "GET" json: true strictSSL: false auth: user: connection.user pass: connection.password || "" sendImmediately: true request( options, (error, response, body) => if error? or response.statusCode != 200 onError?(error, response) else onSuccess?(body) ) checkServer: (onSuccess) => xar = @getXAR() query = """ xquery version "3.0"; declare namespace expath="http://expath.org/ns/pkg"; declare namespace output="http://www.w3.org/2010/xslt-xquery-serialization"; declare option output:method "json"; declare option output:media-type "application/json"; if ("http://exist-db.org/apps/atom-editor" = repo:list()) then let $data := repo:get-resource("http://exist-db.org/apps/atom-editor", "expath-pkg.xml") let $xml := parse-xml(util:binary-to-string($data)) return if ($xml/expath:package/@version = "#{xar.version}") then true() else $xml/expath:package/@version/string() else false() """ @runQuery(query, (error, response) -> atom.notifications.addWarning("Failed to access database", detail: if response? then response.statusMessage else error) (body) => if body == true onSuccess?() else if typeof body == "string" message = "Installed support app has version #{body}. A newer version (#{xar.version}) is recommended for proper operation. Do you want to install it?" else message = "This package requires a small support app to be installed on the eXistdb server. Do you want to install it?" atom.confirm message: "Install server-side support app?" detailedMessage: message buttons: Yes: => @deploy(xar.path).then(onSuccess) No: -> if typeof body == "string" then onSuccess?() else null ) getXAR: () => pkgDir = atom.packages.resolvePackagePath("existdb") if pkgDir? files = fs.readdirSync(path.join(pkgDir, "resources/db")) for file in files if file.endsWith(".xar") return { version: file.replace(/^.*-([\d\.]+)\.xar/, "$1"), path: path.join(pkgDir, "resources/db", file) }
[ { "context": "ammy names', ->\n\t\texpect(SpamSafe.isSafeUserName(\"Charline Wałęsa\")).to.equal true\n\t\texpect(SpamSafe.isSafeUserName", "end": 278, "score": 0.9998620748519897, "start": 263, "tag": "NAME", "value": "Charline Wałęsa" }, { "context": "')).to.equal false\n\t\texpect...
test/unit/coffee/Email/SpamSafeTests.coffee
shyoshyo/web-sharelatex
1
path = require('path') modulePath = path.join __dirname, "../../../../app/js/Features/Email/SpamSafe" SpamSafe = require(modulePath) expect = require("chai").expect describe "SpamSafe", -> it 'should reject spammy names', -> expect(SpamSafe.isSafeUserName("Charline Wałęsa")).to.equal true expect(SpamSafe.isSafeUserName("hey come buy this product im selling it's really good for you and it'll make your latex 10x guaranteed")).to.equal false expect(SpamSafe.isSafeUserName("隆太郎 宮本")).to.equal true expect(SpamSafe.isSafeUserName("Visit haxx0red.com")).to.equal false expect(SpamSafe.isSafeUserName('加美汝VX:hihi661,金沙2001005com the first deposit will be _100%_')).to.equal false expect(SpamSafe.isSafeProjectName('Neural Networks: good for your health and will solve all your problems')).to.equal false expect(SpamSafe.isSafeProjectName("An analysis of the questions of the universe!")).to.equal true expect(SpamSafe.isSafeProjectName("A'p'o's't'r'o'p'h'e gallore")).to.equal true expect(SpamSafe.isSafeProjectName('come buy this => http://www.dopeproduct.com/search/?q=user123')).to.equal false expect(SpamSafe.isSafeEmail("realistic-email+1@domain.sub-hyphen.com")).to.equal true expect(SpamSafe.isSafeEmail("notquiteRight\@evil$.com")).to.equal false expect(SpamSafe.safeUserName("Tammy Weinstįen", "A User")).to.equal "Tammy Weinstįen" expect(SpamSafe.safeUserName("haxx0red.com", "A User")).to.equal "A User" expect(SpamSafe.safeUserName("What$ Upp", "A User")).to.equal "A User" expect(SpamSafe.safeProjectName("Math-ematics!", "A Project")).to.equal "Math-ematics!" expect(SpamSafe.safeProjectName("A Very long title for a very long book that will never be read" + "a".repeat(250), "A Project")).to.equal "A Project" expect(SpamSafe.safeEmail("safe-ëmail@domain.com", "A collaborator")).to.equal "safe-ëmail@domain.com" expect(SpamSafe.safeEmail("Բարեւ@another.domain", "A collaborator")).to.equal "Բարեւ@another.domain" expect(SpamSafe.safeEmail("me+" + "a".repeat(40) + "@googoole.con", "A collaborator")).to.equal "A collaborator" expect(SpamSafe.safeEmail("sendME$$$@iAmAprince.com", "A collaborator")).to.equal "A collaborator"
134133
path = require('path') modulePath = path.join __dirname, "../../../../app/js/Features/Email/SpamSafe" SpamSafe = require(modulePath) expect = require("chai").expect describe "SpamSafe", -> it 'should reject spammy names', -> expect(SpamSafe.isSafeUserName("<NAME>")).to.equal true expect(SpamSafe.isSafeUserName("hey come buy this product im selling it's really good for you and it'll make your latex 10x guaranteed")).to.equal false expect(SpamSafe.isSafeUserName("隆太郎 宮本")).to.equal true expect(SpamSafe.isSafeUserName("Visit haxx0red.com")).to.equal false expect(SpamSafe.isSafeUserName('加美汝VX:hihi661,金沙2001005com the first deposit will be _100%_')).to.equal false expect(SpamSafe.isSafeProjectName('Neural Networks: good for your health and will solve all your problems')).to.equal false expect(SpamSafe.isSafeProjectName("An analysis of the questions of the universe!")).to.equal true expect(SpamSafe.isSafeProjectName("A'p'o's't'r'o'p'h'e gallore")).to.equal true expect(SpamSafe.isSafeProjectName('come buy this => http://www.dopeproduct.com/search/?q=user123')).to.equal false expect(SpamSafe.isSafeEmail("<EMAIL>")).to.equal true expect(SpamSafe.isSafeEmail("not<EMAIL>")).to.equal false expect(SpamSafe.safeUserName("Tammy Weinst<NAME>en", "A User")).to.equal "<NAME>" expect(SpamSafe.safeUserName("haxx0red.com", "A User")).to.equal "A User" expect(SpamSafe.safeUserName("What$ Upp", "A User")).to.equal "A User" expect(SpamSafe.safeProjectName("Math-ematics!", "A Project")).to.equal "Math-ematics!" expect(SpamSafe.safeProjectName("A Very long title for a very long book that will never be read" + "a".repeat(250), "A Project")).to.equal "A Project" expect(SpamSafe.safeEmail("<EMAIL>", "A collaborator")).to.equal "<EMAIL>" expect(SpamSafe.safeEmail("<EMAIL>", "A collaborator")).to.equal "<EMAIL>" expect(SpamSafe.safeEmail("me+" + "a".repeat(40) + "@googoole.con", "A collaborator")).to.equal "A collaborator" expect(SpamSafe.safeEmail("<EMAIL>ME<EMAIL>", "A collaborator")).to.equal "A collaborator"
true
path = require('path') modulePath = path.join __dirname, "../../../../app/js/Features/Email/SpamSafe" SpamSafe = require(modulePath) expect = require("chai").expect describe "SpamSafe", -> it 'should reject spammy names', -> expect(SpamSafe.isSafeUserName("PI:NAME:<NAME>END_PI")).to.equal true expect(SpamSafe.isSafeUserName("hey come buy this product im selling it's really good for you and it'll make your latex 10x guaranteed")).to.equal false expect(SpamSafe.isSafeUserName("隆太郎 宮本")).to.equal true expect(SpamSafe.isSafeUserName("Visit haxx0red.com")).to.equal false expect(SpamSafe.isSafeUserName('加美汝VX:hihi661,金沙2001005com the first deposit will be _100%_')).to.equal false expect(SpamSafe.isSafeProjectName('Neural Networks: good for your health and will solve all your problems')).to.equal false expect(SpamSafe.isSafeProjectName("An analysis of the questions of the universe!")).to.equal true expect(SpamSafe.isSafeProjectName("A'p'o's't'r'o'p'h'e gallore")).to.equal true expect(SpamSafe.isSafeProjectName('come buy this => http://www.dopeproduct.com/search/?q=user123')).to.equal false expect(SpamSafe.isSafeEmail("PI:EMAIL:<EMAIL>END_PI")).to.equal true expect(SpamSafe.isSafeEmail("notPI:EMAIL:<EMAIL>END_PI")).to.equal false expect(SpamSafe.safeUserName("Tammy WeinstPI:NAME:<NAME>END_PIen", "A User")).to.equal "PI:NAME:<NAME>END_PI" expect(SpamSafe.safeUserName("haxx0red.com", "A User")).to.equal "A User" expect(SpamSafe.safeUserName("What$ Upp", "A User")).to.equal "A User" expect(SpamSafe.safeProjectName("Math-ematics!", "A Project")).to.equal "Math-ematics!" expect(SpamSafe.safeProjectName("A Very long title for a very long book that will never be read" + "a".repeat(250), "A Project")).to.equal "A Project" expect(SpamSafe.safeEmail("PI:EMAIL:<EMAIL>END_PI", "A collaborator")).to.equal "PI:EMAIL:<EMAIL>END_PI" expect(SpamSafe.safeEmail("PI:EMAIL:<EMAIL>END_PI", "A collaborator")).to.equal "PI:EMAIL:<EMAIL>END_PI" expect(SpamSafe.safeEmail("me+" + "a".repeat(40) + "@googoole.con", "A collaborator")).to.equal "A collaborator" expect(SpamSafe.safeEmail("PI:EMAIL:<EMAIL>END_PIMEPI:EMAIL:<EMAIL>END_PI", "A collaborator")).to.equal "A collaborator"
[ { "context": "ate().getTime()\n total = 100000\n #testUsers = ['livelily+test31@gmail.com', 'livelily+test37@gmail.com']\n if testUsers?\n ", "end": 945, "score": 0.9998376965522766, "start": 920, "tag": "EMAIL", "value": "livelily+test31@gmail.com" }, { "context": "000\n #testU...
scripts/recreateEarnedAchievements.coffee
JurianLock/codecombat
1
database = require '../server/commons/database' mongoose = require 'mongoose' log = require 'winston' async = require 'async' ### SET UP ### do (setupLodash = this) -> GLOBAL._ = require 'lodash' _.str = require 'underscore.string' _.mixin _.str.exports() GLOBAL.tv4 = require('tv4').tv4 database.connect() LocalMongo = require '../app/lib/LocalMongo' User = require '../server/users/User' EarnedAchievement = require '../server/achievements/EarnedAchievement' Achievement = require '../server/achievements/Achievement' Achievement.loadAchievements (achievementCategories) -> # Really, it's just the 'users' category, since we don't keep all the LevelSession achievements in memory, rather letting the clients make those. userAchievements = achievementCategories.users console.log 'There are', userAchievements.length, 'user achievements.' t0 = new Date().getTime() total = 100000 #testUsers = ['livelily+test31@gmail.com', 'livelily+test37@gmail.com'] if testUsers? userQuery = emailLower: {$in: testUsers} else userQuery = anonymous: false User.count userQuery, (err, count) -> total = count onFinished = -> t1 = new Date().getTime() runningTime = ((t1-t0)/1000/60/60).toFixed(2) console.log "we finished in #{runningTime} hours" process.exit() # Fetch every single user. This tends to get big so do it in a streaming fashion. userStream = User.find(userQuery).sort('_id').stream() streamFinished = false usersTotal = 0 usersFinished = 0 totalAchievementsExisting = 0 totalAchievementsCreated = 0 numberRunning = 0 doneWithUser = -> ++usersFinished numberRunning -= 1 userStream.resume() onFinished?() if streamFinished and usersFinished is usersTotal userStream.on 'error', (err) -> log.error err userStream.on 'close', -> streamFinished = true userStream.on 'data', (user) -> ++usersTotal numberRunning += 1 userStream.pause() if numberRunning > 20 userID = user.get('_id').toHexString() userObject = user.toObject() # Fetch all of a user's earned achievements EarnedAchievement.find {user: userID}, (err, alreadyEarnedAchievements) -> log.error err if err achievementsExisting = 0 achievementsCreated = 0 for achievement in userAchievements #console.log "Testing", achievement.get('name'), achievement.get('_id') if testUsers? shouldBeAchieved = LocalMongo.matchesQuery userObject, achievement.get('query') continue unless shouldBeAchieved # Could delete existing ones that shouldn't be achieved if we wanted. earnedAchievement = _.find(alreadyEarnedAchievements, (ea) -> ea.get('user') is userID and ea.get('achievement') is achievement.get('_id').toHexString()) if earnedAchievement #console.log "... already earned #{achievement.get('name')} #{achievement.get('_id')} for user: #{user.get('name')} #{user.get('_id')}" if testUsers? ++achievementsExisting continue #console.log "Making an achievement: #{achievement.get('name')} #{achievement.get('_id')} for user: #{user.get('name')} #{user.get('_id')}" if testUsers? ++achievementsCreated EarnedAchievement.createForAchievement achievement, user totalAchievementsExisting += achievementsExisting totalAchievementsCreated += achievementsCreated pctDone = (100 * usersFinished / total).toFixed(2) console.log "Created #{achievementsCreated}, existing #{achievementsExisting} EarnedAchievements for #{user.get('name') or '???'} (#{user.get('_id')}) (#{pctDone}%, totals #{totalAchievementsExisting} existing, #{totalAchievementsCreated} created)" doneWithUser()
200686
database = require '../server/commons/database' mongoose = require 'mongoose' log = require 'winston' async = require 'async' ### SET UP ### do (setupLodash = this) -> GLOBAL._ = require 'lodash' _.str = require 'underscore.string' _.mixin _.str.exports() GLOBAL.tv4 = require('tv4').tv4 database.connect() LocalMongo = require '../app/lib/LocalMongo' User = require '../server/users/User' EarnedAchievement = require '../server/achievements/EarnedAchievement' Achievement = require '../server/achievements/Achievement' Achievement.loadAchievements (achievementCategories) -> # Really, it's just the 'users' category, since we don't keep all the LevelSession achievements in memory, rather letting the clients make those. userAchievements = achievementCategories.users console.log 'There are', userAchievements.length, 'user achievements.' t0 = new Date().getTime() total = 100000 #testUsers = ['<EMAIL>', '<EMAIL>'] if testUsers? userQuery = emailLower: {$in: testUsers} else userQuery = anonymous: false User.count userQuery, (err, count) -> total = count onFinished = -> t1 = new Date().getTime() runningTime = ((t1-t0)/1000/60/60).toFixed(2) console.log "we finished in #{runningTime} hours" process.exit() # Fetch every single user. This tends to get big so do it in a streaming fashion. userStream = User.find(userQuery).sort('_id').stream() streamFinished = false usersTotal = 0 usersFinished = 0 totalAchievementsExisting = 0 totalAchievementsCreated = 0 numberRunning = 0 doneWithUser = -> ++usersFinished numberRunning -= 1 userStream.resume() onFinished?() if streamFinished and usersFinished is usersTotal userStream.on 'error', (err) -> log.error err userStream.on 'close', -> streamFinished = true userStream.on 'data', (user) -> ++usersTotal numberRunning += 1 userStream.pause() if numberRunning > 20 userID = user.get('_id').toHexString() userObject = user.toObject() # Fetch all of a user's earned achievements EarnedAchievement.find {user: userID}, (err, alreadyEarnedAchievements) -> log.error err if err achievementsExisting = 0 achievementsCreated = 0 for achievement in userAchievements #console.log "Testing", achievement.get('name'), achievement.get('_id') if testUsers? shouldBeAchieved = LocalMongo.matchesQuery userObject, achievement.get('query') continue unless shouldBeAchieved # Could delete existing ones that shouldn't be achieved if we wanted. earnedAchievement = _.find(alreadyEarnedAchievements, (ea) -> ea.get('user') is userID and ea.get('achievement') is achievement.get('_id').toHexString()) if earnedAchievement #console.log "... already earned #{achievement.get('name')} #{achievement.get('_id')} for user: #{user.get('name')} #{user.get('_id')}" if testUsers? ++achievementsExisting continue #console.log "Making an achievement: #{achievement.get('name')} #{achievement.get('_id')} for user: #{user.get('name')} #{user.get('_id')}" if testUsers? ++achievementsCreated EarnedAchievement.createForAchievement achievement, user totalAchievementsExisting += achievementsExisting totalAchievementsCreated += achievementsCreated pctDone = (100 * usersFinished / total).toFixed(2) console.log "Created #{achievementsCreated}, existing #{achievementsExisting} EarnedAchievements for #{user.get('name') or '???'} (#{user.get('_id')}) (#{pctDone}%, totals #{totalAchievementsExisting} existing, #{totalAchievementsCreated} created)" doneWithUser()
true
database = require '../server/commons/database' mongoose = require 'mongoose' log = require 'winston' async = require 'async' ### SET UP ### do (setupLodash = this) -> GLOBAL._ = require 'lodash' _.str = require 'underscore.string' _.mixin _.str.exports() GLOBAL.tv4 = require('tv4').tv4 database.connect() LocalMongo = require '../app/lib/LocalMongo' User = require '../server/users/User' EarnedAchievement = require '../server/achievements/EarnedAchievement' Achievement = require '../server/achievements/Achievement' Achievement.loadAchievements (achievementCategories) -> # Really, it's just the 'users' category, since we don't keep all the LevelSession achievements in memory, rather letting the clients make those. userAchievements = achievementCategories.users console.log 'There are', userAchievements.length, 'user achievements.' t0 = new Date().getTime() total = 100000 #testUsers = ['PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI'] if testUsers? userQuery = emailLower: {$in: testUsers} else userQuery = anonymous: false User.count userQuery, (err, count) -> total = count onFinished = -> t1 = new Date().getTime() runningTime = ((t1-t0)/1000/60/60).toFixed(2) console.log "we finished in #{runningTime} hours" process.exit() # Fetch every single user. This tends to get big so do it in a streaming fashion. userStream = User.find(userQuery).sort('_id').stream() streamFinished = false usersTotal = 0 usersFinished = 0 totalAchievementsExisting = 0 totalAchievementsCreated = 0 numberRunning = 0 doneWithUser = -> ++usersFinished numberRunning -= 1 userStream.resume() onFinished?() if streamFinished and usersFinished is usersTotal userStream.on 'error', (err) -> log.error err userStream.on 'close', -> streamFinished = true userStream.on 'data', (user) -> ++usersTotal numberRunning += 1 userStream.pause() if numberRunning > 20 userID = user.get('_id').toHexString() userObject = user.toObject() # Fetch all of a user's earned achievements EarnedAchievement.find {user: userID}, (err, alreadyEarnedAchievements) -> log.error err if err achievementsExisting = 0 achievementsCreated = 0 for achievement in userAchievements #console.log "Testing", achievement.get('name'), achievement.get('_id') if testUsers? shouldBeAchieved = LocalMongo.matchesQuery userObject, achievement.get('query') continue unless shouldBeAchieved # Could delete existing ones that shouldn't be achieved if we wanted. earnedAchievement = _.find(alreadyEarnedAchievements, (ea) -> ea.get('user') is userID and ea.get('achievement') is achievement.get('_id').toHexString()) if earnedAchievement #console.log "... already earned #{achievement.get('name')} #{achievement.get('_id')} for user: #{user.get('name')} #{user.get('_id')}" if testUsers? ++achievementsExisting continue #console.log "Making an achievement: #{achievement.get('name')} #{achievement.get('_id')} for user: #{user.get('name')} #{user.get('_id')}" if testUsers? ++achievementsCreated EarnedAchievement.createForAchievement achievement, user totalAchievementsExisting += achievementsExisting totalAchievementsCreated += achievementsCreated pctDone = (100 * usersFinished / total).toFixed(2) console.log "Created #{achievementsCreated}, existing #{achievementsExisting} EarnedAchievements for #{user.get('name') or '???'} (#{user.get('_id')}) (#{pctDone}%, totals #{totalAchievementsExisting} existing, #{totalAchievementsCreated} created)" doneWithUser()
[ { "context": " \n test 'create', ->\n User.create firstName: \"Lance\", (error, user) ->\n expect(user instanceof U", "end": 227, "score": 0.9996049404144287, "start": 222, "tag": "NAME", "value": "Lance" }, { "context": "hy()\n expect(user.get(\"firstName\")).toEqual \...
test/cases/store/memoryTest.coffee
hussainmuzzamil/tower
1
### require '../../config' require '../storeSpec' describe 'Tower.Store.Memory', -> beforeEach -> User.store new Tower.Store.Memory(name: "users", type: "User") test 'create', -> User.create firstName: "Lance", (error, user) -> expect(user instanceof User).toBeTruthy() expect(user.get("firstName")).toEqual "Lance" describe 'finders', -> beforeEach -> User.create firstName: "Lance", lastName: "Pollard", id: 1 User.create firstName: "Dane", lastName: "Pollard", id: 2 User.create firstName: "John", lastName: "Smith", id: 3 test 'all', -> User.all (error, users) -> expect(users.length).toEqual 3 test 'count', -> User.count (error, count) -> expect(count).toEqual 3 #test 'find(1)', -> # User.find 1, (error, user) -> # expect(user instanceof User).toBeTruthy() test 'find(1, 2)', -> User.find 1, 2, (error, users) -> for user in users expect(user instanceof User).toBeTruthy() test 'find([1, 2])', -> User.find [1, 2], (error, users) -> for user in users expect(user instanceof User).toBeTruthy() test 'where(firstName: "Lance").find(1, 2)', -> User.where(firstName: "Lance").find 1, 2, (error, users) -> expect(users.length).toEqual 1 for user in users expect(user instanceof User).toBeTruthy() test 'where(firstName: /L/)', -> User.where(firstName: /L/).all (error, records) -> for record in records expect(record.firstName).toMatch /L/ test 'where(firstName: "=~": "L")', -> User.where(firstName: "=~": "L").all (error, records) -> for record in records expect(record.firstName).toMatch /L/ test 'where(firstName: "$match": "L")', -> User.where(firstName: "$match": "L").all (error, records) -> for record in records expect(record.firstName).toMatch /L/ test 'where(firstName: "!~": "L")' test 'where(firstName: "!=": "Lance")' test 'where(firstName: "!=": null)' test 'where(firstName: "==": null)' test 'where(firstName: null)' test 'where(createdAt: ">=": _(2).days().ago())' test 'where(createdAt: ">=": _(2).days().ago(), "<=": _(1).day().ago())' test 'where(tags: $in: ["ruby", "javascript"])' test 'where(tags: $nin: ["java", "asp"])' test 'where(tags: $all: ["jquery", "node"])' test 'where(likeCount: 10)' test 'where(likeCount: ">=": 10)' test 'asc("firstName")' test 'desc("firstName")' test 'order(["firstName", "desc"])' test 'limit(10)' test 'paginate(perPage: 20, page: 2)' test 'page(2)' describe 'update', -> test 'update(name: "Tom")', -> User.update name: "Tom", (error) -> console.log "UPDATE" test 'update(1, 2, name: "Tom")', -> User.update name: "Tom", (error) -> test 'where(name: "John").update(name: "Tom")', -> User.where(name: "John").update name: "Tom", (error) -> describe 'destroy', -> test 'where(name: "John").destroy()', -> User.where(name: "John").destroy (error) -> ###
135577
### require '../../config' require '../storeSpec' describe 'Tower.Store.Memory', -> beforeEach -> User.store new Tower.Store.Memory(name: "users", type: "User") test 'create', -> User.create firstName: "<NAME>", (error, user) -> expect(user instanceof User).toBeTruthy() expect(user.get("firstName")).toEqual "<NAME>" describe 'finders', -> beforeEach -> User.create firstName: "<NAME>", lastName: "<NAME>", id: 1 User.create firstName: "<NAME>", lastName: "<NAME>", id: 2 User.create firstName: "<NAME>", lastName: "<NAME>", id: 3 test 'all', -> User.all (error, users) -> expect(users.length).toEqual 3 test 'count', -> User.count (error, count) -> expect(count).toEqual 3 #test 'find(1)', -> # User.find 1, (error, user) -> # expect(user instanceof User).toBeTruthy() test 'find(1, 2)', -> User.find 1, 2, (error, users) -> for user in users expect(user instanceof User).toBeTruthy() test 'find([1, 2])', -> User.find [1, 2], (error, users) -> for user in users expect(user instanceof User).toBeTruthy() test 'where(firstName: "<NAME>").find(1, 2)', -> User.where(firstName: "<NAME>").find 1, 2, (error, users) -> expect(users.length).toEqual 1 for user in users expect(user instanceof User).toBeTruthy() test 'where(firstName: /L/)', -> User.where(firstName: /L/).all (error, records) -> for record in records expect(record.firstName).toMatch /L/ test 'where(firstName: "=~": "L")', -> User.where(firstName: "=~": "L").all (error, records) -> for record in records expect(record.firstName).toMatch /L/ test 'where(firstName: "$match": "L")', -> User.where(firstName: "$match": "L").all (error, records) -> for record in records expect(record.firstName).toMatch /L/ test 'where(firstName: "!~": "L")' test 'where(firstName: "!=": "<NAME>")' test 'where(firstName: "!=": null)' test 'where(firstName: "==": null)' test 'where(firstName: null)' test 'where(createdAt: ">=": _(2).days().ago())' test 'where(createdAt: ">=": _(2).days().ago(), "<=": _(1).day().ago())' test 'where(tags: $in: ["ruby", "javascript"])' test 'where(tags: $nin: ["java", "asp"])' test 'where(tags: $all: ["jquery", "node"])' test 'where(likeCount: 10)' test 'where(likeCount: ">=": 10)' test 'asc("firstName")' test 'desc("firstName")' test 'order(["firstName", "desc"])' test 'limit(10)' test 'paginate(perPage: 20, page: 2)' test 'page(2)' describe 'update', -> test 'update(name: "<NAME>")', -> User.update name: "<NAME>", (error) -> console.log "UPDATE" test 'update(1, 2, name: "<NAME>")', -> User.update name: "<NAME>", (error) -> test 'where(name: "<NAME>").update(name: "<NAME>")', -> User.where(name: "<NAME>").update name: "<NAME>", (error) -> describe 'destroy', -> test 'where(name: "<NAME>").destroy()', -> User.where(name: "<NAME>").destroy (error) -> ###
true
### require '../../config' require '../storeSpec' describe 'Tower.Store.Memory', -> beforeEach -> User.store new Tower.Store.Memory(name: "users", type: "User") test 'create', -> User.create firstName: "PI:NAME:<NAME>END_PI", (error, user) -> expect(user instanceof User).toBeTruthy() expect(user.get("firstName")).toEqual "PI:NAME:<NAME>END_PI" describe 'finders', -> beforeEach -> User.create firstName: "PI:NAME:<NAME>END_PI", lastName: "PI:NAME:<NAME>END_PI", id: 1 User.create firstName: "PI:NAME:<NAME>END_PI", lastName: "PI:NAME:<NAME>END_PI", id: 2 User.create firstName: "PI:NAME:<NAME>END_PI", lastName: "PI:NAME:<NAME>END_PI", id: 3 test 'all', -> User.all (error, users) -> expect(users.length).toEqual 3 test 'count', -> User.count (error, count) -> expect(count).toEqual 3 #test 'find(1)', -> # User.find 1, (error, user) -> # expect(user instanceof User).toBeTruthy() test 'find(1, 2)', -> User.find 1, 2, (error, users) -> for user in users expect(user instanceof User).toBeTruthy() test 'find([1, 2])', -> User.find [1, 2], (error, users) -> for user in users expect(user instanceof User).toBeTruthy() test 'where(firstName: "PI:NAME:<NAME>END_PI").find(1, 2)', -> User.where(firstName: "PI:NAME:<NAME>END_PI").find 1, 2, (error, users) -> expect(users.length).toEqual 1 for user in users expect(user instanceof User).toBeTruthy() test 'where(firstName: /L/)', -> User.where(firstName: /L/).all (error, records) -> for record in records expect(record.firstName).toMatch /L/ test 'where(firstName: "=~": "L")', -> User.where(firstName: "=~": "L").all (error, records) -> for record in records expect(record.firstName).toMatch /L/ test 'where(firstName: "$match": "L")', -> User.where(firstName: "$match": "L").all (error, records) -> for record in records expect(record.firstName).toMatch /L/ test 'where(firstName: "!~": "L")' test 'where(firstName: "!=": "PI:NAME:<NAME>END_PI")' test 'where(firstName: "!=": null)' test 'where(firstName: "==": null)' test 'where(firstName: null)' test 'where(createdAt: ">=": _(2).days().ago())' test 'where(createdAt: ">=": _(2).days().ago(), "<=": _(1).day().ago())' test 'where(tags: $in: ["ruby", "javascript"])' test 'where(tags: $nin: ["java", "asp"])' test 'where(tags: $all: ["jquery", "node"])' test 'where(likeCount: 10)' test 'where(likeCount: ">=": 10)' test 'asc("firstName")' test 'desc("firstName")' test 'order(["firstName", "desc"])' test 'limit(10)' test 'paginate(perPage: 20, page: 2)' test 'page(2)' describe 'update', -> test 'update(name: "PI:NAME:<NAME>END_PI")', -> User.update name: "PI:NAME:<NAME>END_PI", (error) -> console.log "UPDATE" test 'update(1, 2, name: "PI:NAME:<NAME>END_PI")', -> User.update name: "PI:NAME:<NAME>END_PI", (error) -> test 'where(name: "PI:NAME:<NAME>END_PI").update(name: "PI:NAME:<NAME>END_PI")', -> User.where(name: "PI:NAME:<NAME>END_PI").update name: "PI:NAME:<NAME>END_PI", (error) -> describe 'destroy', -> test 'where(name: "PI:NAME:<NAME>END_PI").destroy()', -> User.where(name: "PI:NAME:<NAME>END_PI").destroy (error) -> ###
[ { "context": "e Wonderful Wizard of Oz',\n author: 'L. Frank Baum'}, new Assets('test/files', 'assets/'))\n ", "end": 1277, "score": 0.9998218417167664, "start": 1264, "tag": "NAME", "value": "L. Frank Baum" }, { "context": "e Wonderful Wizard of Oz',\n ...
scripts/test/chapter.coffee
baldurbjarnason/bookmaker
1
'use strict' chai = require 'chai' should = chai.should() index = require '../src/index' Chapter = index.Chapter Book = index.Book Assets = index.Assets testbook = {} testchapters = { 'md': { type: 'md', title: 'Markdown', body: '# header\n\nTest' }, 'html': { type: 'html', title: 'HTML', arbitraryMeta: 'is arbitrary' body: '<h1>header</h1><p>Test<br>&lsquo;&mdash;&rsquo;&ldquo;&ndash;&rdquo;&nbsp;</p>' }, 'xhtml': { type: 'xhtml', title: 'XHTML', body: '<h1>header</h1><p>Test<br/></p>' }, 'hbs': { type: 'hbs', title: 'Template', body: '<h1>{{title}}</h1><p>Test<br>&lsquo;&mdash;&rsquo;&ldquo;&ndash;&rdquo;&nbsp;</p>' } } describe 'Chapter', () -> describe '#constructor', () -> it 'should contain all of the properties of the passed object', () -> testchapter = new Chapter(testchapters.html) testchapter.title.should.equal('HTML') testchapter.arbitraryMeta.should.equal('is arbitrary') describe '#context', () -> it 'should contain all of the context needed for templates', () -> testbook = new Book({ title: 'The Wonderful Wizard of Oz', author: 'L. Frank Baum'}, new Assets('test/files', 'assets/')) testbook.addChapter(new Chapter(testchapters.html)) testbook.chapters.should.be.instanceOf(Array) testbook.chapters[0].title.should.equal('HTML') testbook.chapters[0].arbitraryMeta.should.equal('is arbitrary') testbook.chapters[0].should.be.instanceOf(Chapter) context = testbook.chapters[0].context() context.should.have.property('meta', testbook.meta) context.should.have.property('chapters', testbook.chapters) context.should.have.property('assets', testbook.assets) context.should.have.property('title', 'HTML') context.should.have.property('arbitraryMeta', 'is arbitrary') describe '#html (html)', () -> it 'should correctly render xhtml body content', () -> testchapter = new Chapter(testchapters.html) testchapter.title.should.equal('HTML') testchapter.arbitraryMeta.should.equal('is arbitrary') testchapter.should.be.instanceOf(Chapter) testchapter.html.should.equal('<h1 id="h1-1">header</h1><p class="noindent" id="p-1">Test<br />‘—’“–”&#160;</p>') describe '#html (md)', () -> it 'should correctly render xhtml body content', () -> testchapter = new Chapter(testchapters.md) testchapter.title.should.equal('Markdown') testchapter.should.be.instanceOf(Chapter) testchapter.html.should.equal('<h1 id="header">header</h1>\n<p class="noindent" id="p-1">Test</p>\n') describe '#html (hbs)', () -> it 'should correctly render xhtml body content', () -> testbook = new Book({ title: 'The Wonderful Wizard of Oz', author: 'L. Frank Baum'}) testbook.addChapter(new Chapter(testchapters.hbs)) testbook.chapters[0].should.be.instanceOf(Chapter) testbook.chapters[0].title.should.equal('Template') testbook.chapters[0].should.be.instanceOf(Chapter) testbook.chapters[0].html.should.equal('<h1 id="h1-1">Template</h1><p class="noindent" id="p-1">Test<br />‘—’“–”&#160;</p>') describe '#html (xhtml)', () -> it 'should correctly render xhtml body content', () -> testchapter = new Chapter(testchapters.xhtml) testchapter.title.should.equal('XHTML') testchapter.should.be.instanceOf(Chapter) testchapter.html.should.equal('<h1>header</h1><p>Test<br/></p>') describe '#toJSON', () -> it 'should correctly give you a safe json file', () -> testbook = new Book({ title: 'The Wonderful Wizard of Oz', author: 'L. Frank Baum'}) testbook.addChapter(new Chapter(testchapters.hbs)) jsontest = testbook.chapters[0].toJSON() jsontest.should.equal("{\n \"type\": \"html\",\n \"title\": \"Template\",\n \"body\": \"<h1 id=\\\"h1-1\\\">Template</h1><p class=\\\"noindent\\\" id=\\\"p-1\\\">Test<br />‘—’“–”&#160;</p>\",\n \"id\": \"doc1\",\n \"_links\": {\n \"toc\": {\n \"href\": \"../index.json\",\n \"name\": \"TOC-JSON\",\n \"type\": \"application/hal+json\"\n },\n \"self\": {\n \"href\": \"doc1.json\",\n \"type\": \"application/hal+json\"\n }\n }\n}")
17975
'use strict' chai = require 'chai' should = chai.should() index = require '../src/index' Chapter = index.Chapter Book = index.Book Assets = index.Assets testbook = {} testchapters = { 'md': { type: 'md', title: 'Markdown', body: '# header\n\nTest' }, 'html': { type: 'html', title: 'HTML', arbitraryMeta: 'is arbitrary' body: '<h1>header</h1><p>Test<br>&lsquo;&mdash;&rsquo;&ldquo;&ndash;&rdquo;&nbsp;</p>' }, 'xhtml': { type: 'xhtml', title: 'XHTML', body: '<h1>header</h1><p>Test<br/></p>' }, 'hbs': { type: 'hbs', title: 'Template', body: '<h1>{{title}}</h1><p>Test<br>&lsquo;&mdash;&rsquo;&ldquo;&ndash;&rdquo;&nbsp;</p>' } } describe 'Chapter', () -> describe '#constructor', () -> it 'should contain all of the properties of the passed object', () -> testchapter = new Chapter(testchapters.html) testchapter.title.should.equal('HTML') testchapter.arbitraryMeta.should.equal('is arbitrary') describe '#context', () -> it 'should contain all of the context needed for templates', () -> testbook = new Book({ title: 'The Wonderful Wizard of Oz', author: '<NAME>'}, new Assets('test/files', 'assets/')) testbook.addChapter(new Chapter(testchapters.html)) testbook.chapters.should.be.instanceOf(Array) testbook.chapters[0].title.should.equal('HTML') testbook.chapters[0].arbitraryMeta.should.equal('is arbitrary') testbook.chapters[0].should.be.instanceOf(Chapter) context = testbook.chapters[0].context() context.should.have.property('meta', testbook.meta) context.should.have.property('chapters', testbook.chapters) context.should.have.property('assets', testbook.assets) context.should.have.property('title', 'HTML') context.should.have.property('arbitraryMeta', 'is arbitrary') describe '#html (html)', () -> it 'should correctly render xhtml body content', () -> testchapter = new Chapter(testchapters.html) testchapter.title.should.equal('HTML') testchapter.arbitraryMeta.should.equal('is arbitrary') testchapter.should.be.instanceOf(Chapter) testchapter.html.should.equal('<h1 id="h1-1">header</h1><p class="noindent" id="p-1">Test<br />‘—’“–”&#160;</p>') describe '#html (md)', () -> it 'should correctly render xhtml body content', () -> testchapter = new Chapter(testchapters.md) testchapter.title.should.equal('Markdown') testchapter.should.be.instanceOf(Chapter) testchapter.html.should.equal('<h1 id="header">header</h1>\n<p class="noindent" id="p-1">Test</p>\n') describe '#html (hbs)', () -> it 'should correctly render xhtml body content', () -> testbook = new Book({ title: 'The Wonderful Wizard of Oz', author: '<NAME>'}) testbook.addChapter(new Chapter(testchapters.hbs)) testbook.chapters[0].should.be.instanceOf(Chapter) testbook.chapters[0].title.should.equal('Template') testbook.chapters[0].should.be.instanceOf(Chapter) testbook.chapters[0].html.should.equal('<h1 id="h1-1">Template</h1><p class="noindent" id="p-1">Test<br />‘—’“–”&#160;</p>') describe '#html (xhtml)', () -> it 'should correctly render xhtml body content', () -> testchapter = new Chapter(testchapters.xhtml) testchapter.title.should.equal('XHTML') testchapter.should.be.instanceOf(Chapter) testchapter.html.should.equal('<h1>header</h1><p>Test<br/></p>') describe '#toJSON', () -> it 'should correctly give you a safe json file', () -> testbook = new Book({ title: 'The Wonderful Wizard of Oz', author: '<NAME>'}) testbook.addChapter(new Chapter(testchapters.hbs)) jsontest = testbook.chapters[0].toJSON() jsontest.should.equal("{\n \"type\": \"html\",\n \"title\": \"Template\",\n \"body\": \"<h1 id=\\\"h1-1\\\">Template</h1><p class=\\\"noindent\\\" id=\\\"p-1\\\">Test<br />‘—’“–”&#160;</p>\",\n \"id\": \"doc1\",\n \"_links\": {\n \"toc\": {\n \"href\": \"../index.json\",\n \"name\": \"TOC-JSON\",\n \"type\": \"application/hal+json\"\n },\n \"self\": {\n \"href\": \"doc1.json\",\n \"type\": \"application/hal+json\"\n }\n }\n}")
true
'use strict' chai = require 'chai' should = chai.should() index = require '../src/index' Chapter = index.Chapter Book = index.Book Assets = index.Assets testbook = {} testchapters = { 'md': { type: 'md', title: 'Markdown', body: '# header\n\nTest' }, 'html': { type: 'html', title: 'HTML', arbitraryMeta: 'is arbitrary' body: '<h1>header</h1><p>Test<br>&lsquo;&mdash;&rsquo;&ldquo;&ndash;&rdquo;&nbsp;</p>' }, 'xhtml': { type: 'xhtml', title: 'XHTML', body: '<h1>header</h1><p>Test<br/></p>' }, 'hbs': { type: 'hbs', title: 'Template', body: '<h1>{{title}}</h1><p>Test<br>&lsquo;&mdash;&rsquo;&ldquo;&ndash;&rdquo;&nbsp;</p>' } } describe 'Chapter', () -> describe '#constructor', () -> it 'should contain all of the properties of the passed object', () -> testchapter = new Chapter(testchapters.html) testchapter.title.should.equal('HTML') testchapter.arbitraryMeta.should.equal('is arbitrary') describe '#context', () -> it 'should contain all of the context needed for templates', () -> testbook = new Book({ title: 'The Wonderful Wizard of Oz', author: 'PI:NAME:<NAME>END_PI'}, new Assets('test/files', 'assets/')) testbook.addChapter(new Chapter(testchapters.html)) testbook.chapters.should.be.instanceOf(Array) testbook.chapters[0].title.should.equal('HTML') testbook.chapters[0].arbitraryMeta.should.equal('is arbitrary') testbook.chapters[0].should.be.instanceOf(Chapter) context = testbook.chapters[0].context() context.should.have.property('meta', testbook.meta) context.should.have.property('chapters', testbook.chapters) context.should.have.property('assets', testbook.assets) context.should.have.property('title', 'HTML') context.should.have.property('arbitraryMeta', 'is arbitrary') describe '#html (html)', () -> it 'should correctly render xhtml body content', () -> testchapter = new Chapter(testchapters.html) testchapter.title.should.equal('HTML') testchapter.arbitraryMeta.should.equal('is arbitrary') testchapter.should.be.instanceOf(Chapter) testchapter.html.should.equal('<h1 id="h1-1">header</h1><p class="noindent" id="p-1">Test<br />‘—’“–”&#160;</p>') describe '#html (md)', () -> it 'should correctly render xhtml body content', () -> testchapter = new Chapter(testchapters.md) testchapter.title.should.equal('Markdown') testchapter.should.be.instanceOf(Chapter) testchapter.html.should.equal('<h1 id="header">header</h1>\n<p class="noindent" id="p-1">Test</p>\n') describe '#html (hbs)', () -> it 'should correctly render xhtml body content', () -> testbook = new Book({ title: 'The Wonderful Wizard of Oz', author: 'PI:NAME:<NAME>END_PI'}) testbook.addChapter(new Chapter(testchapters.hbs)) testbook.chapters[0].should.be.instanceOf(Chapter) testbook.chapters[0].title.should.equal('Template') testbook.chapters[0].should.be.instanceOf(Chapter) testbook.chapters[0].html.should.equal('<h1 id="h1-1">Template</h1><p class="noindent" id="p-1">Test<br />‘—’“–”&#160;</p>') describe '#html (xhtml)', () -> it 'should correctly render xhtml body content', () -> testchapter = new Chapter(testchapters.xhtml) testchapter.title.should.equal('XHTML') testchapter.should.be.instanceOf(Chapter) testchapter.html.should.equal('<h1>header</h1><p>Test<br/></p>') describe '#toJSON', () -> it 'should correctly give you a safe json file', () -> testbook = new Book({ title: 'The Wonderful Wizard of Oz', author: 'PI:NAME:<NAME>END_PI'}) testbook.addChapter(new Chapter(testchapters.hbs)) jsontest = testbook.chapters[0].toJSON() jsontest.should.equal("{\n \"type\": \"html\",\n \"title\": \"Template\",\n \"body\": \"<h1 id=\\\"h1-1\\\">Template</h1><p class=\\\"noindent\\\" id=\\\"p-1\\\">Test<br />‘—’“–”&#160;</p>\",\n \"id\": \"doc1\",\n \"_links\": {\n \"toc\": {\n \"href\": \"../index.json\",\n \"name\": \"TOC-JSON\",\n \"type\": \"application/hal+json\"\n },\n \"self\": {\n \"href\": \"doc1.json\",\n \"type\": \"application/hal+json\"\n }\n }\n}")
[ { "context": "schema', ->\n instance = new Model hacker: 'p0wn3d'\n expect(instance.hacker).to.be.undefined\n", "end": 6343, "score": 0.6650859117507935, "start": 6337, "tag": "USERNAME", "value": "p0wn3d" }, { "context": " m: { s: { t: 't' } }\n hacke...
test/ModinhaSpec.coffee
christiansmith/modinha
2
Modinha = require '../lib/Modinha' ModelCollection = require '../lib/ModelCollection' chai = require 'chai' expect = chai.expect chai.should() describe 'Modinha', -> {Model,InheritsFromModel,instance,validation,data,mapping,projection} = {} before -> Modinha.prototype.b = 'change me' Modinha.b = 'changed' Model = Modinha.inherit({ a: 'a' b: 'b' }, { a: 'a' b: 'b' schema: { q: { type: 'string' }, r: { type: 'boolean', default: true }, s: { properties: { t: { type: 'string' }, u: { type: 'boolean', default: true } } }, v: { type: 'string', default: -> 'generated' }, w: { type: 'string', private: true }, uuid: { type: 'string', default: Modinha.defaults.uuid, format: 'uuid', uniqueId: true }, random: { type: 'string', default: Modinha.defaults.random(12) } timestamp: { type: 'number', default: Modinha.defaults.timestamp } short: { type: 'string', maxLength: 6 } indirect: { type: 'string', set: ((data) -> @indirect = "indirect#{data.indirect}"), after: ((data) -> @after = "after#{@indirect}") } after: { type: 'string' } immutable: { type: 'string', immutable: true } } }) Model.mappings.named = 'q' : 'n' 's.t' : 'm.s.t' InheritsFromModel = Model.inherit({ b: 'bb' c: 'c' }, { b: 'bb' c: 'c' schema: { q: { default: 'q'} r: { default: false } } }) describe 'model', -> it 'should be inheritable', -> Descendant = Model.inherit() instance = new Descendant expect(instance).to.be.an.instanceof Descendant expect(instance).to.be.an.instanceof Model expect(instance).to.be.an.instanceof Modinha describe 'model definition', -> it 'should require a schema', -> expect(-> Modinha.define()).to.throw Modinha.UndefinedSchemaError it 'should inherit the model from Modinha', -> DefinedModel = Modinha.define Model.schema instance = new DefinedModel expect(instance).to.be.an.instanceof Modinha it 'should optionally assign a collection', -> DefinedModel = Modinha.define 'collection', Model.schema DefinedModel.collection.should.equal 'collection' describe 'model inheritance', -> before -> instance = new Model it 'should require a schema', -> expect(-> Modinha.inherit()).to.throw Modinha.UndefinedSchemaError it 'should override default uniqueId', -> Model.uniqueId.should.equal 'uuid' it 'should set new prototype properties on the subclass', -> instance.a.should.equal 'a' it 'should set new static properties on the subclass', -> Model.a.should.equal 'a' it 'should set the prototype\'s constructor', -> Model.prototype.constructor.should.equal Model it 'should set the superclass\' prototype', -> Model.superclass.should.equal Modinha.prototype it 'should override static properties on the subclass', -> InheritsFromModel.schema.r.default.should.equal false it 'should override prototype properties on the subclass', -> new InheritsFromModel().b.should.equal 'bb' it 'should not mutate the superclass', -> Model.schema.r.default.should.equal true describe 'model extension', -> describe 'with constructor function', -> before -> class Extension c: 'c' b: 'bb' @c: 'c' @b: 'bb' Model.extend Extension instance = new Model it 'should set new prototype properties on the model', -> instance.c.should.equal 'c' it 'should override prototype properties on the model', -> instance.b.should.equal 'bb' it 'should set new static properties on the model', -> Model.c.should.equal 'c' it 'should override static properties on the model', -> Model.b.should.equal 'bb' describe 'with prototype and static objects', -> before -> proto = d: 'd', b: 'bbb' stat = e: 'e', c: 'cc' Model.extend proto, stat instance = new Model it 'should set new prototype properties on the model', -> instance.d.should.equal 'd' it 'should override prototype properties on the model', -> instance.b.should.equal 'bbb' it 'should set new static properties on the model', -> Model.e.should.equal 'e' it 'should override static properties on the model', -> Model.c.should.equal 'cc' describe 'with post extend hook', -> before -> class PostExtension @__postExtend: -> @schema.foo = { type: 'string', default: 'bar' } Model.extend PostExtension instance = new Model it 'should invoke the hook to mutate the model', -> instance.foo.should.equal 'bar' describe 'instance', -> it 'should be an instance of its constructor', -> expect(instance).to.be.an.instanceof Model it 'should be an instance of Modinha', -> expect(instance).to.be.an.instanceof Modinha describe 'serialize', -> it 'should generate JSON', -> Model.serialize({ foo: 'bar' }).should.equal(JSON.stringify({ foo: 'bar' })) describe 'deserialize', -> it 'should parse JSON', -> Model.deserialize('{ "foo": "bar" }').foo.should.equal 'bar' it 'should catch parsing errors', -> expect(-> Model.deserialize('{badjson}')).to.throw Error describe 'instance initialization (merge)', -> describe 'without data', -> it 'should set defaults defined by value', -> instance = new Model instance.r.should.be.true instance.s.u.should.be.true it 'should set defaults defined by function', -> instance = new Model instance.v.should.equal 'generated' describe 'with data', -> it 'should set properties defined in the schema', -> instance = new Model { q: 'q', s: { t: 't' } } instance.q.should.equal 'q' instance.s.t.should.equal 't' it 'should ignore properties not defined in the schema', -> instance = new Model hacker: 'p0wn3d' expect(instance.hacker).to.be.undefined it 'should set defaults defined by value', -> instance = new Model q : 'q' instance.r.should.be.true instance.s.u.should.be.true it 'should set defaults defined by function', -> instance = new Model q: 'q' instance.v.should.equal 'generated' it 'should invoke setter', -> instance = new Model indirect: 'value' instance.indirect.should.equal 'indirectvalue' it 'should invoke after', -> instance = new Model indirect: 'value' instance.after.should.equal 'afterindirectvalue' it 'should override default properties with provided data', -> instance = new Model r: false instance.r.should.be.false it 'should skip private values by default', -> instance = new Model w: 'secret' expect(instance.w).to.be.undefined it 'should set immutable values', -> instance = new Model immutable: 'cannot change' instance.immutable = 'changed' instance.immutable.should.equal 'cannot change' describe 'with $unset operator', -> it 'should delete specified properties', -> instance = new Model { q: 'not deleted' } instance.should.have.property 'q' instance.q.should.equal 'not deleted' instance.merge { }, { $unset: [ 'q' ] } instance.should.not.have.property 'q' describe 'with private values option', -> it 'should set private values', -> instance = new Model { w: 'secret' }, { private: true } instance.w.should.equal 'secret' describe 'with mapping option', -> before -> data = n: 'q' m: { s: { t: 't' } } hacker: 'p0wn3d' mapping = 'q' : 'n' 's.t' : 'm.s.t' instance = new Model data, mapping: mapping it 'should initialize an object from a literal mapping', -> instance.q.should.equal 'q' instance.s.t.should.equal 't' it 'should initialize an object from a named mapping', -> instance = new Model data, mapping: 'named' instance.q.should.equal 'q' instance.s.t.should.equal 't' it 'should ignore properties not defined in the map', -> expect(instance.hacker).to.be.undefined describe 'with select option', -> before -> instance = new Model { q: 'q', r: true, v: 'generated' }, select: ['r','v'] it 'should initialize a subset of an object\'s properties', -> instance.r.should.be.true instance.v.should.equal 'generated' it 'should ignore properties not defined in the selection', -> expect(instance.q).to.be.undefined it 'should generate default values if selected' describe 'without default values', -> before -> instance = new Model {}, { defaults: false } it 'should not initialize default values', -> expect(instance.r).to.be.undefined expect(instance.s.u).to.be.undefined expect(instance.v).to.be.undefined describe 'instance projection', -> before -> instance = new Model q: 'q', s: { t: 't' } mapping = 'q' : 'n' 's.t' : 'm.s.t' data = instance.project(mapping) it 'should initialize a new object from a literal mapping', -> data.n.should.equal 'q' data.m.s.t.should.equal 't' it 'should initialize a new object from a named mapping', -> data = instance.project 'named' data.n.should.equal 'q' data.m.s.t.should.equal 't' describe 'static initialization', -> describe 'without data', -> it 'should provide an instance of the model', -> instance = Model.initialize() expect(instance).to.be.instanceof Model describe 'with nullify option and no data', -> it 'should provide null if data is undefined', -> instance = Model.initialize undefined, nullify: true expect(instance).to.be.null it 'should provide null if data is null', -> instance = Model.initialize null, nullify: true expect(instance).to.be.null describe 'with object data', -> it 'should provide an instance of the model', -> instance = Model.initialize { q: 'qwerty' } expect(instance).to.be.instanceof Model instance.q.should.equal 'qwerty' describe 'with array data', -> it 'should provide an array of model instances', -> Model.initialize([ {q:'first'} {q:'second'} {q:'third'} ]).forEach (instance) -> expect(instance).to.be.instanceof Model describe 'with JSON object data', -> it 'should provide an instance of the model', -> instance = Model.initialize '{ "q": "qwerty" }' expect(instance).to.be.instanceof Model instance.q.should.equal 'qwerty' describe 'with JSON array data', -> it 'should provide a ModelCollection of model instances', -> models = Model.initialize('''[ { "q": "first" }, { "q": "second" }, { "q": "third" } ]''') expect(models).to.be.an 'array' expect(models.__model).to.equal Model models.forEach (instance) -> expect(instance).to.be.instanceof Model describe 'with an array of JSON object data', -> it 'should provide a ModelCollection of model instances', -> models = Model.initialize([ '{ "q": "first" }', '{ "q": "second" }', '{ "q": "third" }' ]) expect(models).to.be.an 'array' expect(models.__model).to.equal Model models.forEach (instance) -> expect(instance).to.be.instanceof Model describe 'with an array and "first" option', -> it 'should return the first instance', -> instance = Model.initialize([{}, {}, {}], { first: true }) Array.isArray(instance).should.be.false expect(instance).to.be.instanceof Model describe 'with functional options', -> it 'should map over instances' it 'should return a filtered set of instances' describe 'default', -> describe 'random', -> it 'should generate a random string of a given length', -> instance = new Model instance.random.length.should.be.at.least 12 describe 'uuid', -> it 'should generate a uuid', -> instance = new Model instance.uuid.length.should.equal 36 instance.validate().valid.should.be.true describe 'timestamp', -> it 'should generate a timestamp', -> instance = new Model instance.timestamp.should.equal Date.now(instance.timestamp) describe 'instance merge', -> describe 'with no options', -> before -> instance = new Model { q: 'q', s: { t: 't' } } instance.initialize { q: 'qq', s: { t: 'tt' }, hacker: 'p0wn3d' } it 'should set properties defined in the schema', -> instance.q.should.equal 'qq' instance.s.t.should.equal 'tt' it 'should ignore properties not defined in the schema', -> expect(instance.hacker).to.be.undefined describe 'with map option', -> beforeEach -> instance = new Model { q: 'q', s: { t: 't' } } data = n: 'qq' m: { s: { t: 'tt' } } hacker: 'p0wn3d' mapping = 'q' : 'n' 's.t' : 'm.s.t' it 'should update an object from a literal mapping', -> instance.initialize data, mapping: mapping instance.q.should.equal 'qq' instance.s.t.should.equal 'tt' it 'should update an object from a named mapping', -> instance.initialize data, mapping: 'named' instance.q.should.equal 'qq' instance.s.t.should.equal 'tt' it 'should ignore properties not defined in the map', -> instance.initialize data, mapping: mapping expect(instance.hacker).to.be.undefined describe 'with project option', -> beforeEach -> data = q: 'q' s: t: 't' projection = 'q' : 'n' 's.t' : 'm.s.t' it 'should intialize an object that differs from the schema', -> instance = Model.initialize data object = Modinha.project instance, {}, projection object.n.should.equal 'q' object.m.s.t.should.equal 't' describe 'instance validation', -> describe 'with valid data', -> it 'should be valid', -> instance = new Model { short: 'short' } instance.validate().valid.should.be.true describe 'with invalid data', -> before -> instance = new Model { short: 'tooLong' } validation = instance.validate() it 'should not be valid', -> validation.valid.should.be.false it 'should return a ValidationError', -> expect(validation).to.be.instanceof Modinha.ValidationError describe 'static validation', -> describe 'with valid data', -> it 'should be valid', -> Model.validate({ short: 'short' }).valid.should.be.true describe 'with invalid data', -> before -> validation = Model.validate({ short: 'tooLong' }) it 'should not be valid', -> validation.valid.should.be.false it 'should return a ValidationError', -> expect(validation).to.be.instanceof Modinha.ValidationError describe 'state machine', -> it 'should add a "state" property to the schema?' it 'should enumerate states' it 'should define transitions' it 'should guard transitions' it 'should execute "enter" callbacks' it 'should execute "exit" callbacks' describe 'related object constraints?', ->
65595
Modinha = require '../lib/Modinha' ModelCollection = require '../lib/ModelCollection' chai = require 'chai' expect = chai.expect chai.should() describe 'Modinha', -> {Model,InheritsFromModel,instance,validation,data,mapping,projection} = {} before -> Modinha.prototype.b = 'change me' Modinha.b = 'changed' Model = Modinha.inherit({ a: 'a' b: 'b' }, { a: 'a' b: 'b' schema: { q: { type: 'string' }, r: { type: 'boolean', default: true }, s: { properties: { t: { type: 'string' }, u: { type: 'boolean', default: true } } }, v: { type: 'string', default: -> 'generated' }, w: { type: 'string', private: true }, uuid: { type: 'string', default: Modinha.defaults.uuid, format: 'uuid', uniqueId: true }, random: { type: 'string', default: Modinha.defaults.random(12) } timestamp: { type: 'number', default: Modinha.defaults.timestamp } short: { type: 'string', maxLength: 6 } indirect: { type: 'string', set: ((data) -> @indirect = "indirect#{data.indirect}"), after: ((data) -> @after = "after#{@indirect}") } after: { type: 'string' } immutable: { type: 'string', immutable: true } } }) Model.mappings.named = 'q' : 'n' 's.t' : 'm.s.t' InheritsFromModel = Model.inherit({ b: 'bb' c: 'c' }, { b: 'bb' c: 'c' schema: { q: { default: 'q'} r: { default: false } } }) describe 'model', -> it 'should be inheritable', -> Descendant = Model.inherit() instance = new Descendant expect(instance).to.be.an.instanceof Descendant expect(instance).to.be.an.instanceof Model expect(instance).to.be.an.instanceof Modinha describe 'model definition', -> it 'should require a schema', -> expect(-> Modinha.define()).to.throw Modinha.UndefinedSchemaError it 'should inherit the model from Modinha', -> DefinedModel = Modinha.define Model.schema instance = new DefinedModel expect(instance).to.be.an.instanceof Modinha it 'should optionally assign a collection', -> DefinedModel = Modinha.define 'collection', Model.schema DefinedModel.collection.should.equal 'collection' describe 'model inheritance', -> before -> instance = new Model it 'should require a schema', -> expect(-> Modinha.inherit()).to.throw Modinha.UndefinedSchemaError it 'should override default uniqueId', -> Model.uniqueId.should.equal 'uuid' it 'should set new prototype properties on the subclass', -> instance.a.should.equal 'a' it 'should set new static properties on the subclass', -> Model.a.should.equal 'a' it 'should set the prototype\'s constructor', -> Model.prototype.constructor.should.equal Model it 'should set the superclass\' prototype', -> Model.superclass.should.equal Modinha.prototype it 'should override static properties on the subclass', -> InheritsFromModel.schema.r.default.should.equal false it 'should override prototype properties on the subclass', -> new InheritsFromModel().b.should.equal 'bb' it 'should not mutate the superclass', -> Model.schema.r.default.should.equal true describe 'model extension', -> describe 'with constructor function', -> before -> class Extension c: 'c' b: 'bb' @c: 'c' @b: 'bb' Model.extend Extension instance = new Model it 'should set new prototype properties on the model', -> instance.c.should.equal 'c' it 'should override prototype properties on the model', -> instance.b.should.equal 'bb' it 'should set new static properties on the model', -> Model.c.should.equal 'c' it 'should override static properties on the model', -> Model.b.should.equal 'bb' describe 'with prototype and static objects', -> before -> proto = d: 'd', b: 'bbb' stat = e: 'e', c: 'cc' Model.extend proto, stat instance = new Model it 'should set new prototype properties on the model', -> instance.d.should.equal 'd' it 'should override prototype properties on the model', -> instance.b.should.equal 'bbb' it 'should set new static properties on the model', -> Model.e.should.equal 'e' it 'should override static properties on the model', -> Model.c.should.equal 'cc' describe 'with post extend hook', -> before -> class PostExtension @__postExtend: -> @schema.foo = { type: 'string', default: 'bar' } Model.extend PostExtension instance = new Model it 'should invoke the hook to mutate the model', -> instance.foo.should.equal 'bar' describe 'instance', -> it 'should be an instance of its constructor', -> expect(instance).to.be.an.instanceof Model it 'should be an instance of Modinha', -> expect(instance).to.be.an.instanceof Modinha describe 'serialize', -> it 'should generate JSON', -> Model.serialize({ foo: 'bar' }).should.equal(JSON.stringify({ foo: 'bar' })) describe 'deserialize', -> it 'should parse JSON', -> Model.deserialize('{ "foo": "bar" }').foo.should.equal 'bar' it 'should catch parsing errors', -> expect(-> Model.deserialize('{badjson}')).to.throw Error describe 'instance initialization (merge)', -> describe 'without data', -> it 'should set defaults defined by value', -> instance = new Model instance.r.should.be.true instance.s.u.should.be.true it 'should set defaults defined by function', -> instance = new Model instance.v.should.equal 'generated' describe 'with data', -> it 'should set properties defined in the schema', -> instance = new Model { q: 'q', s: { t: 't' } } instance.q.should.equal 'q' instance.s.t.should.equal 't' it 'should ignore properties not defined in the schema', -> instance = new Model hacker: 'p0wn3d' expect(instance.hacker).to.be.undefined it 'should set defaults defined by value', -> instance = new Model q : 'q' instance.r.should.be.true instance.s.u.should.be.true it 'should set defaults defined by function', -> instance = new Model q: 'q' instance.v.should.equal 'generated' it 'should invoke setter', -> instance = new Model indirect: 'value' instance.indirect.should.equal 'indirectvalue' it 'should invoke after', -> instance = new Model indirect: 'value' instance.after.should.equal 'afterindirectvalue' it 'should override default properties with provided data', -> instance = new Model r: false instance.r.should.be.false it 'should skip private values by default', -> instance = new Model w: 'secret' expect(instance.w).to.be.undefined it 'should set immutable values', -> instance = new Model immutable: 'cannot change' instance.immutable = 'changed' instance.immutable.should.equal 'cannot change' describe 'with $unset operator', -> it 'should delete specified properties', -> instance = new Model { q: 'not deleted' } instance.should.have.property 'q' instance.q.should.equal 'not deleted' instance.merge { }, { $unset: [ 'q' ] } instance.should.not.have.property 'q' describe 'with private values option', -> it 'should set private values', -> instance = new Model { w: 'secret' }, { private: true } instance.w.should.equal 'secret' describe 'with mapping option', -> before -> data = n: 'q' m: { s: { t: 't' } } hacker: 'p<PASSWORD>' mapping = 'q' : 'n' 's.t' : 'm.s.t' instance = new Model data, mapping: mapping it 'should initialize an object from a literal mapping', -> instance.q.should.equal 'q' instance.s.t.should.equal 't' it 'should initialize an object from a named mapping', -> instance = new Model data, mapping: 'named' instance.q.should.equal 'q' instance.s.t.should.equal 't' it 'should ignore properties not defined in the map', -> expect(instance.hacker).to.be.undefined describe 'with select option', -> before -> instance = new Model { q: 'q', r: true, v: 'generated' }, select: ['r','v'] it 'should initialize a subset of an object\'s properties', -> instance.r.should.be.true instance.v.should.equal 'generated' it 'should ignore properties not defined in the selection', -> expect(instance.q).to.be.undefined it 'should generate default values if selected' describe 'without default values', -> before -> instance = new Model {}, { defaults: false } it 'should not initialize default values', -> expect(instance.r).to.be.undefined expect(instance.s.u).to.be.undefined expect(instance.v).to.be.undefined describe 'instance projection', -> before -> instance = new Model q: 'q', s: { t: 't' } mapping = 'q' : 'n' 's.t' : 'm.s.t' data = instance.project(mapping) it 'should initialize a new object from a literal mapping', -> data.n.should.equal 'q' data.m.s.t.should.equal 't' it 'should initialize a new object from a named mapping', -> data = instance.project 'named' data.n.should.equal 'q' data.m.s.t.should.equal 't' describe 'static initialization', -> describe 'without data', -> it 'should provide an instance of the model', -> instance = Model.initialize() expect(instance).to.be.instanceof Model describe 'with nullify option and no data', -> it 'should provide null if data is undefined', -> instance = Model.initialize undefined, nullify: true expect(instance).to.be.null it 'should provide null if data is null', -> instance = Model.initialize null, nullify: true expect(instance).to.be.null describe 'with object data', -> it 'should provide an instance of the model', -> instance = Model.initialize { q: 'qwerty' } expect(instance).to.be.instanceof Model instance.q.should.equal 'qwerty' describe 'with array data', -> it 'should provide an array of model instances', -> Model.initialize([ {q:'first'} {q:'second'} {q:'third'} ]).forEach (instance) -> expect(instance).to.be.instanceof Model describe 'with JSON object data', -> it 'should provide an instance of the model', -> instance = Model.initialize '{ "q": "qwerty" }' expect(instance).to.be.instanceof Model instance.q.should.equal 'qwerty' describe 'with JSON array data', -> it 'should provide a ModelCollection of model instances', -> models = Model.initialize('''[ { "q": "first" }, { "q": "second" }, { "q": "third" } ]''') expect(models).to.be.an 'array' expect(models.__model).to.equal Model models.forEach (instance) -> expect(instance).to.be.instanceof Model describe 'with an array of JSON object data', -> it 'should provide a ModelCollection of model instances', -> models = Model.initialize([ '{ "q": "first" }', '{ "q": "second" }', '{ "q": "third" }' ]) expect(models).to.be.an 'array' expect(models.__model).to.equal Model models.forEach (instance) -> expect(instance).to.be.instanceof Model describe 'with an array and "first" option', -> it 'should return the first instance', -> instance = Model.initialize([{}, {}, {}], { first: true }) Array.isArray(instance).should.be.false expect(instance).to.be.instanceof Model describe 'with functional options', -> it 'should map over instances' it 'should return a filtered set of instances' describe 'default', -> describe 'random', -> it 'should generate a random string of a given length', -> instance = new Model instance.random.length.should.be.at.least 12 describe 'uuid', -> it 'should generate a uuid', -> instance = new Model instance.uuid.length.should.equal 36 instance.validate().valid.should.be.true describe 'timestamp', -> it 'should generate a timestamp', -> instance = new Model instance.timestamp.should.equal Date.now(instance.timestamp) describe 'instance merge', -> describe 'with no options', -> before -> instance = new Model { q: 'q', s: { t: 't' } } instance.initialize { q: 'qq', s: { t: 'tt' }, hacker: 'p0wn3d' } it 'should set properties defined in the schema', -> instance.q.should.equal 'qq' instance.s.t.should.equal 'tt' it 'should ignore properties not defined in the schema', -> expect(instance.hacker).to.be.undefined describe 'with map option', -> beforeEach -> instance = new Model { q: 'q', s: { t: 't' } } data = n: 'qq' m: { s: { t: 'tt' } } hacker: 'p0wn3d' mapping = 'q' : 'n' 's.t' : 'm.s.t' it 'should update an object from a literal mapping', -> instance.initialize data, mapping: mapping instance.q.should.equal 'qq' instance.s.t.should.equal 'tt' it 'should update an object from a named mapping', -> instance.initialize data, mapping: 'named' instance.q.should.equal 'qq' instance.s.t.should.equal 'tt' it 'should ignore properties not defined in the map', -> instance.initialize data, mapping: mapping expect(instance.hacker).to.be.undefined describe 'with project option', -> beforeEach -> data = q: 'q' s: t: 't' projection = 'q' : 'n' 's.t' : 'm.s.t' it 'should intialize an object that differs from the schema', -> instance = Model.initialize data object = Modinha.project instance, {}, projection object.n.should.equal 'q' object.m.s.t.should.equal 't' describe 'instance validation', -> describe 'with valid data', -> it 'should be valid', -> instance = new Model { short: 'short' } instance.validate().valid.should.be.true describe 'with invalid data', -> before -> instance = new Model { short: 'tooLong' } validation = instance.validate() it 'should not be valid', -> validation.valid.should.be.false it 'should return a ValidationError', -> expect(validation).to.be.instanceof Modinha.ValidationError describe 'static validation', -> describe 'with valid data', -> it 'should be valid', -> Model.validate({ short: 'short' }).valid.should.be.true describe 'with invalid data', -> before -> validation = Model.validate({ short: 'tooLong' }) it 'should not be valid', -> validation.valid.should.be.false it 'should return a ValidationError', -> expect(validation).to.be.instanceof Modinha.ValidationError describe 'state machine', -> it 'should add a "state" property to the schema?' it 'should enumerate states' it 'should define transitions' it 'should guard transitions' it 'should execute "enter" callbacks' it 'should execute "exit" callbacks' describe 'related object constraints?', ->
true
Modinha = require '../lib/Modinha' ModelCollection = require '../lib/ModelCollection' chai = require 'chai' expect = chai.expect chai.should() describe 'Modinha', -> {Model,InheritsFromModel,instance,validation,data,mapping,projection} = {} before -> Modinha.prototype.b = 'change me' Modinha.b = 'changed' Model = Modinha.inherit({ a: 'a' b: 'b' }, { a: 'a' b: 'b' schema: { q: { type: 'string' }, r: { type: 'boolean', default: true }, s: { properties: { t: { type: 'string' }, u: { type: 'boolean', default: true } } }, v: { type: 'string', default: -> 'generated' }, w: { type: 'string', private: true }, uuid: { type: 'string', default: Modinha.defaults.uuid, format: 'uuid', uniqueId: true }, random: { type: 'string', default: Modinha.defaults.random(12) } timestamp: { type: 'number', default: Modinha.defaults.timestamp } short: { type: 'string', maxLength: 6 } indirect: { type: 'string', set: ((data) -> @indirect = "indirect#{data.indirect}"), after: ((data) -> @after = "after#{@indirect}") } after: { type: 'string' } immutable: { type: 'string', immutable: true } } }) Model.mappings.named = 'q' : 'n' 's.t' : 'm.s.t' InheritsFromModel = Model.inherit({ b: 'bb' c: 'c' }, { b: 'bb' c: 'c' schema: { q: { default: 'q'} r: { default: false } } }) describe 'model', -> it 'should be inheritable', -> Descendant = Model.inherit() instance = new Descendant expect(instance).to.be.an.instanceof Descendant expect(instance).to.be.an.instanceof Model expect(instance).to.be.an.instanceof Modinha describe 'model definition', -> it 'should require a schema', -> expect(-> Modinha.define()).to.throw Modinha.UndefinedSchemaError it 'should inherit the model from Modinha', -> DefinedModel = Modinha.define Model.schema instance = new DefinedModel expect(instance).to.be.an.instanceof Modinha it 'should optionally assign a collection', -> DefinedModel = Modinha.define 'collection', Model.schema DefinedModel.collection.should.equal 'collection' describe 'model inheritance', -> before -> instance = new Model it 'should require a schema', -> expect(-> Modinha.inherit()).to.throw Modinha.UndefinedSchemaError it 'should override default uniqueId', -> Model.uniqueId.should.equal 'uuid' it 'should set new prototype properties on the subclass', -> instance.a.should.equal 'a' it 'should set new static properties on the subclass', -> Model.a.should.equal 'a' it 'should set the prototype\'s constructor', -> Model.prototype.constructor.should.equal Model it 'should set the superclass\' prototype', -> Model.superclass.should.equal Modinha.prototype it 'should override static properties on the subclass', -> InheritsFromModel.schema.r.default.should.equal false it 'should override prototype properties on the subclass', -> new InheritsFromModel().b.should.equal 'bb' it 'should not mutate the superclass', -> Model.schema.r.default.should.equal true describe 'model extension', -> describe 'with constructor function', -> before -> class Extension c: 'c' b: 'bb' @c: 'c' @b: 'bb' Model.extend Extension instance = new Model it 'should set new prototype properties on the model', -> instance.c.should.equal 'c' it 'should override prototype properties on the model', -> instance.b.should.equal 'bb' it 'should set new static properties on the model', -> Model.c.should.equal 'c' it 'should override static properties on the model', -> Model.b.should.equal 'bb' describe 'with prototype and static objects', -> before -> proto = d: 'd', b: 'bbb' stat = e: 'e', c: 'cc' Model.extend proto, stat instance = new Model it 'should set new prototype properties on the model', -> instance.d.should.equal 'd' it 'should override prototype properties on the model', -> instance.b.should.equal 'bbb' it 'should set new static properties on the model', -> Model.e.should.equal 'e' it 'should override static properties on the model', -> Model.c.should.equal 'cc' describe 'with post extend hook', -> before -> class PostExtension @__postExtend: -> @schema.foo = { type: 'string', default: 'bar' } Model.extend PostExtension instance = new Model it 'should invoke the hook to mutate the model', -> instance.foo.should.equal 'bar' describe 'instance', -> it 'should be an instance of its constructor', -> expect(instance).to.be.an.instanceof Model it 'should be an instance of Modinha', -> expect(instance).to.be.an.instanceof Modinha describe 'serialize', -> it 'should generate JSON', -> Model.serialize({ foo: 'bar' }).should.equal(JSON.stringify({ foo: 'bar' })) describe 'deserialize', -> it 'should parse JSON', -> Model.deserialize('{ "foo": "bar" }').foo.should.equal 'bar' it 'should catch parsing errors', -> expect(-> Model.deserialize('{badjson}')).to.throw Error describe 'instance initialization (merge)', -> describe 'without data', -> it 'should set defaults defined by value', -> instance = new Model instance.r.should.be.true instance.s.u.should.be.true it 'should set defaults defined by function', -> instance = new Model instance.v.should.equal 'generated' describe 'with data', -> it 'should set properties defined in the schema', -> instance = new Model { q: 'q', s: { t: 't' } } instance.q.should.equal 'q' instance.s.t.should.equal 't' it 'should ignore properties not defined in the schema', -> instance = new Model hacker: 'p0wn3d' expect(instance.hacker).to.be.undefined it 'should set defaults defined by value', -> instance = new Model q : 'q' instance.r.should.be.true instance.s.u.should.be.true it 'should set defaults defined by function', -> instance = new Model q: 'q' instance.v.should.equal 'generated' it 'should invoke setter', -> instance = new Model indirect: 'value' instance.indirect.should.equal 'indirectvalue' it 'should invoke after', -> instance = new Model indirect: 'value' instance.after.should.equal 'afterindirectvalue' it 'should override default properties with provided data', -> instance = new Model r: false instance.r.should.be.false it 'should skip private values by default', -> instance = new Model w: 'secret' expect(instance.w).to.be.undefined it 'should set immutable values', -> instance = new Model immutable: 'cannot change' instance.immutable = 'changed' instance.immutable.should.equal 'cannot change' describe 'with $unset operator', -> it 'should delete specified properties', -> instance = new Model { q: 'not deleted' } instance.should.have.property 'q' instance.q.should.equal 'not deleted' instance.merge { }, { $unset: [ 'q' ] } instance.should.not.have.property 'q' describe 'with private values option', -> it 'should set private values', -> instance = new Model { w: 'secret' }, { private: true } instance.w.should.equal 'secret' describe 'with mapping option', -> before -> data = n: 'q' m: { s: { t: 't' } } hacker: 'pPI:PASSWORD:<PASSWORD>END_PI' mapping = 'q' : 'n' 's.t' : 'm.s.t' instance = new Model data, mapping: mapping it 'should initialize an object from a literal mapping', -> instance.q.should.equal 'q' instance.s.t.should.equal 't' it 'should initialize an object from a named mapping', -> instance = new Model data, mapping: 'named' instance.q.should.equal 'q' instance.s.t.should.equal 't' it 'should ignore properties not defined in the map', -> expect(instance.hacker).to.be.undefined describe 'with select option', -> before -> instance = new Model { q: 'q', r: true, v: 'generated' }, select: ['r','v'] it 'should initialize a subset of an object\'s properties', -> instance.r.should.be.true instance.v.should.equal 'generated' it 'should ignore properties not defined in the selection', -> expect(instance.q).to.be.undefined it 'should generate default values if selected' describe 'without default values', -> before -> instance = new Model {}, { defaults: false } it 'should not initialize default values', -> expect(instance.r).to.be.undefined expect(instance.s.u).to.be.undefined expect(instance.v).to.be.undefined describe 'instance projection', -> before -> instance = new Model q: 'q', s: { t: 't' } mapping = 'q' : 'n' 's.t' : 'm.s.t' data = instance.project(mapping) it 'should initialize a new object from a literal mapping', -> data.n.should.equal 'q' data.m.s.t.should.equal 't' it 'should initialize a new object from a named mapping', -> data = instance.project 'named' data.n.should.equal 'q' data.m.s.t.should.equal 't' describe 'static initialization', -> describe 'without data', -> it 'should provide an instance of the model', -> instance = Model.initialize() expect(instance).to.be.instanceof Model describe 'with nullify option and no data', -> it 'should provide null if data is undefined', -> instance = Model.initialize undefined, nullify: true expect(instance).to.be.null it 'should provide null if data is null', -> instance = Model.initialize null, nullify: true expect(instance).to.be.null describe 'with object data', -> it 'should provide an instance of the model', -> instance = Model.initialize { q: 'qwerty' } expect(instance).to.be.instanceof Model instance.q.should.equal 'qwerty' describe 'with array data', -> it 'should provide an array of model instances', -> Model.initialize([ {q:'first'} {q:'second'} {q:'third'} ]).forEach (instance) -> expect(instance).to.be.instanceof Model describe 'with JSON object data', -> it 'should provide an instance of the model', -> instance = Model.initialize '{ "q": "qwerty" }' expect(instance).to.be.instanceof Model instance.q.should.equal 'qwerty' describe 'with JSON array data', -> it 'should provide a ModelCollection of model instances', -> models = Model.initialize('''[ { "q": "first" }, { "q": "second" }, { "q": "third" } ]''') expect(models).to.be.an 'array' expect(models.__model).to.equal Model models.forEach (instance) -> expect(instance).to.be.instanceof Model describe 'with an array of JSON object data', -> it 'should provide a ModelCollection of model instances', -> models = Model.initialize([ '{ "q": "first" }', '{ "q": "second" }', '{ "q": "third" }' ]) expect(models).to.be.an 'array' expect(models.__model).to.equal Model models.forEach (instance) -> expect(instance).to.be.instanceof Model describe 'with an array and "first" option', -> it 'should return the first instance', -> instance = Model.initialize([{}, {}, {}], { first: true }) Array.isArray(instance).should.be.false expect(instance).to.be.instanceof Model describe 'with functional options', -> it 'should map over instances' it 'should return a filtered set of instances' describe 'default', -> describe 'random', -> it 'should generate a random string of a given length', -> instance = new Model instance.random.length.should.be.at.least 12 describe 'uuid', -> it 'should generate a uuid', -> instance = new Model instance.uuid.length.should.equal 36 instance.validate().valid.should.be.true describe 'timestamp', -> it 'should generate a timestamp', -> instance = new Model instance.timestamp.should.equal Date.now(instance.timestamp) describe 'instance merge', -> describe 'with no options', -> before -> instance = new Model { q: 'q', s: { t: 't' } } instance.initialize { q: 'qq', s: { t: 'tt' }, hacker: 'p0wn3d' } it 'should set properties defined in the schema', -> instance.q.should.equal 'qq' instance.s.t.should.equal 'tt' it 'should ignore properties not defined in the schema', -> expect(instance.hacker).to.be.undefined describe 'with map option', -> beforeEach -> instance = new Model { q: 'q', s: { t: 't' } } data = n: 'qq' m: { s: { t: 'tt' } } hacker: 'p0wn3d' mapping = 'q' : 'n' 's.t' : 'm.s.t' it 'should update an object from a literal mapping', -> instance.initialize data, mapping: mapping instance.q.should.equal 'qq' instance.s.t.should.equal 'tt' it 'should update an object from a named mapping', -> instance.initialize data, mapping: 'named' instance.q.should.equal 'qq' instance.s.t.should.equal 'tt' it 'should ignore properties not defined in the map', -> instance.initialize data, mapping: mapping expect(instance.hacker).to.be.undefined describe 'with project option', -> beforeEach -> data = q: 'q' s: t: 't' projection = 'q' : 'n' 's.t' : 'm.s.t' it 'should intialize an object that differs from the schema', -> instance = Model.initialize data object = Modinha.project instance, {}, projection object.n.should.equal 'q' object.m.s.t.should.equal 't' describe 'instance validation', -> describe 'with valid data', -> it 'should be valid', -> instance = new Model { short: 'short' } instance.validate().valid.should.be.true describe 'with invalid data', -> before -> instance = new Model { short: 'tooLong' } validation = instance.validate() it 'should not be valid', -> validation.valid.should.be.false it 'should return a ValidationError', -> expect(validation).to.be.instanceof Modinha.ValidationError describe 'static validation', -> describe 'with valid data', -> it 'should be valid', -> Model.validate({ short: 'short' }).valid.should.be.true describe 'with invalid data', -> before -> validation = Model.validate({ short: 'tooLong' }) it 'should not be valid', -> validation.valid.should.be.false it 'should return a ValidationError', -> expect(validation).to.be.instanceof Modinha.ValidationError describe 'state machine', -> it 'should add a "state" property to the schema?' it 'should enumerate states' it 'should define transitions' it 'should guard transitions' it 'should execute "enter" callbacks' it 'should execute "exit" callbacks' describe 'related object constraints?', ->
[ { "context": "JAX related extensions\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\nElement.include\n #\n # Loads the the url via A", "end": 94, "score": 0.999889075756073, "start": 77, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/ajax/src/element.coffee
lovely-io/lovely.io-stl
2
# # The DOM Element unit AJAX related extensions # # Copyright (C) 2011-2012 Nikolay Nemshilov # Element.include # # Loads the the url via AJAX and then updates the content # of the element with the response text # # NOTE: will perform a _GET_ request by default # # @param {String} url address # @param {Object} ajax options # @return {Element} this # load: (url, options)-> @ajax = new Ajax(url, Hash.merge({method: 'get'}, options)) @ajax.on('success', bind((event)-> @update event.ajax.responseText @emit 'ajax:update' , @)) @ajax.send() return @
62053
# # The DOM Element unit AJAX related extensions # # Copyright (C) 2011-2012 <NAME> # Element.include # # Loads the the url via AJAX and then updates the content # of the element with the response text # # NOTE: will perform a _GET_ request by default # # @param {String} url address # @param {Object} ajax options # @return {Element} this # load: (url, options)-> @ajax = new Ajax(url, Hash.merge({method: 'get'}, options)) @ajax.on('success', bind((event)-> @update event.ajax.responseText @emit 'ajax:update' , @)) @ajax.send() return @
true
# # The DOM Element unit AJAX related extensions # # Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI # Element.include # # Loads the the url via AJAX and then updates the content # of the element with the response text # # NOTE: will perform a _GET_ request by default # # @param {String} url address # @param {Object} ajax options # @return {Element} this # load: (url, options)-> @ajax = new Ajax(url, Hash.merge({method: 'get'}, options)) @ajax.on('success', bind((event)-> @update event.ajax.responseText @emit 'ajax:update' , @)) @ajax.send() return @
[ { "context": "s:\n# pong - Display a pong image\n#\n# Author:\n# Adam Crews <adam.crews@gmail.com>\n\npong = [\n \"http://img.sh", "end": 169, "score": 0.9998509883880615, "start": 159, "tag": "NAME", "value": "Adam Crews" }, { "context": " Display a pong image\n#\n# Author:\n# ...
src/pong.coffee
adamcrews/hubot-pong
0
# Description: # Display's a pong image # # Dependencies: # None # # Configuration: # None # # Commands: # pong - Display a pong image # # Author: # Adam Crews <adam.crews@gmail.com> pong = [ "http://img.shroom.net/pong.jpg", "http://media.moddb.com/cache/images/mods/1/8/7707/thumb_620x2000/50085.jpg", "https://lh4.ggpht.com/_RzlKPjvg-AmeM5SlDV4HNtpiGpkt7rxiR_bioIGtM2tfYcRa03_61hSGTKWf0DKJQ=h900", "http://www.game-gt.com/images/pongflash.jpg", "http://pongmuseum.com/history/_picts/atari/pong_cabbig-web.jpg", "http://thedoteaters.com/tde/wp-content/uploads/2013/03/pong-winnerIV.jpg", "http://www.obsolete-tears.com/photos/Sears-Pong-Sports-IV-gp.jpg", "https://atariage.com/2600/carts/c_Sears_PongSports_Picture_front.jpg", "http://www.vectronicscollections.org/consoles/images/atari2600/paddles.jpg", "https://dustyconsoles.files.wordpress.com/2013/02/fairchild-channel-f.png", "http://www.davesclassicarcade.com/consoles/telstaralpha.JPG", "https://s-media-cache-ak0.pinimg.com/564x/ee/f1/47/eef147fa8b2a737b714ae9e3d5377411.jpg", "https://upload.wikimedia.org/wikipedia/commons/f/f1/Ping-Pong_2.jpg", "https://dustyconsoles.files.wordpress.com/2013/01/img_0740.jpg" ] module.exports = (robot) -> robot.hear /pong/i, (msg) -> msg.send msg.random pong
152232
# Description: # Display's a pong image # # Dependencies: # None # # Configuration: # None # # Commands: # pong - Display a pong image # # Author: # <NAME> <<EMAIL>> pong = [ "http://img.shroom.net/pong.jpg", "http://media.moddb.com/cache/images/mods/1/8/7707/thumb_620x2000/50085.jpg", "https://lh4.ggpht.com/_RzlKPjvg-AmeM5SlDV4HNtpiGpkt7rxiR_bioIGtM2tfYcRa03_61hSGTKWf0DKJQ=h900", "http://www.game-gt.com/images/pongflash.jpg", "http://pongmuseum.com/history/_picts/atari/pong_cabbig-web.jpg", "http://thedoteaters.com/tde/wp-content/uploads/2013/03/pong-winnerIV.jpg", "http://www.obsolete-tears.com/photos/Sears-Pong-Sports-IV-gp.jpg", "https://atariage.com/2600/carts/c_Sears_PongSports_Picture_front.jpg", "http://www.vectronicscollections.org/consoles/images/atari2600/paddles.jpg", "https://dustyconsoles.files.wordpress.com/2013/02/fairchild-channel-f.png", "http://www.davesclassicarcade.com/consoles/telstaralpha.JPG", "https://s-media-cache-ak0.pinimg.com/564x/ee/f1/47/eef147fa8b2a737b714ae9e3d5377411.jpg", "https://upload.wikimedia.org/wikipedia/commons/f/f1/Ping-Pong_2.jpg", "https://dustyconsoles.files.wordpress.com/2013/01/img_0740.jpg" ] module.exports = (robot) -> robot.hear /pong/i, (msg) -> msg.send msg.random pong
true
# Description: # Display's a pong image # # Dependencies: # None # # Configuration: # None # # Commands: # pong - Display a pong image # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> pong = [ "http://img.shroom.net/pong.jpg", "http://media.moddb.com/cache/images/mods/1/8/7707/thumb_620x2000/50085.jpg", "https://lh4.ggpht.com/_RzlKPjvg-AmeM5SlDV4HNtpiGpkt7rxiR_bioIGtM2tfYcRa03_61hSGTKWf0DKJQ=h900", "http://www.game-gt.com/images/pongflash.jpg", "http://pongmuseum.com/history/_picts/atari/pong_cabbig-web.jpg", "http://thedoteaters.com/tde/wp-content/uploads/2013/03/pong-winnerIV.jpg", "http://www.obsolete-tears.com/photos/Sears-Pong-Sports-IV-gp.jpg", "https://atariage.com/2600/carts/c_Sears_PongSports_Picture_front.jpg", "http://www.vectronicscollections.org/consoles/images/atari2600/paddles.jpg", "https://dustyconsoles.files.wordpress.com/2013/02/fairchild-channel-f.png", "http://www.davesclassicarcade.com/consoles/telstaralpha.JPG", "https://s-media-cache-ak0.pinimg.com/564x/ee/f1/47/eef147fa8b2a737b714ae9e3d5377411.jpg", "https://upload.wikimedia.org/wikipedia/commons/f/f1/Ping-Pong_2.jpg", "https://dustyconsoles.files.wordpress.com/2013/01/img_0740.jpg" ] module.exports = (robot) -> robot.hear /pong/i, (msg) -> msg.send msg.random pong
[ { "context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\n{File, Emitter, CompositeD", "end": 35, "score": 0.9997671246528625, "start": 21, "tag": "NAME", "value": "Jesse Grosjean" } ]
atom/packages/foldingtext-for-atom/lib/core/outline.coffee
prookie/dotfiles-1
0
# Copyright (c) 2015 Jesse Grosjean. All rights reserved. {File, Emitter, CompositeDisposable} = require 'atom' ItemSerializer = require './item-serializer' UndoManager = require './undo-manager' Constants = require './constants' ItemPath = require './item-path' Mutation = require './mutation' UrlUtil = require './url-util' shortid = require './shortid' _ = require 'underscore-plus' assert = require 'assert' Item = require './item' path = require 'path' fs = require 'fs' Q = require 'q' # Essential: A mutable outline of {Item}s. # # Use outlines to create new items, find existing items, and watch for changes # in items. Outlines also coordinate loading and saving items. # # Internally a {HTMLDocument} is used to store the underlying outline data. # You should never modify the content of this HTMLDocument directly, but you # can query it using {::evaluateXPath}. The structure of this document is # described in [FoldingText Markup Language](http://jessegrosjean.gitbooks.io # /foldingtext-for-atom-user-s-guide/content/appendix_b_file_format.html). # # ## Examples # # Group multiple changes: # # ```coffeescript # outline.beginUpdates() # root = outline.root # root.appendChild outline.createItem() # root.appendChild outline.createItem() # root.firstChild.bodyText = 'first' # root.lastChild.bodyText = 'last' # outline.endUpdates() # ``` # # Watch for outline changes: # # ```coffeescript # disposable = outline.onDidChange (mutations) -> # for mutation in mutations # switch mutation.type # when Mutation.ATTRIBUTE_CHANGED # console.log mutation.attributeName # when Mutation.BODT_TEXT_CHANGED # console.log mutation.target.bodyText # when Mutation.CHILDREN_CHANGED # console.log mutation.addedItems # console.log mutation.removedItems # ``` # # Use XPath to list all items with bold text: # # ```coffeescript # for each in outline.getItemsForXPath('//b') # console.log each # ``` class Outline root: null refcount: 0 changeCount: 0 undoSubscriptions: null updateCount: 0 updateCallbacks: null updateMutations: null coalescingMutation: null stoppedChangingDelay: 300 stoppedChangingTimeout: null file: null fileMimeType: null fileConflict: false fileSubscriptions: null loadOptions: null ### Section: Construction ### # Public: Create a new outline. constructor: (options) -> @id = shortid() @outlineStore = @createOutlineStore() rootElement = @outlineStore.getElementById Constants.RootID @loadingLIUsedIDs = {} @root = @createItem null, rootElement @loadingLIUsedIDs = null @undoManager = undoManager = new UndoManager @emitter = new Emitter @loaded = false @loadOptions = {} @undoSubscriptions = new CompositeDisposable @undoSubscriptions.add undoManager.onDidCloseUndoGroup => unless undoManager.isUndoing or undoManager.isRedoing @changeCount++ @scheduleModifiedEvents() @undoSubscriptions.add undoManager.onWillUndo => @breakUndoCoalescing() @undoSubscriptions.add undoManager.onDidUndo => @changeCount-- @breakUndoCoalescing() @scheduleModifiedEvents() @undoSubscriptions.add undoManager.onWillRedo => @breakUndoCoalescing() @undoSubscriptions.add undoManager.onDidRedo => @changeCount++ @breakUndoCoalescing() @scheduleModifiedEvents() @setPath(options.filePath) if options?.filePath @load() if options?.load createOutlineStore: (outlineStore) -> outlineStore = document.implementation.createHTMLDocument() rootUL = outlineStore.createElement('ul') rootUL.id = Constants.RootID outlineStore.documentElement.lastChild.appendChild(rootUL) outlineStore ### Section: Finding Outlines ### # Public: Read-only unique (not persistent) {String} outline ID. id: null @outlines = [] # Retrieves all open {Outlines}s. # # Returns an {Array} of {Outlines}s. @getOutlines: -> @outlines.slice() # Public: Returns existing {Outline} with the given outline id. # # - `id` {String} outline id. @getOutlineForID: (id) -> for each in @outlines if each.id is id return each # Given a file path, this retrieves or creates a new {Outline}. # # - `filePath` {String} outline file path. # - `createIfNeeded` (optional) {Boolean} create and return a new outline if can't find match. # # Returns a promise that resolves to the {Outline}. @getOutlineForPath: (filePath, createIfNeeded=true) -> absoluteFilePath = atom.project.resolvePath(filePath) for each in @outlines if each.getPath() is absoluteFilePath return Q(each) if createIfNeeded Q(@buildOutline(absoluteFilePath)) @getOutlineForPathSync: (filePath, createIfNeeded=true) -> absoluteFilePath = atom.project.resolvePath(filePath) for each in @outlines if each.getPath() is absoluteFilePath return each if createIfNeeded @buildOutlineSync(absoluteFilePath) @buildOutline: (absoluteFilePath) -> outline = new Outline({filePath: absoluteFilePath}) @addOutline(outline) outline.load() .then((outline) -> outline) .catch (error) -> atom.confirm message: "Could not open '#{outline.getTitle()}'" detailedMessage: "While trying to load encountered the following problem: #{error.name} – #{error.message}" outline.destroy() @buildOutlineSync: (absoluteFilePath) -> outline = new Outline({filePath: absoluteFilePath}) @addOutline(outline) outline.loadSync() outline @addOutline: (outline, options={}) -> @addOutlineAtIndex(outline, @outlines.length, options) @subscribeToOutline(outline) @addOutlineAtIndex: (outline, index, options={}) -> @outlines.splice(index, 0, outline) @subscribeToOutline(outline) outline @removeOutline: (outline) -> index = @outlines.indexOf(outline) @removeOutlineAtIndex(index) unless index is -1 @removeOutlineAtIndex: (index, options={}) -> [outline] = @outlines.splice(index, 1) outline?.destroy() @subscribeToOutline: (outline) -> outline.onDidDestroy => @removeOutline(outline) outline.onWillThrowWatchError ({error, handle}) -> handle() atom.notifications.addWarning """ Unable to read file after file `#{error.eventType}` event. Make sure you have permission to access `#{outline.getPath()}`. """, detail: error.message dismissable: true ### Section: Event Subscription ### # Public: Invoke the given callback synchronously _before_ the outline # changes. # # Because observers are invoked synchronously, it's important not to perform # any expensive operations via this method. # # * `callback` {Function} to be called when the outline will change. # * `mutation` {Mutation} describing the change. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onWillChange: (callback) -> @emitter.on 'will-change', callback # Public: Invoke the given callback when the outline changes. # # See {Outline} Examples for an example of subscribing to this event. # # - `callback` {Function} to be called when the outline changes. # - `mutations` {Array} of {Mutation}s describing the changes. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChange: (callback) -> @emitter.on 'did-change', callback onDidStopChanging: (callback) -> @emitter.on 'did-stop-changing', callback # Public: Invoke the given callback when the in-memory contents of the # outline become in conflict with the contents of the file on disk. # # - `callback` {Function} to be called when the outline enters conflict. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidConflict: (callback) -> @emitter.on 'did-conflict', callback # Public: Invoke the given callback when the value of {::isModified} changes. # # - `callback` {Function} to be called when {::isModified} changes. # - `modified` {Boolean} indicating whether the outline is modified. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChangeModified: (callback) -> @emitter.on 'did-change-modified', callback # Public: Invoke the given callback when the value of {::getPath} changes. # # - `callback` {Function} to be called when the path changes. # - `path` {String} representing the outline's current path on disk. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChangePath: (callback) -> @emitter.on 'did-change-path', callback # Public: Invoke the given callback before the outline is saved to disk. # # - `callback` {Function} to be called before the outline is saved. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onWillSave: (callback) -> @emitter.on 'will-save', callback # Public: Invoke the given callback after the outline is saved to disk. # # - `callback` {Function} to be called after the outline is saved. # - `event` {Object} with the following keys: # - `path` The path to which the outline was saved. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidSave: (callback) -> @emitter.on 'did-save', callback # Public: Invoke the given callback after the file backing the outline is # deleted. # # * `callback` {Function} to be called after the outline is deleted. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidDelete: (callback) -> @emitter.on 'did-delete', callback # Public: Invoke the given callback before the outline is reloaded from the # contents of its file on disk. # # - `callback` {Function} to be called before the outline is reloaded. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onWillReload: (callback) -> @emitter.on 'will-reload', callback # Public: Invoke the given callback after the outline is reloaded from the # contents of its file on disk. # # - `callback` {Function} to be called after the outline is reloaded. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidReload: (callback) -> @emitter.on 'did-reload', callback # Public: Invoke the given callback when the outline is destroyed. # # - `callback` {Function} to be called when the outline is destroyed. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidDestroy: (callback) -> @emitter.on 'did-destroy', callback # Public: Invoke the given callback when there is an error in watching the # file. # # * `callback` {Function} callback # * `errorObject` {Object} # * `error` {Object} the error object # * `handle` {Function} call this to indicate you have handled the error. # The error will not be thrown if this function is called. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onWillThrowWatchError: (callback) -> @emitter.on 'will-throw-watch-error', callback getStoppedChangingDelay: -> @stoppedChangingDelay ### Section: Reading Items ### # Public: Returns an {Array} of all {Item}s in the outline (except the # root) in outline order. getItems: -> @root.descendants isEmpty: -> firstChild = @root.firstChild not firstChild or (not firstChild.nextItem and firstChild.bodyText.length is 0) # Public: Returns {Item} for given id. # # - `id` {String} id. getItemForID: (id) -> @outlineStore.getElementById(id)?._item # Public: Returns {Array} of {Item}s for given {Array} of ids. # # - `ids` {Array} of ids. getItemsForIDs: (ids) -> return [] unless ids items = [] for each in ids each = @getItemForID each if each items.push each items ### Section: Creating Items ### # Public: Create a new item. The new item is owned by this outline, but is # not yet inserted into it so it won't be visible until you insert it. # # - `text` (optional) {String} or {AttributedString}. createItem: (text, LIOrID, remapIDCallback) -> if LIOrID and _.isString(LIOrID) LI = @createStoreLI() LI.id = LIOrID LIOrID = LI new Item(@, text, LIOrID or @createStoreLI(), remapIDCallback) cloneItem: (item, remapIDCallback) -> assert.ok(not item.isRoot, 'Can not clone root') assert.ok(item.outline is @, 'Item must be owned by this outline') @createItem(null, item._liOrRootUL.cloneNode(true), remapIDCallback) # Public: Creates a copy of an {Item} from an external outline that can be # inserted into the current outline. # # - `item` {Item} to import. # # Returns {Item} copy. importItem: (item) -> assert.ok(not item.isRoot, 'Can not import root item') assert.ok(item.outline isnt @, 'Item must not be owned by this outline') @createItem(null, @outlineStore.importNode(item._liOrRootUL, true)) ### Section: Insert & Remove Items ### # Not sure about this method... I think they are being used to handle moving # items from one outline to another... is that needed? TODO removeItemsFromParents: (items) -> siblings = [] prev = null for each in items if not prev or prev.nextSibling is each siblings.push(each) else @removeSiblingsFromParent(siblings) siblings = [each] prev = each if siblings.length @removeSiblingsFromParent(siblings); removeSiblingsFromParent: (siblings) -> return unless siblings.length firstSibling = siblings[0] outline = firstSibling.outline parent = firstSibling.parent return unless parent nextSibling = siblings[siblings.length - 1].nextSibling isInOutline = firstSibling.isInOutline undoManager = outline.undoManager if isInOutline if undoManager.isUndoRegistrationEnabled() undoManager.registerUndoOperation -> # This seems especially wrong? should now only have mutations on the # undo stack parent.insertChildrenBefore(siblings, nextSibling) undoManager.disableUndoRegistration() outline.beginUpdates() for each in siblings parent.removeChild each if isInOutline undoManager.enableUndoRegistration() outline.endUpdates() ### Section: Querying Items ### # Pubilc: Evaluate the item path starting with the root item and return all # matching items. # # - `itemPath` {String} itempath expression # - `contextItem` (optional) # # Returns an {Array} of matching {Item}s. evaluateItemPath: (itemPath, contextItem, options) -> options ?= {} options.root ?= @root contextItem ?= @root ItemPath.evaluate itemPath, contextItem, options # Public: XPath query internal HTML structure. # # - `xpathExpression` {String} xpath expression # - `contextItem` (optional) # - `namespaceResolver` (optional) # - `resultType` (optional) # - `result` (optional) # # This query evaluates on the underlying HTMLDocument. Please refer to the # standard [document.evaluate](https://developer.mozilla.org/en- # US/docs/Web/API/document.evaluate) documentation for details. # # Returns an [XPathResult](https://developer.mozilla.org/en- # US/docs/XPathResult) based on an [XPath](https://developer.mozilla.org/en- # US/docs/Web/XPath) expression and other given parameters. evaluateXPath: (xpathExpression, contextItem, namespaceResolver, resultType, result) -> contextItem ?= @root @outlineStore.evaluate( xpathExpression, contextItem._liOrRootUL, namespaceResolver, resultType, result ) # Public: XPath query internal HTML structure for matching {Items}. # # Items are considered to match if they, or a node contained in their body # text, matches the XPath. # # - `xpathExpression` {String} xpath expression # - `contextItem` (optional) {String} # - `namespaceResolver` (optional) {String} # # Returns an {Array} of all {Item} matching the # [XPath](https://developer.mozilla.org/en-US/docs/Web/XPath) expression. getItemsForXPath: (xpathExpression, contextItem, namespaceResolver, exceptionCallback) -> try xpathResult = @evaluateXPath( xpathExpression, contextItem, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE ) each = xpathResult.iterateNext() lastItem = undefined items = [] while each while each and not each._item each = each.parentNode if each eachItem = each._item if eachItem isnt lastItem items.push(eachItem) lastItem = eachItem each = xpathResult.iterateNext() return items catch error exceptionCallback?(error) [] ### Section: Grouping Changes ### # Public: Returns {Boolean} true if outline is updating. isUpdating: -> @updateCount isnt 0 # Public: Begin grouping changes. Must later call {::endUpdates} to balance # this call. beginUpdates: -> if ++@updateCount is 1 @updateCallbacks = [] @updateMutations = [] breakUndoCoalescing: -> @coalescingMutation = null recoredUpdateMutation: (mutation) -> @updateMutations.push mutation.copy() if @undoManager.isUndoing or @undoManager.isUndoing @breakUndoCoalescing() if @coalescingMutation and @coalescingMutation.coalesce(mutation) metadata = @undoManager.getUndoGroupMetadata() undoSelection = metadata.undoSelection if undoSelection and @coalescingMutation.type is Mutation.BODT_TEXT_CHANGED # Update the undo selection to match coalescingMutation undoSelection.anchorOffset = @coalescingMutation.insertedTextLocation undoSelection.startOffset = @coalescingMutation.insertedTextLocation undoSelection.focusOffset = @coalescingMutation.insertedTextLocation + @coalescingMutation.replacedText.length undoSelection.endOffset = @coalescingMutation.insertedTextLocation + @coalescingMutation.replacedText.length else @undoManager.registerUndoOperation mutation @coalescingMutation = mutation # Public: End grouping changes. Must call to balance a previous # {::beginUpdates} call. # # - `callback` (optional) Callback is called when outline finishes updating. endUpdates: (callback) -> @updateCallbacks.push(callback) if callback if --@updateCount is 0 updateMutations = @updateMutations @updateMutations = null if updateMutations.length > 0 @conflict = false if @conflict and not @isModified() @emitter.emit('did-change', updateMutations) @scheduleModifiedEvents() updateCallbacks = @updateCallbacks @updateCallbacks = null for each in updateCallbacks each() ### Section: Undo ### # Essential: Undo the last change. undo: -> @undoManager.undo() # Essential: Redo the last change. redo: -> @undoManager.redo() ### Section: File Details ### # Public: Determine if the outline has changed since it was loaded. # # If the outline is unsaved, always returns `true` unless the outline is # empty. # # Returns a {Boolean}. isModified: -> return false unless @loaded if @file @changeCount isnt 0 #if @file.existsSync() # @getText() isnt @cachedDiskContents #else # @wasModifiedBeforeRemove ? not @isEmpty() else not @isEmpty() # Public: Determine if the in-memory contents of the outline conflict with the # on-disk contents of its associated file. # # Returns a {Boolean}. isInConflict: -> @conflict getMimeType: -> unless @fileMimeType @fileMimeType = ItemSerializer.getMimeTypeForURI(@getPath()) or Constants.FTMLMimeType @fileMimeType setMimeType: (mimeType) -> unless @getMimeType() is mimeType @fileMimeType = mimeType # Public: Get the path of the associated file. # # Returns a {String}. getPath: -> @file?.getPath() # Public: Set the path for the outlines's associated file. # # - `filePath` A {String} representing the new file path setPath: (filePath) -> return if filePath is @getPath() if filePath @file = new File(filePath) @file.setEncoding('utf8') @subscribeToFile() else @file = null @emitter.emit 'did-change-path', @getPath() @setMimeType(null) getURI: (options) -> @getPath() # Public: Get an href to this outline. # # * `options` (optional) The {Object} with URL options (default: {}): # * `hoistedItem` An {Item} to hoist when opening the outline # * `query` A {String} item path to set when opening the outline. # * `expanded` An {Array} of items to expand when opening the outline. # * `selection` An {Object} with the selection to set when opening the outline. # * `focusItem` The focus {Item}. # * `focusOffset` The focus offset {Number}. # * `anchorItem` The anchor {Item}. # * `anchorOffset` The anchor offset {Number}. getFileURL: (options={}) -> urlOptions = {} hoistedItem = options.hoistedItem if hoistedItem and not hoistedItem.isRoot urlOptions.hash = hoistedItem.id if query = options.query urlOptions.query = query if expanded = options.expanded urlOptions.expanded = (each.id for each in expanded).join(',') if options.selection?.focusItem selection = options.selection focusItem = selection.focusItem focusOffset = selection.focusOffset ? undefined anchorItem = selection.anchorItem ? focusItem anchorOffset = selection.anchorOffset ? focusOffset urlOptions.selection = "#{focusItem?.id},#{focusOffset},#{anchorItem?.id},#{anchorOffset}" if @getPath() UrlUtil.getFileURLFromPathnameAndOptions(@getPath(), urlOptions) else # Hack... in case where outline has no path can't return file:// url # since they require and absolute path. So instead just return the # encoded options. UrlUtil.getHREFFromFileURLs('file:///', 'file:///', urlOptions) getBaseName: -> @file?.getBaseName() or 'Untitled' getTitle: -> if sessionPath = @getPath() path.basename(sessionPath) else 'Untitled' getLongTitle: -> if sessionPath = @getPath() fileName = path.basename(sessionPath) directory = atom.project.relativize(path.dirname(sessionPath)) directory = if directory.length > 0 then directory else path.basename(path.dirname(sessionPath)) "#{fileName} - #{directory}" else 'Untitled' ### Section: File Content Operations ### # Public: Save the outline. save: (editor) -> @saveAs @getPath(), editor # Public: Save the outline at a specific path. # # - `filePath` The path to save at. saveAs: (filePath, editor) -> unless filePath then throw new Error("Can't save outline with no file path") @emitter.emit 'will-save', {path: filePath} @setPath(filePath) text = ItemSerializer.serializeItems(@root.children, editor, @getMimeType()) @file.writeSync text @cachedDiskContents = text @conflict = false @changeCount = 0 @emitModifiedStatusChanged(false) @emitter.emit 'did-save', {path: filePath} # Public: Reload the outline's contents from disk. # # Sets the outline's content to the cached disk contents. reload: -> @emitter.emit 'will-reload' @beginUpdates() @root.removeChildren(@root.children) if @cachedDiskContents items = ItemSerializer.deserializeItems(@cachedDiskContents, this, @getMimeType()) @loadOptions = items.loadOptions for each in items @root.appendChild(each) @endUpdates() @changeCount = 0 @emitModifiedStatusChanged(false) @emitter.emit 'did-reload' updateCachedDiskContentsSync: (pathOverride) -> if pathOverride @cachedDiskContents = fs.readFileSync(pathOverride, 'utf8') else @cachedDiskContents = @file?.readSync() ? "" updateCachedDiskContents: (flushCache=false, callback) -> Q(@file?.read(flushCache) ? "").then (contents) => @cachedDiskContents = contents callback?() ### Section: Private Utility Methods ### createStoreLI: -> outlineStore = @outlineStore li = outlineStore.createElement('LI') li.appendChild(outlineStore.createElement('P')) li nextOutlineUniqueItemID: (candidateID) -> loadingLIUsedIDs = @loadingLIUsedIDs while true id = candidateID or shortid() if loadingLIUsedIDs and not loadingLIUsedIDs[id] loadingLIUsedIDs[id] = true return id else if not @outlineStore.getElementById(id) return id else candidateID = null loadSync: (pathOverride) -> @updateCachedDiskContentsSync(pathOverride) @finishLoading() load: -> @updateCachedDiskContents().then => @finishLoading() finishLoading: -> if @isAlive() @loaded = true @reload() @undoManager.removeAllActions() this destroy: -> unless @destroyed Outline.removeOutline this @cancelStoppedChangingTimeout() @undoSubscriptions?.dispose() @fileSubscriptions?.dispose() @destroyed = true @emitter.emit 'did-destroy' isAlive: -> not @destroyed isDestroyed: -> @destroyed isRetained: -> @refcount > 0 retain: -> @refcount++ this release: (editorID) -> @refcount-- for each in @getItems() each.setUserData editorID, undefined @destroy() unless @isRetained() this subscribeToFile: -> @fileSubscriptions?.dispose() @fileSubscriptions = new CompositeDisposable @fileSubscriptions.add @file.onDidChange => @conflict = true if @isModified() previousContents = @cachedDiskContents # Synchronously update the disk contents because the {File} has already # cached them. If the contents updated asynchrounously multiple # `conlict` events could trigger for the same disk contents. @updateCachedDiskContentsSync() return if previousContents is @cachedDiskContents if @conflict @emitter.emit 'did-conflict' else @reload() @fileSubscriptions.add @file.onDidDelete => modified = isModified() @wasModifiedBeforeRemove = modified @emitter.emit 'did-delete' if modified @updateCachedDiskContents() else @destroy() @fileSubscriptions.add @file.onDidRename => @emitter.emit 'did-change-path', @getPath() @fileSubscriptions.add @file.onWillThrowWatchError (errorObject) => @emitter.emit 'will-throw-watch-error', errorObject hasMultipleEditors: -> @refcount > 1 cancelStoppedChangingTimeout: -> clearTimeout(@stoppedChangingTimeout) if @stoppedChangingTimeout scheduleModifiedEvents: -> @cancelStoppedChangingTimeout() stoppedChangingCallback = => @stoppedChangingTimeout = null modifiedStatus = @isModified() @emitter.emit 'did-stop-changing' @emitModifiedStatusChanged(modifiedStatus) @stoppedChangingTimeout = setTimeout( stoppedChangingCallback, @stoppedChangingDelay ) emitModifiedStatusChanged: (modifiedStatus) -> return if modifiedStatus is @previousModifiedStatus @previousModifiedStatus = modifiedStatus @emitter.emit 'did-change-modified', modifiedStatus module.exports = Outline
50146
# Copyright (c) 2015 <NAME>. All rights reserved. {File, Emitter, CompositeDisposable} = require 'atom' ItemSerializer = require './item-serializer' UndoManager = require './undo-manager' Constants = require './constants' ItemPath = require './item-path' Mutation = require './mutation' UrlUtil = require './url-util' shortid = require './shortid' _ = require 'underscore-plus' assert = require 'assert' Item = require './item' path = require 'path' fs = require 'fs' Q = require 'q' # Essential: A mutable outline of {Item}s. # # Use outlines to create new items, find existing items, and watch for changes # in items. Outlines also coordinate loading and saving items. # # Internally a {HTMLDocument} is used to store the underlying outline data. # You should never modify the content of this HTMLDocument directly, but you # can query it using {::evaluateXPath}. The structure of this document is # described in [FoldingText Markup Language](http://jessegrosjean.gitbooks.io # /foldingtext-for-atom-user-s-guide/content/appendix_b_file_format.html). # # ## Examples # # Group multiple changes: # # ```coffeescript # outline.beginUpdates() # root = outline.root # root.appendChild outline.createItem() # root.appendChild outline.createItem() # root.firstChild.bodyText = 'first' # root.lastChild.bodyText = 'last' # outline.endUpdates() # ``` # # Watch for outline changes: # # ```coffeescript # disposable = outline.onDidChange (mutations) -> # for mutation in mutations # switch mutation.type # when Mutation.ATTRIBUTE_CHANGED # console.log mutation.attributeName # when Mutation.BODT_TEXT_CHANGED # console.log mutation.target.bodyText # when Mutation.CHILDREN_CHANGED # console.log mutation.addedItems # console.log mutation.removedItems # ``` # # Use XPath to list all items with bold text: # # ```coffeescript # for each in outline.getItemsForXPath('//b') # console.log each # ``` class Outline root: null refcount: 0 changeCount: 0 undoSubscriptions: null updateCount: 0 updateCallbacks: null updateMutations: null coalescingMutation: null stoppedChangingDelay: 300 stoppedChangingTimeout: null file: null fileMimeType: null fileConflict: false fileSubscriptions: null loadOptions: null ### Section: Construction ### # Public: Create a new outline. constructor: (options) -> @id = shortid() @outlineStore = @createOutlineStore() rootElement = @outlineStore.getElementById Constants.RootID @loadingLIUsedIDs = {} @root = @createItem null, rootElement @loadingLIUsedIDs = null @undoManager = undoManager = new UndoManager @emitter = new Emitter @loaded = false @loadOptions = {} @undoSubscriptions = new CompositeDisposable @undoSubscriptions.add undoManager.onDidCloseUndoGroup => unless undoManager.isUndoing or undoManager.isRedoing @changeCount++ @scheduleModifiedEvents() @undoSubscriptions.add undoManager.onWillUndo => @breakUndoCoalescing() @undoSubscriptions.add undoManager.onDidUndo => @changeCount-- @breakUndoCoalescing() @scheduleModifiedEvents() @undoSubscriptions.add undoManager.onWillRedo => @breakUndoCoalescing() @undoSubscriptions.add undoManager.onDidRedo => @changeCount++ @breakUndoCoalescing() @scheduleModifiedEvents() @setPath(options.filePath) if options?.filePath @load() if options?.load createOutlineStore: (outlineStore) -> outlineStore = document.implementation.createHTMLDocument() rootUL = outlineStore.createElement('ul') rootUL.id = Constants.RootID outlineStore.documentElement.lastChild.appendChild(rootUL) outlineStore ### Section: Finding Outlines ### # Public: Read-only unique (not persistent) {String} outline ID. id: null @outlines = [] # Retrieves all open {Outlines}s. # # Returns an {Array} of {Outlines}s. @getOutlines: -> @outlines.slice() # Public: Returns existing {Outline} with the given outline id. # # - `id` {String} outline id. @getOutlineForID: (id) -> for each in @outlines if each.id is id return each # Given a file path, this retrieves or creates a new {Outline}. # # - `filePath` {String} outline file path. # - `createIfNeeded` (optional) {Boolean} create and return a new outline if can't find match. # # Returns a promise that resolves to the {Outline}. @getOutlineForPath: (filePath, createIfNeeded=true) -> absoluteFilePath = atom.project.resolvePath(filePath) for each in @outlines if each.getPath() is absoluteFilePath return Q(each) if createIfNeeded Q(@buildOutline(absoluteFilePath)) @getOutlineForPathSync: (filePath, createIfNeeded=true) -> absoluteFilePath = atom.project.resolvePath(filePath) for each in @outlines if each.getPath() is absoluteFilePath return each if createIfNeeded @buildOutlineSync(absoluteFilePath) @buildOutline: (absoluteFilePath) -> outline = new Outline({filePath: absoluteFilePath}) @addOutline(outline) outline.load() .then((outline) -> outline) .catch (error) -> atom.confirm message: "Could not open '#{outline.getTitle()}'" detailedMessage: "While trying to load encountered the following problem: #{error.name} – #{error.message}" outline.destroy() @buildOutlineSync: (absoluteFilePath) -> outline = new Outline({filePath: absoluteFilePath}) @addOutline(outline) outline.loadSync() outline @addOutline: (outline, options={}) -> @addOutlineAtIndex(outline, @outlines.length, options) @subscribeToOutline(outline) @addOutlineAtIndex: (outline, index, options={}) -> @outlines.splice(index, 0, outline) @subscribeToOutline(outline) outline @removeOutline: (outline) -> index = @outlines.indexOf(outline) @removeOutlineAtIndex(index) unless index is -1 @removeOutlineAtIndex: (index, options={}) -> [outline] = @outlines.splice(index, 1) outline?.destroy() @subscribeToOutline: (outline) -> outline.onDidDestroy => @removeOutline(outline) outline.onWillThrowWatchError ({error, handle}) -> handle() atom.notifications.addWarning """ Unable to read file after file `#{error.eventType}` event. Make sure you have permission to access `#{outline.getPath()}`. """, detail: error.message dismissable: true ### Section: Event Subscription ### # Public: Invoke the given callback synchronously _before_ the outline # changes. # # Because observers are invoked synchronously, it's important not to perform # any expensive operations via this method. # # * `callback` {Function} to be called when the outline will change. # * `mutation` {Mutation} describing the change. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onWillChange: (callback) -> @emitter.on 'will-change', callback # Public: Invoke the given callback when the outline changes. # # See {Outline} Examples for an example of subscribing to this event. # # - `callback` {Function} to be called when the outline changes. # - `mutations` {Array} of {Mutation}s describing the changes. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChange: (callback) -> @emitter.on 'did-change', callback onDidStopChanging: (callback) -> @emitter.on 'did-stop-changing', callback # Public: Invoke the given callback when the in-memory contents of the # outline become in conflict with the contents of the file on disk. # # - `callback` {Function} to be called when the outline enters conflict. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidConflict: (callback) -> @emitter.on 'did-conflict', callback # Public: Invoke the given callback when the value of {::isModified} changes. # # - `callback` {Function} to be called when {::isModified} changes. # - `modified` {Boolean} indicating whether the outline is modified. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChangeModified: (callback) -> @emitter.on 'did-change-modified', callback # Public: Invoke the given callback when the value of {::getPath} changes. # # - `callback` {Function} to be called when the path changes. # - `path` {String} representing the outline's current path on disk. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChangePath: (callback) -> @emitter.on 'did-change-path', callback # Public: Invoke the given callback before the outline is saved to disk. # # - `callback` {Function} to be called before the outline is saved. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onWillSave: (callback) -> @emitter.on 'will-save', callback # Public: Invoke the given callback after the outline is saved to disk. # # - `callback` {Function} to be called after the outline is saved. # - `event` {Object} with the following keys: # - `path` The path to which the outline was saved. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidSave: (callback) -> @emitter.on 'did-save', callback # Public: Invoke the given callback after the file backing the outline is # deleted. # # * `callback` {Function} to be called after the outline is deleted. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidDelete: (callback) -> @emitter.on 'did-delete', callback # Public: Invoke the given callback before the outline is reloaded from the # contents of its file on disk. # # - `callback` {Function} to be called before the outline is reloaded. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onWillReload: (callback) -> @emitter.on 'will-reload', callback # Public: Invoke the given callback after the outline is reloaded from the # contents of its file on disk. # # - `callback` {Function} to be called after the outline is reloaded. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidReload: (callback) -> @emitter.on 'did-reload', callback # Public: Invoke the given callback when the outline is destroyed. # # - `callback` {Function} to be called when the outline is destroyed. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidDestroy: (callback) -> @emitter.on 'did-destroy', callback # Public: Invoke the given callback when there is an error in watching the # file. # # * `callback` {Function} callback # * `errorObject` {Object} # * `error` {Object} the error object # * `handle` {Function} call this to indicate you have handled the error. # The error will not be thrown if this function is called. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onWillThrowWatchError: (callback) -> @emitter.on 'will-throw-watch-error', callback getStoppedChangingDelay: -> @stoppedChangingDelay ### Section: Reading Items ### # Public: Returns an {Array} of all {Item}s in the outline (except the # root) in outline order. getItems: -> @root.descendants isEmpty: -> firstChild = @root.firstChild not firstChild or (not firstChild.nextItem and firstChild.bodyText.length is 0) # Public: Returns {Item} for given id. # # - `id` {String} id. getItemForID: (id) -> @outlineStore.getElementById(id)?._item # Public: Returns {Array} of {Item}s for given {Array} of ids. # # - `ids` {Array} of ids. getItemsForIDs: (ids) -> return [] unless ids items = [] for each in ids each = @getItemForID each if each items.push each items ### Section: Creating Items ### # Public: Create a new item. The new item is owned by this outline, but is # not yet inserted into it so it won't be visible until you insert it. # # - `text` (optional) {String} or {AttributedString}. createItem: (text, LIOrID, remapIDCallback) -> if LIOrID and _.isString(LIOrID) LI = @createStoreLI() LI.id = LIOrID LIOrID = LI new Item(@, text, LIOrID or @createStoreLI(), remapIDCallback) cloneItem: (item, remapIDCallback) -> assert.ok(not item.isRoot, 'Can not clone root') assert.ok(item.outline is @, 'Item must be owned by this outline') @createItem(null, item._liOrRootUL.cloneNode(true), remapIDCallback) # Public: Creates a copy of an {Item} from an external outline that can be # inserted into the current outline. # # - `item` {Item} to import. # # Returns {Item} copy. importItem: (item) -> assert.ok(not item.isRoot, 'Can not import root item') assert.ok(item.outline isnt @, 'Item must not be owned by this outline') @createItem(null, @outlineStore.importNode(item._liOrRootUL, true)) ### Section: Insert & Remove Items ### # Not sure about this method... I think they are being used to handle moving # items from one outline to another... is that needed? TODO removeItemsFromParents: (items) -> siblings = [] prev = null for each in items if not prev or prev.nextSibling is each siblings.push(each) else @removeSiblingsFromParent(siblings) siblings = [each] prev = each if siblings.length @removeSiblingsFromParent(siblings); removeSiblingsFromParent: (siblings) -> return unless siblings.length firstSibling = siblings[0] outline = firstSibling.outline parent = firstSibling.parent return unless parent nextSibling = siblings[siblings.length - 1].nextSibling isInOutline = firstSibling.isInOutline undoManager = outline.undoManager if isInOutline if undoManager.isUndoRegistrationEnabled() undoManager.registerUndoOperation -> # This seems especially wrong? should now only have mutations on the # undo stack parent.insertChildrenBefore(siblings, nextSibling) undoManager.disableUndoRegistration() outline.beginUpdates() for each in siblings parent.removeChild each if isInOutline undoManager.enableUndoRegistration() outline.endUpdates() ### Section: Querying Items ### # Pubilc: Evaluate the item path starting with the root item and return all # matching items. # # - `itemPath` {String} itempath expression # - `contextItem` (optional) # # Returns an {Array} of matching {Item}s. evaluateItemPath: (itemPath, contextItem, options) -> options ?= {} options.root ?= @root contextItem ?= @root ItemPath.evaluate itemPath, contextItem, options # Public: XPath query internal HTML structure. # # - `xpathExpression` {String} xpath expression # - `contextItem` (optional) # - `namespaceResolver` (optional) # - `resultType` (optional) # - `result` (optional) # # This query evaluates on the underlying HTMLDocument. Please refer to the # standard [document.evaluate](https://developer.mozilla.org/en- # US/docs/Web/API/document.evaluate) documentation for details. # # Returns an [XPathResult](https://developer.mozilla.org/en- # US/docs/XPathResult) based on an [XPath](https://developer.mozilla.org/en- # US/docs/Web/XPath) expression and other given parameters. evaluateXPath: (xpathExpression, contextItem, namespaceResolver, resultType, result) -> contextItem ?= @root @outlineStore.evaluate( xpathExpression, contextItem._liOrRootUL, namespaceResolver, resultType, result ) # Public: XPath query internal HTML structure for matching {Items}. # # Items are considered to match if they, or a node contained in their body # text, matches the XPath. # # - `xpathExpression` {String} xpath expression # - `contextItem` (optional) {String} # - `namespaceResolver` (optional) {String} # # Returns an {Array} of all {Item} matching the # [XPath](https://developer.mozilla.org/en-US/docs/Web/XPath) expression. getItemsForXPath: (xpathExpression, contextItem, namespaceResolver, exceptionCallback) -> try xpathResult = @evaluateXPath( xpathExpression, contextItem, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE ) each = xpathResult.iterateNext() lastItem = undefined items = [] while each while each and not each._item each = each.parentNode if each eachItem = each._item if eachItem isnt lastItem items.push(eachItem) lastItem = eachItem each = xpathResult.iterateNext() return items catch error exceptionCallback?(error) [] ### Section: Grouping Changes ### # Public: Returns {Boolean} true if outline is updating. isUpdating: -> @updateCount isnt 0 # Public: Begin grouping changes. Must later call {::endUpdates} to balance # this call. beginUpdates: -> if ++@updateCount is 1 @updateCallbacks = [] @updateMutations = [] breakUndoCoalescing: -> @coalescingMutation = null recoredUpdateMutation: (mutation) -> @updateMutations.push mutation.copy() if @undoManager.isUndoing or @undoManager.isUndoing @breakUndoCoalescing() if @coalescingMutation and @coalescingMutation.coalesce(mutation) metadata = @undoManager.getUndoGroupMetadata() undoSelection = metadata.undoSelection if undoSelection and @coalescingMutation.type is Mutation.BODT_TEXT_CHANGED # Update the undo selection to match coalescingMutation undoSelection.anchorOffset = @coalescingMutation.insertedTextLocation undoSelection.startOffset = @coalescingMutation.insertedTextLocation undoSelection.focusOffset = @coalescingMutation.insertedTextLocation + @coalescingMutation.replacedText.length undoSelection.endOffset = @coalescingMutation.insertedTextLocation + @coalescingMutation.replacedText.length else @undoManager.registerUndoOperation mutation @coalescingMutation = mutation # Public: End grouping changes. Must call to balance a previous # {::beginUpdates} call. # # - `callback` (optional) Callback is called when outline finishes updating. endUpdates: (callback) -> @updateCallbacks.push(callback) if callback if --@updateCount is 0 updateMutations = @updateMutations @updateMutations = null if updateMutations.length > 0 @conflict = false if @conflict and not @isModified() @emitter.emit('did-change', updateMutations) @scheduleModifiedEvents() updateCallbacks = @updateCallbacks @updateCallbacks = null for each in updateCallbacks each() ### Section: Undo ### # Essential: Undo the last change. undo: -> @undoManager.undo() # Essential: Redo the last change. redo: -> @undoManager.redo() ### Section: File Details ### # Public: Determine if the outline has changed since it was loaded. # # If the outline is unsaved, always returns `true` unless the outline is # empty. # # Returns a {Boolean}. isModified: -> return false unless @loaded if @file @changeCount isnt 0 #if @file.existsSync() # @getText() isnt @cachedDiskContents #else # @wasModifiedBeforeRemove ? not @isEmpty() else not @isEmpty() # Public: Determine if the in-memory contents of the outline conflict with the # on-disk contents of its associated file. # # Returns a {Boolean}. isInConflict: -> @conflict getMimeType: -> unless @fileMimeType @fileMimeType = ItemSerializer.getMimeTypeForURI(@getPath()) or Constants.FTMLMimeType @fileMimeType setMimeType: (mimeType) -> unless @getMimeType() is mimeType @fileMimeType = mimeType # Public: Get the path of the associated file. # # Returns a {String}. getPath: -> @file?.getPath() # Public: Set the path for the outlines's associated file. # # - `filePath` A {String} representing the new file path setPath: (filePath) -> return if filePath is @getPath() if filePath @file = new File(filePath) @file.setEncoding('utf8') @subscribeToFile() else @file = null @emitter.emit 'did-change-path', @getPath() @setMimeType(null) getURI: (options) -> @getPath() # Public: Get an href to this outline. # # * `options` (optional) The {Object} with URL options (default: {}): # * `hoistedItem` An {Item} to hoist when opening the outline # * `query` A {String} item path to set when opening the outline. # * `expanded` An {Array} of items to expand when opening the outline. # * `selection` An {Object} with the selection to set when opening the outline. # * `focusItem` The focus {Item}. # * `focusOffset` The focus offset {Number}. # * `anchorItem` The anchor {Item}. # * `anchorOffset` The anchor offset {Number}. getFileURL: (options={}) -> urlOptions = {} hoistedItem = options.hoistedItem if hoistedItem and not hoistedItem.isRoot urlOptions.hash = hoistedItem.id if query = options.query urlOptions.query = query if expanded = options.expanded urlOptions.expanded = (each.id for each in expanded).join(',') if options.selection?.focusItem selection = options.selection focusItem = selection.focusItem focusOffset = selection.focusOffset ? undefined anchorItem = selection.anchorItem ? focusItem anchorOffset = selection.anchorOffset ? focusOffset urlOptions.selection = "#{focusItem?.id},#{focusOffset},#{anchorItem?.id},#{anchorOffset}" if @getPath() UrlUtil.getFileURLFromPathnameAndOptions(@getPath(), urlOptions) else # Hack... in case where outline has no path can't return file:// url # since they require and absolute path. So instead just return the # encoded options. UrlUtil.getHREFFromFileURLs('file:///', 'file:///', urlOptions) getBaseName: -> @file?.getBaseName() or 'Untitled' getTitle: -> if sessionPath = @getPath() path.basename(sessionPath) else 'Untitled' getLongTitle: -> if sessionPath = @getPath() fileName = path.basename(sessionPath) directory = atom.project.relativize(path.dirname(sessionPath)) directory = if directory.length > 0 then directory else path.basename(path.dirname(sessionPath)) "#{fileName} - #{directory}" else 'Untitled' ### Section: File Content Operations ### # Public: Save the outline. save: (editor) -> @saveAs @getPath(), editor # Public: Save the outline at a specific path. # # - `filePath` The path to save at. saveAs: (filePath, editor) -> unless filePath then throw new Error("Can't save outline with no file path") @emitter.emit 'will-save', {path: filePath} @setPath(filePath) text = ItemSerializer.serializeItems(@root.children, editor, @getMimeType()) @file.writeSync text @cachedDiskContents = text @conflict = false @changeCount = 0 @emitModifiedStatusChanged(false) @emitter.emit 'did-save', {path: filePath} # Public: Reload the outline's contents from disk. # # Sets the outline's content to the cached disk contents. reload: -> @emitter.emit 'will-reload' @beginUpdates() @root.removeChildren(@root.children) if @cachedDiskContents items = ItemSerializer.deserializeItems(@cachedDiskContents, this, @getMimeType()) @loadOptions = items.loadOptions for each in items @root.appendChild(each) @endUpdates() @changeCount = 0 @emitModifiedStatusChanged(false) @emitter.emit 'did-reload' updateCachedDiskContentsSync: (pathOverride) -> if pathOverride @cachedDiskContents = fs.readFileSync(pathOverride, 'utf8') else @cachedDiskContents = @file?.readSync() ? "" updateCachedDiskContents: (flushCache=false, callback) -> Q(@file?.read(flushCache) ? "").then (contents) => @cachedDiskContents = contents callback?() ### Section: Private Utility Methods ### createStoreLI: -> outlineStore = @outlineStore li = outlineStore.createElement('LI') li.appendChild(outlineStore.createElement('P')) li nextOutlineUniqueItemID: (candidateID) -> loadingLIUsedIDs = @loadingLIUsedIDs while true id = candidateID or shortid() if loadingLIUsedIDs and not loadingLIUsedIDs[id] loadingLIUsedIDs[id] = true return id else if not @outlineStore.getElementById(id) return id else candidateID = null loadSync: (pathOverride) -> @updateCachedDiskContentsSync(pathOverride) @finishLoading() load: -> @updateCachedDiskContents().then => @finishLoading() finishLoading: -> if @isAlive() @loaded = true @reload() @undoManager.removeAllActions() this destroy: -> unless @destroyed Outline.removeOutline this @cancelStoppedChangingTimeout() @undoSubscriptions?.dispose() @fileSubscriptions?.dispose() @destroyed = true @emitter.emit 'did-destroy' isAlive: -> not @destroyed isDestroyed: -> @destroyed isRetained: -> @refcount > 0 retain: -> @refcount++ this release: (editorID) -> @refcount-- for each in @getItems() each.setUserData editorID, undefined @destroy() unless @isRetained() this subscribeToFile: -> @fileSubscriptions?.dispose() @fileSubscriptions = new CompositeDisposable @fileSubscriptions.add @file.onDidChange => @conflict = true if @isModified() previousContents = @cachedDiskContents # Synchronously update the disk contents because the {File} has already # cached them. If the contents updated asynchrounously multiple # `conlict` events could trigger for the same disk contents. @updateCachedDiskContentsSync() return if previousContents is @cachedDiskContents if @conflict @emitter.emit 'did-conflict' else @reload() @fileSubscriptions.add @file.onDidDelete => modified = isModified() @wasModifiedBeforeRemove = modified @emitter.emit 'did-delete' if modified @updateCachedDiskContents() else @destroy() @fileSubscriptions.add @file.onDidRename => @emitter.emit 'did-change-path', @getPath() @fileSubscriptions.add @file.onWillThrowWatchError (errorObject) => @emitter.emit 'will-throw-watch-error', errorObject hasMultipleEditors: -> @refcount > 1 cancelStoppedChangingTimeout: -> clearTimeout(@stoppedChangingTimeout) if @stoppedChangingTimeout scheduleModifiedEvents: -> @cancelStoppedChangingTimeout() stoppedChangingCallback = => @stoppedChangingTimeout = null modifiedStatus = @isModified() @emitter.emit 'did-stop-changing' @emitModifiedStatusChanged(modifiedStatus) @stoppedChangingTimeout = setTimeout( stoppedChangingCallback, @stoppedChangingDelay ) emitModifiedStatusChanged: (modifiedStatus) -> return if modifiedStatus is @previousModifiedStatus @previousModifiedStatus = modifiedStatus @emitter.emit 'did-change-modified', modifiedStatus module.exports = Outline
true
# Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved. {File, Emitter, CompositeDisposable} = require 'atom' ItemSerializer = require './item-serializer' UndoManager = require './undo-manager' Constants = require './constants' ItemPath = require './item-path' Mutation = require './mutation' UrlUtil = require './url-util' shortid = require './shortid' _ = require 'underscore-plus' assert = require 'assert' Item = require './item' path = require 'path' fs = require 'fs' Q = require 'q' # Essential: A mutable outline of {Item}s. # # Use outlines to create new items, find existing items, and watch for changes # in items. Outlines also coordinate loading and saving items. # # Internally a {HTMLDocument} is used to store the underlying outline data. # You should never modify the content of this HTMLDocument directly, but you # can query it using {::evaluateXPath}. The structure of this document is # described in [FoldingText Markup Language](http://jessegrosjean.gitbooks.io # /foldingtext-for-atom-user-s-guide/content/appendix_b_file_format.html). # # ## Examples # # Group multiple changes: # # ```coffeescript # outline.beginUpdates() # root = outline.root # root.appendChild outline.createItem() # root.appendChild outline.createItem() # root.firstChild.bodyText = 'first' # root.lastChild.bodyText = 'last' # outline.endUpdates() # ``` # # Watch for outline changes: # # ```coffeescript # disposable = outline.onDidChange (mutations) -> # for mutation in mutations # switch mutation.type # when Mutation.ATTRIBUTE_CHANGED # console.log mutation.attributeName # when Mutation.BODT_TEXT_CHANGED # console.log mutation.target.bodyText # when Mutation.CHILDREN_CHANGED # console.log mutation.addedItems # console.log mutation.removedItems # ``` # # Use XPath to list all items with bold text: # # ```coffeescript # for each in outline.getItemsForXPath('//b') # console.log each # ``` class Outline root: null refcount: 0 changeCount: 0 undoSubscriptions: null updateCount: 0 updateCallbacks: null updateMutations: null coalescingMutation: null stoppedChangingDelay: 300 stoppedChangingTimeout: null file: null fileMimeType: null fileConflict: false fileSubscriptions: null loadOptions: null ### Section: Construction ### # Public: Create a new outline. constructor: (options) -> @id = shortid() @outlineStore = @createOutlineStore() rootElement = @outlineStore.getElementById Constants.RootID @loadingLIUsedIDs = {} @root = @createItem null, rootElement @loadingLIUsedIDs = null @undoManager = undoManager = new UndoManager @emitter = new Emitter @loaded = false @loadOptions = {} @undoSubscriptions = new CompositeDisposable @undoSubscriptions.add undoManager.onDidCloseUndoGroup => unless undoManager.isUndoing or undoManager.isRedoing @changeCount++ @scheduleModifiedEvents() @undoSubscriptions.add undoManager.onWillUndo => @breakUndoCoalescing() @undoSubscriptions.add undoManager.onDidUndo => @changeCount-- @breakUndoCoalescing() @scheduleModifiedEvents() @undoSubscriptions.add undoManager.onWillRedo => @breakUndoCoalescing() @undoSubscriptions.add undoManager.onDidRedo => @changeCount++ @breakUndoCoalescing() @scheduleModifiedEvents() @setPath(options.filePath) if options?.filePath @load() if options?.load createOutlineStore: (outlineStore) -> outlineStore = document.implementation.createHTMLDocument() rootUL = outlineStore.createElement('ul') rootUL.id = Constants.RootID outlineStore.documentElement.lastChild.appendChild(rootUL) outlineStore ### Section: Finding Outlines ### # Public: Read-only unique (not persistent) {String} outline ID. id: null @outlines = [] # Retrieves all open {Outlines}s. # # Returns an {Array} of {Outlines}s. @getOutlines: -> @outlines.slice() # Public: Returns existing {Outline} with the given outline id. # # - `id` {String} outline id. @getOutlineForID: (id) -> for each in @outlines if each.id is id return each # Given a file path, this retrieves or creates a new {Outline}. # # - `filePath` {String} outline file path. # - `createIfNeeded` (optional) {Boolean} create and return a new outline if can't find match. # # Returns a promise that resolves to the {Outline}. @getOutlineForPath: (filePath, createIfNeeded=true) -> absoluteFilePath = atom.project.resolvePath(filePath) for each in @outlines if each.getPath() is absoluteFilePath return Q(each) if createIfNeeded Q(@buildOutline(absoluteFilePath)) @getOutlineForPathSync: (filePath, createIfNeeded=true) -> absoluteFilePath = atom.project.resolvePath(filePath) for each in @outlines if each.getPath() is absoluteFilePath return each if createIfNeeded @buildOutlineSync(absoluteFilePath) @buildOutline: (absoluteFilePath) -> outline = new Outline({filePath: absoluteFilePath}) @addOutline(outline) outline.load() .then((outline) -> outline) .catch (error) -> atom.confirm message: "Could not open '#{outline.getTitle()}'" detailedMessage: "While trying to load encountered the following problem: #{error.name} – #{error.message}" outline.destroy() @buildOutlineSync: (absoluteFilePath) -> outline = new Outline({filePath: absoluteFilePath}) @addOutline(outline) outline.loadSync() outline @addOutline: (outline, options={}) -> @addOutlineAtIndex(outline, @outlines.length, options) @subscribeToOutline(outline) @addOutlineAtIndex: (outline, index, options={}) -> @outlines.splice(index, 0, outline) @subscribeToOutline(outline) outline @removeOutline: (outline) -> index = @outlines.indexOf(outline) @removeOutlineAtIndex(index) unless index is -1 @removeOutlineAtIndex: (index, options={}) -> [outline] = @outlines.splice(index, 1) outline?.destroy() @subscribeToOutline: (outline) -> outline.onDidDestroy => @removeOutline(outline) outline.onWillThrowWatchError ({error, handle}) -> handle() atom.notifications.addWarning """ Unable to read file after file `#{error.eventType}` event. Make sure you have permission to access `#{outline.getPath()}`. """, detail: error.message dismissable: true ### Section: Event Subscription ### # Public: Invoke the given callback synchronously _before_ the outline # changes. # # Because observers are invoked synchronously, it's important not to perform # any expensive operations via this method. # # * `callback` {Function} to be called when the outline will change. # * `mutation` {Mutation} describing the change. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onWillChange: (callback) -> @emitter.on 'will-change', callback # Public: Invoke the given callback when the outline changes. # # See {Outline} Examples for an example of subscribing to this event. # # - `callback` {Function} to be called when the outline changes. # - `mutations` {Array} of {Mutation}s describing the changes. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChange: (callback) -> @emitter.on 'did-change', callback onDidStopChanging: (callback) -> @emitter.on 'did-stop-changing', callback # Public: Invoke the given callback when the in-memory contents of the # outline become in conflict with the contents of the file on disk. # # - `callback` {Function} to be called when the outline enters conflict. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidConflict: (callback) -> @emitter.on 'did-conflict', callback # Public: Invoke the given callback when the value of {::isModified} changes. # # - `callback` {Function} to be called when {::isModified} changes. # - `modified` {Boolean} indicating whether the outline is modified. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChangeModified: (callback) -> @emitter.on 'did-change-modified', callback # Public: Invoke the given callback when the value of {::getPath} changes. # # - `callback` {Function} to be called when the path changes. # - `path` {String} representing the outline's current path on disk. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChangePath: (callback) -> @emitter.on 'did-change-path', callback # Public: Invoke the given callback before the outline is saved to disk. # # - `callback` {Function} to be called before the outline is saved. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onWillSave: (callback) -> @emitter.on 'will-save', callback # Public: Invoke the given callback after the outline is saved to disk. # # - `callback` {Function} to be called after the outline is saved. # - `event` {Object} with the following keys: # - `path` The path to which the outline was saved. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidSave: (callback) -> @emitter.on 'did-save', callback # Public: Invoke the given callback after the file backing the outline is # deleted. # # * `callback` {Function} to be called after the outline is deleted. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidDelete: (callback) -> @emitter.on 'did-delete', callback # Public: Invoke the given callback before the outline is reloaded from the # contents of its file on disk. # # - `callback` {Function} to be called before the outline is reloaded. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onWillReload: (callback) -> @emitter.on 'will-reload', callback # Public: Invoke the given callback after the outline is reloaded from the # contents of its file on disk. # # - `callback` {Function} to be called after the outline is reloaded. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidReload: (callback) -> @emitter.on 'did-reload', callback # Public: Invoke the given callback when the outline is destroyed. # # - `callback` {Function} to be called when the outline is destroyed. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidDestroy: (callback) -> @emitter.on 'did-destroy', callback # Public: Invoke the given callback when there is an error in watching the # file. # # * `callback` {Function} callback # * `errorObject` {Object} # * `error` {Object} the error object # * `handle` {Function} call this to indicate you have handled the error. # The error will not be thrown if this function is called. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onWillThrowWatchError: (callback) -> @emitter.on 'will-throw-watch-error', callback getStoppedChangingDelay: -> @stoppedChangingDelay ### Section: Reading Items ### # Public: Returns an {Array} of all {Item}s in the outline (except the # root) in outline order. getItems: -> @root.descendants isEmpty: -> firstChild = @root.firstChild not firstChild or (not firstChild.nextItem and firstChild.bodyText.length is 0) # Public: Returns {Item} for given id. # # - `id` {String} id. getItemForID: (id) -> @outlineStore.getElementById(id)?._item # Public: Returns {Array} of {Item}s for given {Array} of ids. # # - `ids` {Array} of ids. getItemsForIDs: (ids) -> return [] unless ids items = [] for each in ids each = @getItemForID each if each items.push each items ### Section: Creating Items ### # Public: Create a new item. The new item is owned by this outline, but is # not yet inserted into it so it won't be visible until you insert it. # # - `text` (optional) {String} or {AttributedString}. createItem: (text, LIOrID, remapIDCallback) -> if LIOrID and _.isString(LIOrID) LI = @createStoreLI() LI.id = LIOrID LIOrID = LI new Item(@, text, LIOrID or @createStoreLI(), remapIDCallback) cloneItem: (item, remapIDCallback) -> assert.ok(not item.isRoot, 'Can not clone root') assert.ok(item.outline is @, 'Item must be owned by this outline') @createItem(null, item._liOrRootUL.cloneNode(true), remapIDCallback) # Public: Creates a copy of an {Item} from an external outline that can be # inserted into the current outline. # # - `item` {Item} to import. # # Returns {Item} copy. importItem: (item) -> assert.ok(not item.isRoot, 'Can not import root item') assert.ok(item.outline isnt @, 'Item must not be owned by this outline') @createItem(null, @outlineStore.importNode(item._liOrRootUL, true)) ### Section: Insert & Remove Items ### # Not sure about this method... I think they are being used to handle moving # items from one outline to another... is that needed? TODO removeItemsFromParents: (items) -> siblings = [] prev = null for each in items if not prev or prev.nextSibling is each siblings.push(each) else @removeSiblingsFromParent(siblings) siblings = [each] prev = each if siblings.length @removeSiblingsFromParent(siblings); removeSiblingsFromParent: (siblings) -> return unless siblings.length firstSibling = siblings[0] outline = firstSibling.outline parent = firstSibling.parent return unless parent nextSibling = siblings[siblings.length - 1].nextSibling isInOutline = firstSibling.isInOutline undoManager = outline.undoManager if isInOutline if undoManager.isUndoRegistrationEnabled() undoManager.registerUndoOperation -> # This seems especially wrong? should now only have mutations on the # undo stack parent.insertChildrenBefore(siblings, nextSibling) undoManager.disableUndoRegistration() outline.beginUpdates() for each in siblings parent.removeChild each if isInOutline undoManager.enableUndoRegistration() outline.endUpdates() ### Section: Querying Items ### # Pubilc: Evaluate the item path starting with the root item and return all # matching items. # # - `itemPath` {String} itempath expression # - `contextItem` (optional) # # Returns an {Array} of matching {Item}s. evaluateItemPath: (itemPath, contextItem, options) -> options ?= {} options.root ?= @root contextItem ?= @root ItemPath.evaluate itemPath, contextItem, options # Public: XPath query internal HTML structure. # # - `xpathExpression` {String} xpath expression # - `contextItem` (optional) # - `namespaceResolver` (optional) # - `resultType` (optional) # - `result` (optional) # # This query evaluates on the underlying HTMLDocument. Please refer to the # standard [document.evaluate](https://developer.mozilla.org/en- # US/docs/Web/API/document.evaluate) documentation for details. # # Returns an [XPathResult](https://developer.mozilla.org/en- # US/docs/XPathResult) based on an [XPath](https://developer.mozilla.org/en- # US/docs/Web/XPath) expression and other given parameters. evaluateXPath: (xpathExpression, contextItem, namespaceResolver, resultType, result) -> contextItem ?= @root @outlineStore.evaluate( xpathExpression, contextItem._liOrRootUL, namespaceResolver, resultType, result ) # Public: XPath query internal HTML structure for matching {Items}. # # Items are considered to match if they, or a node contained in their body # text, matches the XPath. # # - `xpathExpression` {String} xpath expression # - `contextItem` (optional) {String} # - `namespaceResolver` (optional) {String} # # Returns an {Array} of all {Item} matching the # [XPath](https://developer.mozilla.org/en-US/docs/Web/XPath) expression. getItemsForXPath: (xpathExpression, contextItem, namespaceResolver, exceptionCallback) -> try xpathResult = @evaluateXPath( xpathExpression, contextItem, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE ) each = xpathResult.iterateNext() lastItem = undefined items = [] while each while each and not each._item each = each.parentNode if each eachItem = each._item if eachItem isnt lastItem items.push(eachItem) lastItem = eachItem each = xpathResult.iterateNext() return items catch error exceptionCallback?(error) [] ### Section: Grouping Changes ### # Public: Returns {Boolean} true if outline is updating. isUpdating: -> @updateCount isnt 0 # Public: Begin grouping changes. Must later call {::endUpdates} to balance # this call. beginUpdates: -> if ++@updateCount is 1 @updateCallbacks = [] @updateMutations = [] breakUndoCoalescing: -> @coalescingMutation = null recoredUpdateMutation: (mutation) -> @updateMutations.push mutation.copy() if @undoManager.isUndoing or @undoManager.isUndoing @breakUndoCoalescing() if @coalescingMutation and @coalescingMutation.coalesce(mutation) metadata = @undoManager.getUndoGroupMetadata() undoSelection = metadata.undoSelection if undoSelection and @coalescingMutation.type is Mutation.BODT_TEXT_CHANGED # Update the undo selection to match coalescingMutation undoSelection.anchorOffset = @coalescingMutation.insertedTextLocation undoSelection.startOffset = @coalescingMutation.insertedTextLocation undoSelection.focusOffset = @coalescingMutation.insertedTextLocation + @coalescingMutation.replacedText.length undoSelection.endOffset = @coalescingMutation.insertedTextLocation + @coalescingMutation.replacedText.length else @undoManager.registerUndoOperation mutation @coalescingMutation = mutation # Public: End grouping changes. Must call to balance a previous # {::beginUpdates} call. # # - `callback` (optional) Callback is called when outline finishes updating. endUpdates: (callback) -> @updateCallbacks.push(callback) if callback if --@updateCount is 0 updateMutations = @updateMutations @updateMutations = null if updateMutations.length > 0 @conflict = false if @conflict and not @isModified() @emitter.emit('did-change', updateMutations) @scheduleModifiedEvents() updateCallbacks = @updateCallbacks @updateCallbacks = null for each in updateCallbacks each() ### Section: Undo ### # Essential: Undo the last change. undo: -> @undoManager.undo() # Essential: Redo the last change. redo: -> @undoManager.redo() ### Section: File Details ### # Public: Determine if the outline has changed since it was loaded. # # If the outline is unsaved, always returns `true` unless the outline is # empty. # # Returns a {Boolean}. isModified: -> return false unless @loaded if @file @changeCount isnt 0 #if @file.existsSync() # @getText() isnt @cachedDiskContents #else # @wasModifiedBeforeRemove ? not @isEmpty() else not @isEmpty() # Public: Determine if the in-memory contents of the outline conflict with the # on-disk contents of its associated file. # # Returns a {Boolean}. isInConflict: -> @conflict getMimeType: -> unless @fileMimeType @fileMimeType = ItemSerializer.getMimeTypeForURI(@getPath()) or Constants.FTMLMimeType @fileMimeType setMimeType: (mimeType) -> unless @getMimeType() is mimeType @fileMimeType = mimeType # Public: Get the path of the associated file. # # Returns a {String}. getPath: -> @file?.getPath() # Public: Set the path for the outlines's associated file. # # - `filePath` A {String} representing the new file path setPath: (filePath) -> return if filePath is @getPath() if filePath @file = new File(filePath) @file.setEncoding('utf8') @subscribeToFile() else @file = null @emitter.emit 'did-change-path', @getPath() @setMimeType(null) getURI: (options) -> @getPath() # Public: Get an href to this outline. # # * `options` (optional) The {Object} with URL options (default: {}): # * `hoistedItem` An {Item} to hoist when opening the outline # * `query` A {String} item path to set when opening the outline. # * `expanded` An {Array} of items to expand when opening the outline. # * `selection` An {Object} with the selection to set when opening the outline. # * `focusItem` The focus {Item}. # * `focusOffset` The focus offset {Number}. # * `anchorItem` The anchor {Item}. # * `anchorOffset` The anchor offset {Number}. getFileURL: (options={}) -> urlOptions = {} hoistedItem = options.hoistedItem if hoistedItem and not hoistedItem.isRoot urlOptions.hash = hoistedItem.id if query = options.query urlOptions.query = query if expanded = options.expanded urlOptions.expanded = (each.id for each in expanded).join(',') if options.selection?.focusItem selection = options.selection focusItem = selection.focusItem focusOffset = selection.focusOffset ? undefined anchorItem = selection.anchorItem ? focusItem anchorOffset = selection.anchorOffset ? focusOffset urlOptions.selection = "#{focusItem?.id},#{focusOffset},#{anchorItem?.id},#{anchorOffset}" if @getPath() UrlUtil.getFileURLFromPathnameAndOptions(@getPath(), urlOptions) else # Hack... in case where outline has no path can't return file:// url # since they require and absolute path. So instead just return the # encoded options. UrlUtil.getHREFFromFileURLs('file:///', 'file:///', urlOptions) getBaseName: -> @file?.getBaseName() or 'Untitled' getTitle: -> if sessionPath = @getPath() path.basename(sessionPath) else 'Untitled' getLongTitle: -> if sessionPath = @getPath() fileName = path.basename(sessionPath) directory = atom.project.relativize(path.dirname(sessionPath)) directory = if directory.length > 0 then directory else path.basename(path.dirname(sessionPath)) "#{fileName} - #{directory}" else 'Untitled' ### Section: File Content Operations ### # Public: Save the outline. save: (editor) -> @saveAs @getPath(), editor # Public: Save the outline at a specific path. # # - `filePath` The path to save at. saveAs: (filePath, editor) -> unless filePath then throw new Error("Can't save outline with no file path") @emitter.emit 'will-save', {path: filePath} @setPath(filePath) text = ItemSerializer.serializeItems(@root.children, editor, @getMimeType()) @file.writeSync text @cachedDiskContents = text @conflict = false @changeCount = 0 @emitModifiedStatusChanged(false) @emitter.emit 'did-save', {path: filePath} # Public: Reload the outline's contents from disk. # # Sets the outline's content to the cached disk contents. reload: -> @emitter.emit 'will-reload' @beginUpdates() @root.removeChildren(@root.children) if @cachedDiskContents items = ItemSerializer.deserializeItems(@cachedDiskContents, this, @getMimeType()) @loadOptions = items.loadOptions for each in items @root.appendChild(each) @endUpdates() @changeCount = 0 @emitModifiedStatusChanged(false) @emitter.emit 'did-reload' updateCachedDiskContentsSync: (pathOverride) -> if pathOverride @cachedDiskContents = fs.readFileSync(pathOverride, 'utf8') else @cachedDiskContents = @file?.readSync() ? "" updateCachedDiskContents: (flushCache=false, callback) -> Q(@file?.read(flushCache) ? "").then (contents) => @cachedDiskContents = contents callback?() ### Section: Private Utility Methods ### createStoreLI: -> outlineStore = @outlineStore li = outlineStore.createElement('LI') li.appendChild(outlineStore.createElement('P')) li nextOutlineUniqueItemID: (candidateID) -> loadingLIUsedIDs = @loadingLIUsedIDs while true id = candidateID or shortid() if loadingLIUsedIDs and not loadingLIUsedIDs[id] loadingLIUsedIDs[id] = true return id else if not @outlineStore.getElementById(id) return id else candidateID = null loadSync: (pathOverride) -> @updateCachedDiskContentsSync(pathOverride) @finishLoading() load: -> @updateCachedDiskContents().then => @finishLoading() finishLoading: -> if @isAlive() @loaded = true @reload() @undoManager.removeAllActions() this destroy: -> unless @destroyed Outline.removeOutline this @cancelStoppedChangingTimeout() @undoSubscriptions?.dispose() @fileSubscriptions?.dispose() @destroyed = true @emitter.emit 'did-destroy' isAlive: -> not @destroyed isDestroyed: -> @destroyed isRetained: -> @refcount > 0 retain: -> @refcount++ this release: (editorID) -> @refcount-- for each in @getItems() each.setUserData editorID, undefined @destroy() unless @isRetained() this subscribeToFile: -> @fileSubscriptions?.dispose() @fileSubscriptions = new CompositeDisposable @fileSubscriptions.add @file.onDidChange => @conflict = true if @isModified() previousContents = @cachedDiskContents # Synchronously update the disk contents because the {File} has already # cached them. If the contents updated asynchrounously multiple # `conlict` events could trigger for the same disk contents. @updateCachedDiskContentsSync() return if previousContents is @cachedDiskContents if @conflict @emitter.emit 'did-conflict' else @reload() @fileSubscriptions.add @file.onDidDelete => modified = isModified() @wasModifiedBeforeRemove = modified @emitter.emit 'did-delete' if modified @updateCachedDiskContents() else @destroy() @fileSubscriptions.add @file.onDidRename => @emitter.emit 'did-change-path', @getPath() @fileSubscriptions.add @file.onWillThrowWatchError (errorObject) => @emitter.emit 'will-throw-watch-error', errorObject hasMultipleEditors: -> @refcount > 1 cancelStoppedChangingTimeout: -> clearTimeout(@stoppedChangingTimeout) if @stoppedChangingTimeout scheduleModifiedEvents: -> @cancelStoppedChangingTimeout() stoppedChangingCallback = => @stoppedChangingTimeout = null modifiedStatus = @isModified() @emitter.emit 'did-stop-changing' @emitModifiedStatusChanged(modifiedStatus) @stoppedChangingTimeout = setTimeout( stoppedChangingCallback, @stoppedChangingDelay ) emitModifiedStatusChanged: (modifiedStatus) -> return if modifiedStatus is @previousModifiedStatus @previousModifiedStatus = modifiedStatus @emitter.emit 'did-change-modified', modifiedStatus module.exports = Outline
[ { "context": "g + \"/package.json\", JSON.stringify(\n author: \"Rocko Artischocko\"\n name: \"noargs\"\n version: \"0.0.0\"\n devD", "end": 175, "score": 0.9998650550842285, "start": 158, "tag": "NAME", "value": "Rocko Artischocko" } ]
deps/npm/test/tap/noargs-install-config-save.coffee
lxe/io.coffee
0
writePackageJson = -> rimraf.sync pkg mkdirp.sync pkg mkdirp.sync pkg + "/cache" fs.writeFileSync pkg + "/package.json", JSON.stringify( author: "Rocko Artischocko" name: "noargs" version: "0.0.0" devDependencies: underscore: "1.3.1" ), "utf8" return createChild = (args) -> env = npm_config_save: true npm_config_registry: common.registry npm_config_cache: pkg + "/cache" HOME: process.env.HOME Path: process.env.PATH PATH: process.env.PATH env.npm_config_cache = "%APPDATA%\\npm-cache" if process.platform is "win32" spawn node, args, cwd: pkg env: env common = require("../common-tap.js") test = require("tap").test npm = require.resolve("../../bin/npm-cli.js") path = require("path") fs = require("fs") rimraf = require("rimraf") mkdirp = require("mkdirp") mr = require("npm-registry-mock") spawn = require("child_process").spawn node = process.execPath pkg = path.resolve(process.env.npm_config_tmp or "/tmp", "noargs-install-config-save") test "does not update the package.json with empty arguments", (t) -> writePackageJson() t.plan 1 mr common.port, (s) -> child = createChild([ npm "install" ]) child.on "close", -> text = JSON.stringify(fs.readFileSync(pkg + "/package.json", "utf8")) t.ok text.indexOf("\"dependencies") is -1 s.close() t.end() return return return test "updates the package.json (adds dependencies) with an argument", (t) -> writePackageJson() t.plan 1 mr common.port, (s) -> child = createChild([ npm "install" "underscore" ]) child.on "close", -> text = JSON.stringify(fs.readFileSync(pkg + "/package.json", "utf8")) t.ok text.indexOf("\"dependencies") isnt -1 s.close() t.end() return return return test "cleanup", (t) -> rimraf.sync pkg + "/cache" t.end() return
172913
writePackageJson = -> rimraf.sync pkg mkdirp.sync pkg mkdirp.sync pkg + "/cache" fs.writeFileSync pkg + "/package.json", JSON.stringify( author: "<NAME>" name: "noargs" version: "0.0.0" devDependencies: underscore: "1.3.1" ), "utf8" return createChild = (args) -> env = npm_config_save: true npm_config_registry: common.registry npm_config_cache: pkg + "/cache" HOME: process.env.HOME Path: process.env.PATH PATH: process.env.PATH env.npm_config_cache = "%APPDATA%\\npm-cache" if process.platform is "win32" spawn node, args, cwd: pkg env: env common = require("../common-tap.js") test = require("tap").test npm = require.resolve("../../bin/npm-cli.js") path = require("path") fs = require("fs") rimraf = require("rimraf") mkdirp = require("mkdirp") mr = require("npm-registry-mock") spawn = require("child_process").spawn node = process.execPath pkg = path.resolve(process.env.npm_config_tmp or "/tmp", "noargs-install-config-save") test "does not update the package.json with empty arguments", (t) -> writePackageJson() t.plan 1 mr common.port, (s) -> child = createChild([ npm "install" ]) child.on "close", -> text = JSON.stringify(fs.readFileSync(pkg + "/package.json", "utf8")) t.ok text.indexOf("\"dependencies") is -1 s.close() t.end() return return return test "updates the package.json (adds dependencies) with an argument", (t) -> writePackageJson() t.plan 1 mr common.port, (s) -> child = createChild([ npm "install" "underscore" ]) child.on "close", -> text = JSON.stringify(fs.readFileSync(pkg + "/package.json", "utf8")) t.ok text.indexOf("\"dependencies") isnt -1 s.close() t.end() return return return test "cleanup", (t) -> rimraf.sync pkg + "/cache" t.end() return
true
writePackageJson = -> rimraf.sync pkg mkdirp.sync pkg mkdirp.sync pkg + "/cache" fs.writeFileSync pkg + "/package.json", JSON.stringify( author: "PI:NAME:<NAME>END_PI" name: "noargs" version: "0.0.0" devDependencies: underscore: "1.3.1" ), "utf8" return createChild = (args) -> env = npm_config_save: true npm_config_registry: common.registry npm_config_cache: pkg + "/cache" HOME: process.env.HOME Path: process.env.PATH PATH: process.env.PATH env.npm_config_cache = "%APPDATA%\\npm-cache" if process.platform is "win32" spawn node, args, cwd: pkg env: env common = require("../common-tap.js") test = require("tap").test npm = require.resolve("../../bin/npm-cli.js") path = require("path") fs = require("fs") rimraf = require("rimraf") mkdirp = require("mkdirp") mr = require("npm-registry-mock") spawn = require("child_process").spawn node = process.execPath pkg = path.resolve(process.env.npm_config_tmp or "/tmp", "noargs-install-config-save") test "does not update the package.json with empty arguments", (t) -> writePackageJson() t.plan 1 mr common.port, (s) -> child = createChild([ npm "install" ]) child.on "close", -> text = JSON.stringify(fs.readFileSync(pkg + "/package.json", "utf8")) t.ok text.indexOf("\"dependencies") is -1 s.close() t.end() return return return test "updates the package.json (adds dependencies) with an argument", (t) -> writePackageJson() t.plan 1 mr common.port, (s) -> child = createChild([ npm "install" "underscore" ]) child.on "close", -> text = JSON.stringify(fs.readFileSync(pkg + "/package.json", "utf8")) t.ok text.indexOf("\"dependencies") isnt -1 s.close() t.end() return return return test "cleanup", (t) -> rimraf.sync pkg + "/cache" t.end() return
[ { "context": "{\n user:\n id: 24\n name: 'test user'\n email: 'test.user@guc.edu.eg'\n ", "end": 642, "score": 0.7163909077644348, "start": 633, "tag": "NAME", "value": "test user" }, { "context": " 24\n name: 'test user'\n e...
spec/directive/logout.coffee
ah450/guclink-auth-angular-modules
0
describe 'logout directive', -> beforeEach module 'guclinkAuthModules' userAuth = null $httpBackend = null $rootScope = null $compile = null beforeEach inject (_UserAuth_, _$httpBackend_, _$rootScope_, _$compile_) -> userAuth = _UserAuth_ $httpBackend = _$httpBackend_ $rootScope = _$rootScope_ $compile = _$compile_ beforeEach -> $httpBackend.when('GET', 'http://localhost:3000/api/configurations.json') .respond({ default_token_exp: 30 }) $httpBackend.when('POST', 'http://localhost:3000/api/tokens.json') .respond(201, { user: id: 24 name: 'test user' email: 'test.user@guc.edu.eg' verified: true student: false super_user: false full_name: 'Test User' created_at: '2016-04-08T20:06:45.391Z' updated_at: '2016-04-08T20:06:45.391Z' token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE0NjAyMDAyMzAsImV4cCI6MTQ5MTczNjIzMCwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5hbWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.Q82UHJ8ep8EUYLKBdwpiTa9S4j5lSxHFrTP3uePnln8' }) beforeEach -> promise = userAuth.login({email: 'haha@guc.edu.eg', password: 'password'}, 24) $httpBackend.flush() $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() it 'logs out on click', -> expect(userAuth.signedIn).to.be.true element = angular.element("<button data-logout></button>") compiled = $compile(element)($rootScope) compiled.click() expect(userAuth.signedIn).to.be.false
26681
describe 'logout directive', -> beforeEach module 'guclinkAuthModules' userAuth = null $httpBackend = null $rootScope = null $compile = null beforeEach inject (_UserAuth_, _$httpBackend_, _$rootScope_, _$compile_) -> userAuth = _UserAuth_ $httpBackend = _$httpBackend_ $rootScope = _$rootScope_ $compile = _$compile_ beforeEach -> $httpBackend.when('GET', 'http://localhost:3000/api/configurations.json') .respond({ default_token_exp: 30 }) $httpBackend.when('POST', 'http://localhost:3000/api/tokens.json') .respond(201, { user: id: 24 name: '<NAME>' email: '<EMAIL>' verified: true student: false super_user: false full_name: '<NAME>' created_at: '2016-04-08T20:06:45.391Z' updated_at: '2016-04-08T20:06:45.391Z' token: '<KEY>Fr<KEY>Pnln<KEY>' }) beforeEach -> promise = userAuth.login({email: '<EMAIL>', password: '<PASSWORD>'}, 24) $httpBackend.flush() $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() it 'logs out on click', -> expect(userAuth.signedIn).to.be.true element = angular.element("<button data-logout></button>") compiled = $compile(element)($rootScope) compiled.click() expect(userAuth.signedIn).to.be.false
true
describe 'logout directive', -> beforeEach module 'guclinkAuthModules' userAuth = null $httpBackend = null $rootScope = null $compile = null beforeEach inject (_UserAuth_, _$httpBackend_, _$rootScope_, _$compile_) -> userAuth = _UserAuth_ $httpBackend = _$httpBackend_ $rootScope = _$rootScope_ $compile = _$compile_ beforeEach -> $httpBackend.when('GET', 'http://localhost:3000/api/configurations.json') .respond({ default_token_exp: 30 }) $httpBackend.when('POST', 'http://localhost:3000/api/tokens.json') .respond(201, { user: id: 24 name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' verified: true student: false super_user: false full_name: 'PI:NAME:<NAME>END_PI' created_at: '2016-04-08T20:06:45.391Z' updated_at: '2016-04-08T20:06:45.391Z' token: 'PI:KEY:<KEY>END_PIFrPI:KEY:<KEY>END_PIPnlnPI:KEY:<KEY>END_PI' }) beforeEach -> promise = userAuth.login({email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI'}, 24) $httpBackend.flush() $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() it 'logs out on click', -> expect(userAuth.signedIn).to.be.true element = angular.element("<button data-logout></button>") compiled = $compile(element)($rootScope) compiled.click() expect(userAuth.signedIn).to.be.false
[ { "context": "ections for real-timey 2-way updates\n# Authored by Andrew J. Hart and licensed under MIT.\n# Generated by CoffeeScri", "end": 173, "score": 0.9998952150344849, "start": 159, "tag": "NAME", "value": "Andrew J. Hart" }, { "context": " 'pusher'\n\n\t# defaults object\n\td...
dev/BackbonePusher.require.coffee
AndrewJHart/backbone-pusher
0
# Backbone-Pusher require-js version # mixin that integrates pusher.js websockets # with your backbone collections for real-timey 2-way updates # Authored by Andrew J. Hart and licensed under MIT. # Generated by CoffeeScript 1.6.3 define (require) -> 'use strict' # use common-js looking requires, in require-js, for readability _ = require 'underscore' Backbone = require 'backbone' Pusher = require 'pusher' # defaults object defaults = key: 'PUSHER-APP-KEY' channel: 'CHANNEL-NAME' channelSuffix: 'channel' messageSuffix: 'message' autoListen: true logEvents: true logStats: true # add in filters so that users can flag models that should be removed filters: status: 'C' # this would be equivalent to api/posts/1/?status__exclude=C class BackbonePusher # mixin events object from Backbone _.extend @prototype, Backbone.Events filters: null settings: null states: last: null current: null logging: false initialize: (options) -> opts = options or {} @settings = _.defaults opts, defaults # merge options w/ defaults if @settings? if @settings.filters? and _.isObject @settings.filters @filters = @settings.filters # assign to var @logging = @settings.logEvents @socketStatus() if @settings.logStats is true @connect() if @settings.autoListen is true this # output all info regarding pusher state logEventsStates: -> console.log 'PusherSocket#setup triggered' if @pusher and @logging @pusher.connection.bind 'state_change', (state) => console.log "PusherSocket.pusher state: #{state.current}" @states = state this this getState: -> console.log "Current Pusher State: #{@pusher?.connection.state}" this # makes Pusher informs whats going on under the hood; Added as method on # actual static Pusher object instead of instantiated object -- Pusher must # check if .log is defined and use it as a callback if it is a function socketStatus: -> Pusher.log = (message) -> if console.debug_state is true console.log message else console.log message # override in case we want this w/o all other app debugging this # method to ensure we are able to create pusher object initPusher: -> if not @pusher if @settings.key? @pusher = new Pusher @settings.key else console.log 'Settings error or key not present for pusher object' this # create the data channel stream initChannel: -> if @pusher? @dataChannel = @pusher.subscribe "#{@settings.channel}-#{@settings.channelSuffix}" this else # retry by waiting 2s to ensure push is rdy setTimeout( => console.log 'PusherSocket#initChannel Error on subscribe retrying' @pusher = new Pusher @settings.key @initChannel() , 2000) this connect: -> console.log 'PusherSocket#connect triggered' @initPusher() # create pusher object @initChannel() # establish data channel @logEventsStates() if @logging console.log 'startPusher method triggered', @pusher, @dataChannel # bind to channels and react accordingly @dataChannel.bind "update_#{@settings.messageSuffix}", (data) => console.log 'Broadcasting pusher Update event: ', data @publishEvent 'push_update', data @liveUpdate data this # note the convenient coffeescript => vs -> to ensure that "this" # bound the PusherSocket object instead of local function @dataChannel.bind "add_#{@settings.messageSuffix}", (data) => console.log 'Broadcasting pusher Add event: ', data @publishEvent 'push_add', data @liveAdd data this # --------------------------- # Methods for modifying the collection dataset # used as getter if no parameter is passed filters: (filters) => return @filters if not filters # else data in param so set some properties if filters? and _.isObject filters filters = filters else filters = {} @filters = _.defaults @settings.filters, filters console.log @filters this liveUpdate: (data) => console.log "#{@constructor.name}.liveUpdate triggered" # look for corresponding model in collection with same id model = @get data.id if model? # by using addFilters a user can * filter out any models that wouldn't normally come down the pipe # but do because of websockets (not REST). This code loops over the objects key:value pairs to test filters! # one can pass a key: value pair to filter -> key is model attribute to check and value is the model attribute # value that would want check against. That is: Filter out models with attribute status of value 'C' would be: # addFilters({status: 'C'}) and then any real-time or updated models with model.status == 'C' will be # automatically removed from collection if @filters? for filter, value of @filters if data[filter] is value console.log "Model with attribute #{filter} and value #{value} was removed from collection!" @remove model else @set(model.set(data), remove: false) # call set on model instance itself to update props @trigger 'change', model #@set data, remove: false console.log 'model already exists in local collection - updating its properties.' else @set data, remove: false # call set on collection to perform smart update console.log 'model was archived & is not present in local collection - updating local collection' this liveAdd: (data) => console.log "#{@constructor.name}.liveAdd triggered" @add data @trigger 'add', data this liveRemove: (data) => console.log "#{@constructor.name}.liveRemove Triggered" model = @get data.id if model? @remove model console.log 'removed model id: #{ data.id }' else console.log 'no model found in this collection that matches pusher data - no removal.' this
196183
# Backbone-Pusher require-js version # mixin that integrates pusher.js websockets # with your backbone collections for real-timey 2-way updates # Authored by <NAME> and licensed under MIT. # Generated by CoffeeScript 1.6.3 define (require) -> 'use strict' # use common-js looking requires, in require-js, for readability _ = require 'underscore' Backbone = require 'backbone' Pusher = require 'pusher' # defaults object defaults = key: '<KEY>' channel: 'CHANNEL-NAME' channelSuffix: 'channel' messageSuffix: 'message' autoListen: true logEvents: true logStats: true # add in filters so that users can flag models that should be removed filters: status: 'C' # this would be equivalent to api/posts/1/?status__exclude=C class BackbonePusher # mixin events object from Backbone _.extend @prototype, Backbone.Events filters: null settings: null states: last: null current: null logging: false initialize: (options) -> opts = options or {} @settings = _.defaults opts, defaults # merge options w/ defaults if @settings? if @settings.filters? and _.isObject @settings.filters @filters = @settings.filters # assign to var @logging = @settings.logEvents @socketStatus() if @settings.logStats is true @connect() if @settings.autoListen is true this # output all info regarding pusher state logEventsStates: -> console.log 'PusherSocket#setup triggered' if @pusher and @logging @pusher.connection.bind 'state_change', (state) => console.log "PusherSocket.pusher state: #{state.current}" @states = state this this getState: -> console.log "Current Pusher State: #{@pusher?.connection.state}" this # makes Pusher informs whats going on under the hood; Added as method on # actual static Pusher object instead of instantiated object -- Pusher must # check if .log is defined and use it as a callback if it is a function socketStatus: -> Pusher.log = (message) -> if console.debug_state is true console.log message else console.log message # override in case we want this w/o all other app debugging this # method to ensure we are able to create pusher object initPusher: -> if not @pusher if @settings.key? @pusher = new Pusher @settings.key else console.log 'Settings error or key not present for pusher object' this # create the data channel stream initChannel: -> if @pusher? @dataChannel = @pusher.subscribe "#{@settings.channel}-#{@settings.channelSuffix}" this else # retry by waiting 2s to ensure push is rdy setTimeout( => console.log 'PusherSocket#initChannel Error on subscribe retrying' @pusher = new Pusher @settings.key @initChannel() , 2000) this connect: -> console.log 'PusherSocket#connect triggered' @initPusher() # create pusher object @initChannel() # establish data channel @logEventsStates() if @logging console.log 'startPusher method triggered', @pusher, @dataChannel # bind to channels and react accordingly @dataChannel.bind "update_#{@settings.messageSuffix}", (data) => console.log 'Broadcasting pusher Update event: ', data @publishEvent 'push_update', data @liveUpdate data this # note the convenient coffeescript => vs -> to ensure that "this" # bound the PusherSocket object instead of local function @dataChannel.bind "add_#{@settings.messageSuffix}", (data) => console.log 'Broadcasting pusher Add event: ', data @publishEvent 'push_add', data @liveAdd data this # --------------------------- # Methods for modifying the collection dataset # used as getter if no parameter is passed filters: (filters) => return @filters if not filters # else data in param so set some properties if filters? and _.isObject filters filters = filters else filters = {} @filters = _.defaults @settings.filters, filters console.log @filters this liveUpdate: (data) => console.log "#{@constructor.name}.liveUpdate triggered" # look for corresponding model in collection with same id model = @get data.id if model? # by using addFilters a user can * filter out any models that wouldn't normally come down the pipe # but do because of websockets (not REST). This code loops over the objects key:value pairs to test filters! # one can pass a key: value pair to filter -> key is model attribute to check and value is the model attribute # value that would want check against. That is: Filter out models with attribute status of value 'C' would be: # addFilters({status: 'C'}) and then any real-time or updated models with model.status == 'C' will be # automatically removed from collection if @filters? for filter, value of @filters if data[filter] is value console.log "Model with attribute #{filter} and value #{value} was removed from collection!" @remove model else @set(model.set(data), remove: false) # call set on model instance itself to update props @trigger 'change', model #@set data, remove: false console.log 'model already exists in local collection - updating its properties.' else @set data, remove: false # call set on collection to perform smart update console.log 'model was archived & is not present in local collection - updating local collection' this liveAdd: (data) => console.log "#{@constructor.name}.liveAdd triggered" @add data @trigger 'add', data this liveRemove: (data) => console.log "#{@constructor.name}.liveRemove Triggered" model = @get data.id if model? @remove model console.log 'removed model id: #{ data.id }' else console.log 'no model found in this collection that matches pusher data - no removal.' this
true
# Backbone-Pusher require-js version # mixin that integrates pusher.js websockets # with your backbone collections for real-timey 2-way updates # Authored by PI:NAME:<NAME>END_PI and licensed under MIT. # Generated by CoffeeScript 1.6.3 define (require) -> 'use strict' # use common-js looking requires, in require-js, for readability _ = require 'underscore' Backbone = require 'backbone' Pusher = require 'pusher' # defaults object defaults = key: 'PI:KEY:<KEY>END_PI' channel: 'CHANNEL-NAME' channelSuffix: 'channel' messageSuffix: 'message' autoListen: true logEvents: true logStats: true # add in filters so that users can flag models that should be removed filters: status: 'C' # this would be equivalent to api/posts/1/?status__exclude=C class BackbonePusher # mixin events object from Backbone _.extend @prototype, Backbone.Events filters: null settings: null states: last: null current: null logging: false initialize: (options) -> opts = options or {} @settings = _.defaults opts, defaults # merge options w/ defaults if @settings? if @settings.filters? and _.isObject @settings.filters @filters = @settings.filters # assign to var @logging = @settings.logEvents @socketStatus() if @settings.logStats is true @connect() if @settings.autoListen is true this # output all info regarding pusher state logEventsStates: -> console.log 'PusherSocket#setup triggered' if @pusher and @logging @pusher.connection.bind 'state_change', (state) => console.log "PusherSocket.pusher state: #{state.current}" @states = state this this getState: -> console.log "Current Pusher State: #{@pusher?.connection.state}" this # makes Pusher informs whats going on under the hood; Added as method on # actual static Pusher object instead of instantiated object -- Pusher must # check if .log is defined and use it as a callback if it is a function socketStatus: -> Pusher.log = (message) -> if console.debug_state is true console.log message else console.log message # override in case we want this w/o all other app debugging this # method to ensure we are able to create pusher object initPusher: -> if not @pusher if @settings.key? @pusher = new Pusher @settings.key else console.log 'Settings error or key not present for pusher object' this # create the data channel stream initChannel: -> if @pusher? @dataChannel = @pusher.subscribe "#{@settings.channel}-#{@settings.channelSuffix}" this else # retry by waiting 2s to ensure push is rdy setTimeout( => console.log 'PusherSocket#initChannel Error on subscribe retrying' @pusher = new Pusher @settings.key @initChannel() , 2000) this connect: -> console.log 'PusherSocket#connect triggered' @initPusher() # create pusher object @initChannel() # establish data channel @logEventsStates() if @logging console.log 'startPusher method triggered', @pusher, @dataChannel # bind to channels and react accordingly @dataChannel.bind "update_#{@settings.messageSuffix}", (data) => console.log 'Broadcasting pusher Update event: ', data @publishEvent 'push_update', data @liveUpdate data this # note the convenient coffeescript => vs -> to ensure that "this" # bound the PusherSocket object instead of local function @dataChannel.bind "add_#{@settings.messageSuffix}", (data) => console.log 'Broadcasting pusher Add event: ', data @publishEvent 'push_add', data @liveAdd data this # --------------------------- # Methods for modifying the collection dataset # used as getter if no parameter is passed filters: (filters) => return @filters if not filters # else data in param so set some properties if filters? and _.isObject filters filters = filters else filters = {} @filters = _.defaults @settings.filters, filters console.log @filters this liveUpdate: (data) => console.log "#{@constructor.name}.liveUpdate triggered" # look for corresponding model in collection with same id model = @get data.id if model? # by using addFilters a user can * filter out any models that wouldn't normally come down the pipe # but do because of websockets (not REST). This code loops over the objects key:value pairs to test filters! # one can pass a key: value pair to filter -> key is model attribute to check and value is the model attribute # value that would want check against. That is: Filter out models with attribute status of value 'C' would be: # addFilters({status: 'C'}) and then any real-time or updated models with model.status == 'C' will be # automatically removed from collection if @filters? for filter, value of @filters if data[filter] is value console.log "Model with attribute #{filter} and value #{value} was removed from collection!" @remove model else @set(model.set(data), remove: false) # call set on model instance itself to update props @trigger 'change', model #@set data, remove: false console.log 'model already exists in local collection - updating its properties.' else @set data, remove: false # call set on collection to perform smart update console.log 'model was archived & is not present in local collection - updating local collection' this liveAdd: (data) => console.log "#{@constructor.name}.liveAdd triggered" @add data @trigger 'add', data this liveRemove: (data) => console.log "#{@constructor.name}.liveRemove Triggered" model = @get data.id if model? @remove model console.log 'removed model id: #{ data.id }' else console.log 'no model found in this collection that matches pusher data - no removal.' this
[ { "context": "y pixel on 2D HTML5 canvas\n# https://github.com/linusyang/jscube\n#\n# Copyright (c) 2013 Linus Yang\n#\n\n@Sh", "end": 101, "score": 0.999293327331543, "start": 92, "tag": "USERNAME", "value": "linusyang" }, { "context": "thub.com/linusyang/jscube\n#\n# Copyrigh...
src/shapeutil.coffee
linusyang/jscube
2
# # JSCube # # Draw 3D objects pixel by pixel on 2D HTML5 canvas # https://github.com/linusyang/jscube # # Copyright (c) 2013 Linus Yang # @ShapeUtil = rebuildMeta: (shape) -> vertices = shape.vertices for qf in shape.quads vert0 = vertices[qf.i0] vert1 = vertices[qf.i1] vert2 = vertices[qf.i2] vec01 = VectorUtil.subPoints3d vert1, vert0 vec02 = VectorUtil.subPoints3d vert2, vert0 n1 = VectorUtil.crossProduct vec01, vec02 if qf.isTriangle() n2 = n1 centroid = MatrixUtil.averagePoints [vert0, vert1, vert2] else vert3 = vertices[qf.i3]; vec03 = VectorUtil.subPoints3d vert3, vert0 n2 = VectorUtil.crossProduct vec02, vec03 centroid = MatrixUtil.averagePoints [vert0, vert1, vert2, vert3] qf.centroid = centroid qf.normal1 = n1 qf.normal2 = n2 shape # 4 -- 0 # /| /| +y # 5 -- 1 | |__ +x # | 7 -|-3 / # |/ |/ +z # 6 -- 2 makeBox: (w, h, d) -> s = new Shape() s.vertices = [ {x: w, y: h, z: -d}, {x: w, y: h, z: d}, {x: w, y: -h, z: d}, {x: w, y: -h, z: -d}, {x: -w, y: h, z: -d}, {x: -w, y: h, z: d}, {x: -w, y: -h, z: d}, {x: -w, y: -h, z: -d} ] s.quads = [ new QuadFace(0, 1, 2, 3), new QuadFace(1, 5, 6, 2), new QuadFace(5, 4, 7, 6), new QuadFace(4, 0, 3, 7), new QuadFace(0, 4, 5, 1), new QuadFace(2, 6, 7, 3) ] @rebuildMeta(s) # Cube makeCube: (whd) -> @makeBox(whd, whd, whd) # Icosahedron makeTwenty: (w) -> X = w Z = X * (Math.sqrt(5) + 1.0) / 2.0 s = new Shape() s.vertices = [ {x: -X, y: 0.0, z: Z}, {x: X, y: 0.0, z: Z}, {x: -X, y: 0.0, z: -Z}, {x: X, y: 0.0, z: -Z}, {x: 0.0, y: Z, z: X}, {x: 0.0, y: Z, z: -X}, {x: 0.0, y: -Z, z: X}, {x: 0.0, y: -Z, z: -X}, {x: Z, y: X, z: 0.0}, {x: -Z, y: X, z: 0.0}, {x: Z, y: -X, z: 0.0}, {x: -Z, y: -X, z: 0.0} ] s.quads = [ new QuadFace(1, 4, 0), new QuadFace(4, 9, 0), new QuadFace(4, 5, 9), new QuadFace(8, 5, 4), new QuadFace(1, 8, 4), new QuadFace(1, 10, 8), new QuadFace(10, 3, 8), new QuadFace(8, 3, 5), new QuadFace(3, 2, 5), new QuadFace(3, 7, 2), new QuadFace(3, 10, 7), new QuadFace(10, 6, 7), new QuadFace(6, 11, 7), new QuadFace(6, 0, 11), new QuadFace(6, 1, 0), new QuadFace(10, 1, 6), new QuadFace(11, 0, 9), new QuadFace(2, 11, 9), new QuadFace(5, 2, 9), new QuadFace(11, 2, 7), ] @rebuildMeta(s)
213808
# # JSCube # # Draw 3D objects pixel by pixel on 2D HTML5 canvas # https://github.com/linusyang/jscube # # Copyright (c) 2013 <NAME> # @ShapeUtil = rebuildMeta: (shape) -> vertices = shape.vertices for qf in shape.quads vert0 = vertices[qf.i0] vert1 = vertices[qf.i1] vert2 = vertices[qf.i2] vec01 = VectorUtil.subPoints3d vert1, vert0 vec02 = VectorUtil.subPoints3d vert2, vert0 n1 = VectorUtil.crossProduct vec01, vec02 if qf.isTriangle() n2 = n1 centroid = MatrixUtil.averagePoints [vert0, vert1, vert2] else vert3 = vertices[qf.i3]; vec03 = VectorUtil.subPoints3d vert3, vert0 n2 = VectorUtil.crossProduct vec02, vec03 centroid = MatrixUtil.averagePoints [vert0, vert1, vert2, vert3] qf.centroid = centroid qf.normal1 = n1 qf.normal2 = n2 shape # 4 -- 0 # /| /| +y # 5 -- 1 | |__ +x # | 7 -|-3 / # |/ |/ +z # 6 -- 2 makeBox: (w, h, d) -> s = new Shape() s.vertices = [ {x: w, y: h, z: -d}, {x: w, y: h, z: d}, {x: w, y: -h, z: d}, {x: w, y: -h, z: -d}, {x: -w, y: h, z: -d}, {x: -w, y: h, z: d}, {x: -w, y: -h, z: d}, {x: -w, y: -h, z: -d} ] s.quads = [ new QuadFace(0, 1, 2, 3), new QuadFace(1, 5, 6, 2), new QuadFace(5, 4, 7, 6), new QuadFace(4, 0, 3, 7), new QuadFace(0, 4, 5, 1), new QuadFace(2, 6, 7, 3) ] @rebuildMeta(s) # Cube makeCube: (whd) -> @makeBox(whd, whd, whd) # Icosahedron makeTwenty: (w) -> X = w Z = X * (Math.sqrt(5) + 1.0) / 2.0 s = new Shape() s.vertices = [ {x: -X, y: 0.0, z: Z}, {x: X, y: 0.0, z: Z}, {x: -X, y: 0.0, z: -Z}, {x: X, y: 0.0, z: -Z}, {x: 0.0, y: Z, z: X}, {x: 0.0, y: Z, z: -X}, {x: 0.0, y: -Z, z: X}, {x: 0.0, y: -Z, z: -X}, {x: Z, y: X, z: 0.0}, {x: -Z, y: X, z: 0.0}, {x: Z, y: -X, z: 0.0}, {x: -Z, y: -X, z: 0.0} ] s.quads = [ new QuadFace(1, 4, 0), new QuadFace(4, 9, 0), new QuadFace(4, 5, 9), new QuadFace(8, 5, 4), new QuadFace(1, 8, 4), new QuadFace(1, 10, 8), new QuadFace(10, 3, 8), new QuadFace(8, 3, 5), new QuadFace(3, 2, 5), new QuadFace(3, 7, 2), new QuadFace(3, 10, 7), new QuadFace(10, 6, 7), new QuadFace(6, 11, 7), new QuadFace(6, 0, 11), new QuadFace(6, 1, 0), new QuadFace(10, 1, 6), new QuadFace(11, 0, 9), new QuadFace(2, 11, 9), new QuadFace(5, 2, 9), new QuadFace(11, 2, 7), ] @rebuildMeta(s)
true
# # JSCube # # Draw 3D objects pixel by pixel on 2D HTML5 canvas # https://github.com/linusyang/jscube # # Copyright (c) 2013 PI:NAME:<NAME>END_PI # @ShapeUtil = rebuildMeta: (shape) -> vertices = shape.vertices for qf in shape.quads vert0 = vertices[qf.i0] vert1 = vertices[qf.i1] vert2 = vertices[qf.i2] vec01 = VectorUtil.subPoints3d vert1, vert0 vec02 = VectorUtil.subPoints3d vert2, vert0 n1 = VectorUtil.crossProduct vec01, vec02 if qf.isTriangle() n2 = n1 centroid = MatrixUtil.averagePoints [vert0, vert1, vert2] else vert3 = vertices[qf.i3]; vec03 = VectorUtil.subPoints3d vert3, vert0 n2 = VectorUtil.crossProduct vec02, vec03 centroid = MatrixUtil.averagePoints [vert0, vert1, vert2, vert3] qf.centroid = centroid qf.normal1 = n1 qf.normal2 = n2 shape # 4 -- 0 # /| /| +y # 5 -- 1 | |__ +x # | 7 -|-3 / # |/ |/ +z # 6 -- 2 makeBox: (w, h, d) -> s = new Shape() s.vertices = [ {x: w, y: h, z: -d}, {x: w, y: h, z: d}, {x: w, y: -h, z: d}, {x: w, y: -h, z: -d}, {x: -w, y: h, z: -d}, {x: -w, y: h, z: d}, {x: -w, y: -h, z: d}, {x: -w, y: -h, z: -d} ] s.quads = [ new QuadFace(0, 1, 2, 3), new QuadFace(1, 5, 6, 2), new QuadFace(5, 4, 7, 6), new QuadFace(4, 0, 3, 7), new QuadFace(0, 4, 5, 1), new QuadFace(2, 6, 7, 3) ] @rebuildMeta(s) # Cube makeCube: (whd) -> @makeBox(whd, whd, whd) # Icosahedron makeTwenty: (w) -> X = w Z = X * (Math.sqrt(5) + 1.0) / 2.0 s = new Shape() s.vertices = [ {x: -X, y: 0.0, z: Z}, {x: X, y: 0.0, z: Z}, {x: -X, y: 0.0, z: -Z}, {x: X, y: 0.0, z: -Z}, {x: 0.0, y: Z, z: X}, {x: 0.0, y: Z, z: -X}, {x: 0.0, y: -Z, z: X}, {x: 0.0, y: -Z, z: -X}, {x: Z, y: X, z: 0.0}, {x: -Z, y: X, z: 0.0}, {x: Z, y: -X, z: 0.0}, {x: -Z, y: -X, z: 0.0} ] s.quads = [ new QuadFace(1, 4, 0), new QuadFace(4, 9, 0), new QuadFace(4, 5, 9), new QuadFace(8, 5, 4), new QuadFace(1, 8, 4), new QuadFace(1, 10, 8), new QuadFace(10, 3, 8), new QuadFace(8, 3, 5), new QuadFace(3, 2, 5), new QuadFace(3, 7, 2), new QuadFace(3, 10, 7), new QuadFace(10, 6, 7), new QuadFace(6, 11, 7), new QuadFace(6, 0, 11), new QuadFace(6, 1, 0), new QuadFace(10, 1, 6), new QuadFace(11, 0, 9), new QuadFace(2, 11, 9), new QuadFace(5, 2, 9), new QuadFace(11, 2, 7), ] @rebuildMeta(s)
[ { "context": "s\",\"Prov\",\"Eccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"", "end": 505, "score": 0.7877874970436096, "start": 502, "tag": "NAME", "value": "Dan" }, { "context": "ov\",\"Eccl\",\"Song\",\"Isa\"...
lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/sw/spec.coffee
saiba-mais/bible-lessons
149
bcv_parser = require("../../js/sw_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","Dan","Hos","Joel","Amos","Obad","Jonah","Mic","Nah","Hab","Zeph","Hag","Zech","Mal","Matt","Mark","Luke","John","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gen (sw)", -> ` expect(p.parse("Kitabu cha Kwanza cha Musa 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Mwanzo 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Mwa 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA KWANZA CHA MUSA 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("MWANZO 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("MWA 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Exod (sw)", -> ` expect(p.parse("Kitabu cha Pili cha Musa 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Kutoka 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Kut 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA PILI CHA MUSA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("KUTOKA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("KUT 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bel (sw)", -> ` expect(p.parse("Danieli na Makuhani wa Beli 1:1").osis()).toEqual("Bel.1.1") expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lev (sw)", -> ` expect(p.parse("Kitabu cha Tatu cha Musa 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Mambo ya Walawi 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Walawi 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Law 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Wal 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA TATU CHA MUSA 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("MAMBO YA WALAWI 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("WALAWI 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LAW 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("WAL 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Num (sw)", -> ` expect(p.parse("Kitabu cha Nne cha Musa 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Hesabu 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Hes 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA NNE CHA MUSA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("HESABU 1:1").osis()).toEqual("Num.1.1") expect(p.parse("HES 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sir (sw)", -> ` expect(p.parse("Yoshua bin Sira 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Sira 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("YbS 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Wis (sw)", -> ` expect(p.parse("Hekima ya Solomoni 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Hekima 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Hek 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lam (sw)", -> ` expect(p.parse("Maombolezo ya Yeremia 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Maombolezo 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Mao 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Omb 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("MAOMBOLEZO YA YEREMIA 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("MAOMBOLEZO 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("MAO 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("OMB 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: EpJer (sw)", -> ` expect(p.parse("Barua ya Yeremia 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rev (sw)", -> ` expect(p.parse("Ufunua wa Yohana 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ufunuo wa Yohana 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ufunuo wa Yohane 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ufunuo 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ufu 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Uf 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("UFUNUA WA YOHANA 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UFUNUO WA YOHANA 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UFUNUO WA YOHANE 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UFUNUO 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UFU 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UF 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrMan (sw)", -> ` expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Deut (sw)", -> ` expect(p.parse("Kitabu cha Tano cha Musa 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kumbukumbu la Sheria 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kumbukumbu la Torati 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kumbukumbu 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kumb 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kum 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA TANO CHA MUSA 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUMBUKUMBU LA SHERIA 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUMBUKUMBU LA TORATI 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUMBUKUMBU 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUMB 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUM 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book Josh (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Josh (sw)", -> ` expect(p.parse("Yoshua 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Yos 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("YOSHUA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("YOS 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Judg (sw)", -> ` expect(p.parse("Waamuzi 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Waam 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Amu 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("WAAMUZI 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("WAAM 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("AMU 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ruth (sw)", -> ` expect(p.parse("Kitabu cha Ruthi 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Kitabu cha Ruthu 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruthi 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruthu 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA RUTHI 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("KITABU CHA RUTHU 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTHI 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTHU 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Esd (sw)", -> ` expect(p.parse("Kitabu cha Kwanza cha Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("Kwanza Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("1. Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("I. Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("1 Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("I Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Esd (sw)", -> ` expect(p.parse("Kitabu cha Pili cha Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("Pili Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("II. Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("2. Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("II Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("2 Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Isa (sw)", -> ` expect(p.parse("Isaya 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Is 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("ISAYA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("IS 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Sam (sw)", -> ` expect(p.parse("Kitabu cha Pili cha Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Pili Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Pili Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Samueli II 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Pili Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA PILI CHA SAMUELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("PILI SAMUELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("PILI SAMWELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAMUELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAMWELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAMUELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAMWELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAMUELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAMWELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SAMUELI II 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMUELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMWELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("PILI SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Sam (sw)", -> ` expect(p.parse("Kitabu cha Kwanza cha Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Kwanza Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Kwanza Samweli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Samweli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Samweli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Kwanza Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Samweli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Samweli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Samueli I 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA KWANZA CHA SAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("KWANZA SAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("KWANZA SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("KWANZA SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("SAMUELI I 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Kgs (sw)", -> ` expect(p.parse("Kitabu cha Pili cha Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Pili Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Wafalme II 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Pili Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA PILI CHA WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("PILI WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("WAFALME II 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("PILI FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Kgs (sw)", -> ` expect(p.parse("Kitabu cha Kwanza cha Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Kwanza Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Kwanza Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Wafalme I 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA KWANZA CHA WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("KWANZA WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("KWANZA FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("WAFALME I 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Chr (sw)", -> ` expect(p.parse("Pili Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Mambo ya Nyakati II 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Pili Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1") p.include_apocrypha(false) expect(p.parse("PILI MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("MAMBO YA NYAKATI II 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("PILI NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Chr (sw)", -> ` expect(p.parse("Kwanza Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Mambo ya Nyakati I 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Kwanza Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1") p.include_apocrypha(false) expect(p.parse("KWANZA MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("MAMBO YA NYAKATI I 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("KWANZA NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezra (sw)", -> ` expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezr 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZR 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Neh (sw)", -> ` expect(p.parse("Nehemia 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEHEMIA 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: GkEsth (sw)", -> ` expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Esth (sw)", -> ` expect(p.parse("Esther 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Ester 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esta 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTHER 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTER 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTA 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Job (sw)", -> ` expect(p.parse("Kitabu cha Ayubu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Kitabu cha Yobu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Ayubu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Yobu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Ayu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Yob 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA AYUBU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("KITABU CHA YOBU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("AYUBU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("YOBU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("AYU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") expect(p.parse("YOB 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ps (sw)", -> ` expect(p.parse("Zaburi 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Zab 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("ZABURI 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("ZAB 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrAzar (sw)", -> ` expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Prov (sw)", -> ` expect(p.parse("Methali 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Mithali 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Meth 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Mith 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Mit 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("METHALI 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("MITHALI 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("METH 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("MITH 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("MIT 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eccl (sw)", -> ` expect(p.parse("Mhubiri 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Mhu 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("MHUBIRI 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("MHU 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: SgThree (sw)", -> ` expect(p.parse("Wimbo wa Vijana Watatu 1:1").osis()).toEqual("SgThree.1.1") expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Song (sw)", -> ` expect(p.parse("Wimbo Ulio Bora 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Wimbo Bora 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Wim 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("WIMBO ULIO BORA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("WIMBO BORA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("WIM 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book Jer (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jer (sw)", -> ` expect(p.parse("Yeremia 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Yer 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("YEREMIA 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("YER 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book Ezek (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezek (sw)", -> ` expect(p.parse("Ezekieli 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Eze 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("EZEKIELI 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZE 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book Dan (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Dan (sw)", -> ` expect(p.parse("Danieli 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("DANIELI 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hos (sw)", -> ` expect(p.parse("Hosea 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("HOSEA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Joel (sw)", -> ` expect(p.parse("Yoeli 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Yoe 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("YOELI 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("YOE 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Amos (sw)", -> ` expect(p.parse("Amosi 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amo 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("AMOSI 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMO 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Obad (sw)", -> ` expect(p.parse("Obadia 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Oba 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Ob 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("OBADIA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OB 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book Jonah (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jonah (sw)", -> ` expect(p.parse("Jonah 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Yona 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Yon 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("YONA 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("YON 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book Mic (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mic (sw)", -> ` expect(p.parse("Mika 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mik 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MIKA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIK 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Nah (sw)", -> ` expect(p.parse("Nahumu 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nahum 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAHUMU 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAHUM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hab (sw)", -> ` expect(p.parse("Habakuki 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("HABAKUKI 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zeph (sw)", -> ` expect(p.parse("Sefania 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sef 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SEFANIA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SEF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hag (sw)", -> ` expect(p.parse("Hagai 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("HAGAI 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zech (sw)", -> ` expect(p.parse("Zekaria 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zek 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("ZEKARIA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZEK 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mal (sw)", -> ` expect(p.parse("Malaki 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALAKI 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book Matt (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Matt (sw)", -> ` expect(p.parse("Injili ya Mathayo 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mathayo 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matayo 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Math 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mat 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1") p.include_apocrypha(false) expect(p.parse("INJILI YA MATHAYO 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATHAYO 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATAYO 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATH 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MAT 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1") ` true describe "Localized book Mark (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mark (sw)", -> ` expect(p.parse("Injili ya Marko 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Marko 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mk 1:1").osis()).toEqual("Mark.1.1") p.include_apocrypha(false) expect(p.parse("INJILI YA MARKO 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARKO 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MK 1:1").osis()).toEqual("Mark.1.1") ` true describe "Localized book Luke (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Luke (sw)", -> ` expect(p.parse("Injili ya Luka 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luka 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("INJILI YA LUKA 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKA 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book 1John (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1John (sw)", -> ` expect(p.parse("Waraka wa Kwanza wa Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Barua ya Kwanza ya Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Kwanza Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Kwanza Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Kwanza Yoh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Yohane I 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yoh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yoh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yoh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yoh 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA WA YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("BARUA YA KWANZA YA YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("KWANZA YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("KWANZA YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("KWANZA YOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("YOHANE I 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOH 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book 2John (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2John (sw)", -> ` expect(p.parse("Waraka wa Pili wa Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Barua ya Pili ya Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Pili Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Pili Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Yohane II 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Pili Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI WA YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("BARUA YA PILI YA YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("PILI YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("PILI YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("YOHANE II 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("PILI YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book 3John (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3John (sw)", -> ` expect(p.parse("Waraka wa Tatu wa Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Barua ya Tatu ya Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Tatu Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Tatu Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Yohane III 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Tatu Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA TATU WA YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("BARUA YA TATU YA YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("TATU YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("TATU YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("YOHANE III 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("TATU YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book John (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: John (sw)", -> ` expect(p.parse("Injili ya Yohana 1:1").osis()).toEqual("John.1.1") expect(p.parse("Injili ya Yohane 1:1").osis()).toEqual("John.1.1") expect(p.parse("Yohana 1:1").osis()).toEqual("John.1.1") expect(p.parse("Yohane 1:1").osis()).toEqual("John.1.1") expect(p.parse("John 1:1").osis()).toEqual("John.1.1") expect(p.parse("Yoh 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("INJILI YA YOHANA 1:1").osis()).toEqual("John.1.1") expect(p.parse("INJILI YA YOHANE 1:1").osis()).toEqual("John.1.1") expect(p.parse("YOHANA 1:1").osis()).toEqual("John.1.1") expect(p.parse("YOHANE 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1") expect(p.parse("YOH 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Acts (sw)", -> ` expect(p.parse("Matendo ya Mitume 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Matendo 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Mdo 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("MATENDO YA MITUME 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("MATENDO 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("MDO 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rom (sw)", -> ` expect(p.parse("Waraka kwa Waroma 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Waraka kwa Warumi 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Barua kwa Waroma 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Waroma 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Warumi 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rum 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAROMA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("WARAKA KWA WARUMI 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BARUA KWA WAROMA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("WAROMA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("WARUMI 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RUM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Cor (sw)", -> ` expect(p.parse("Waraka wa Pili kwa Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Barua ya Pili kwa Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Waraka wa Pili kwa Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Pili Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Pili Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Wakorintho II 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Pili Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI KWA WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("BARUA YA PILI KWA WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("WARAKA WA PILI KWA WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("PILI WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("PILI WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("WAKORINTHO II 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("PILI KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Cor (sw)", -> ` expect(p.parse("Waraka wa Kwanza kwa Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Barua ya Kwanza kwa Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Waraka wa Kwanza kwa Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Kwanza Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Kwanza Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Wakorintho I 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Kwanza Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA KWA WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("BARUA YA KWANZA KWA WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("WARAKA WA KWANZA KWA WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("KWANZA WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("KWANZA WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("WAKORINTHO I 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("KWANZA KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gal (sw)", -> ` expect(p.parse("Barua kwa Wagalatia 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Wagalatia 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("BARUA KWA WAGALATIA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("WAGALATIA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eph (sw)", -> ` expect(p.parse("Waraka kwa Waefeso 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Barua kwa Waefeso 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Waefeso 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efe 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAEFESO 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("BARUA KWA WAEFESO 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("WAEFESO 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFE 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1") ` true describe "Localized book Phil (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phil (sw)", -> ` expect(p.parse("Waraka kwa Wafilipi 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Barua kwa Wafilipi 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Wafilipi 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Flp 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAFILIPI 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BARUA KWA WAFILIPI 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("WAFILIPI 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FLP 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Col (sw)", -> ` expect(p.parse("Waraka kwa Wakolosai 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Barua kwa Wakolosai 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Wakolosai 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAKOLOSAI 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BARUA KWA WAKOLOSAI 1:1").osis()).toEqual("Col.1.1") expect(p.parse("WAKOLOSAI 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Thess (sw)", -> ` expect(p.parse("Waraka wa Pili kwa Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Waraka wa Pili kwa Wathesaloniki 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Barua ya Pili kwa Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Pili Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Wathesalonike II 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Pili Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Pili The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Pili Th 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Th 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Th 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Th 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Th 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI KWA WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("WARAKA WA PILI KWA WATHESALONIKI 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("BARUA YA PILI KWA WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("PILI WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("WATHESALONIKE II 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("PILI THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("PILI THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("PILI TH 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. TH 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. TH 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II TH 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TH 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Thess (sw)", -> ` expect(p.parse("Waraka wa Kwanza kwa Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Waraka wa Kwanza kwa Wathesaloniki 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Barua ya Kwanza kwa Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Kwanza Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Wathesalonike I 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Kwanza Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Kwanza The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Kwanza Th 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Th 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Th 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Th 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Th 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA KWA WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("WARAKA WA KWANZA KWA WATHESALONIKI 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("BARUA YA KWANZA KWA WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("KWANZA WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("WATHESALONIKE I 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("KWANZA THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("KWANZA THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("KWANZA TH 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. TH 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. TH 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TH 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I TH 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Tim (sw)", -> ` expect(p.parse("Waraka wa Pili kwa Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Barua ya Pili kwa Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Pili Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Timotheo II 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Pili Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI KWA TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("BARUA YA PILI KWA TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("PILI TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("TIMOTHEO II 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("PILI TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Tim (sw)", -> ` expect(p.parse("Waraka wa Kwanza kwa Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Barua ya Kwanza kwa Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Kwanza Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Kwanza Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Timotheo I 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA KWA TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("BARUA YA KWANZA KWA TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("KWANZA TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("KWANZA TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("TIMOTHEO I 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Titus (sw)", -> ` expect(p.parse("Waraka kwa Tito 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Barua kwa Tito 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tito 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA TITO 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BARUA KWA TITO 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITO 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phlm (sw)", -> ` expect(p.parse("Waraka kwa Filemoni 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Barua kwa Filemoni 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Filemoni 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Film 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Flm 1:1").osis()).toEqual("Phlm.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA FILEMONI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BARUA KWA FILEMONI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILEMONI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FLM 1:1").osis()).toEqual("Phlm.1.1") ` true describe "Localized book Heb (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Heb (sw)", -> ` expect(p.parse("Waraka kwa Waebrania 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Barua kwa Waebrania 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Waebrania 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Ebr 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Eb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAEBRANIA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("BARUA KWA WAEBRANIA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("WAEBRANIA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("EBR 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("EB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jas (sw)", -> ` expect(p.parse("Waraka wa Yakobo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Barua ya Yakobo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Yakobo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Yak 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA YAKOBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("BARUA YA YAKOBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("YAKOBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("YAK 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Pet (sw)", -> ` expect(p.parse("Waraka wa Pili wa Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Barua ya Pili ya Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Pili Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Petro II 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Pili Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI WA PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("BARUA YA PILI YA PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("PILI PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("PETRO II 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("PILI PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Pet (sw)", -> ` expect(p.parse("Waraka wa Kwanza wa Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Barua ya Kwanza ya Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Kwanza Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Kwanza Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Petro I 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA WA PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("BARUA YA KWANZA YA PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("KWANZA PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("KWANZA PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("PETRO I 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book Jude (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jude (sw)", -> ` expect(p.parse("Barua ya Yuda 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Yuda 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Yud 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("BARUA YA YUDA 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("YUDA 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("YUD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Tob (sw)", -> ` expect(p.parse("Tobiti 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jdt (sw)", -> ` expect(p.parse("Yudithi 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Yudith 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Yuditi 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Yudit 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Yudt 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bar (sw)", -> ` expect(p.parse("Baruku 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Baruk 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sus (sw)", -> ` expect(p.parse("Susana 1:1").osis()).toEqual("Sus.1.1") expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Macc (sw)", -> ` expect(p.parse("Kitabu cha Wamakabayo II 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Pili Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II. Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2. Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Wamakabayo II 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2 Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Pili Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II. Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2. Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2 Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3Macc (sw)", -> ` expect(p.parse("Kitabu cha Wamakabayo III 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III. Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("Tatu Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("Wamakabayo III 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3. Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3 Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III. Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("Tatu Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3. Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3 Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 4Macc (sw)", -> ` expect(p.parse("Kitabu cha Wamakabayo IV 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV. Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Nne Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4. Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Wamakabayo IV 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4 Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV. Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Nne Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4. Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4 Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Macc (sw)", -> ` expect(p.parse("Kitabu cha Wamakabayo I 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("Kwanza Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1. Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I. Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1 Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("Wamakabayo I 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("Kwanza Mak 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1. Mak 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I. Mak 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1 Mak 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I Mak 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Localized book John,Jonah (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: John,Jonah (sw)", -> ` expect(p.parse("Yn 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("YN 1:1").osis()).toEqual("John.1.1") ` true describe "Miscellaneous tests", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete" p.include_apocrypha true it "should return the expected language", -> expect(p.languages).toEqual ["sw"] it "should handle ranges (sw)", -> expect(p.parse("Titus 1:1 hadi 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1hadi2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 HADI 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (sw)", -> expect(p.parse("Titus 1:1, sura 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 SURA 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (sw)", -> expect(p.parse("Exod 1:1 mistari 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm MISTARI 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (sw)", -> expect(p.parse("Exod 1:1 taz. 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 TAZ. 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" expect(p.parse("Exod 1:1 taz 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 TAZ 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" expect(p.parse("Exod 1:1 na 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 NA 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (sw)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (sw)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (sw)", -> expect(p.parse("Lev 1 (HN)").osis_and_translations()).toEqual [["Lev.1", "HN"]] expect(p.parse("lev 1 hn").osis_and_translations()).toEqual [["Lev.1", "HN"]] expect(p.parse("Lev 1 (SUV)").osis_and_translations()).toEqual [["Lev.1", "SUV"]] expect(p.parse("lev 1 suv").osis_and_translations()).toEqual [["Lev.1", "SUV"]] it "should handle book ranges (sw)", -> p.set_options {book_alone_strategy: "full", book_range_strategy: "include"} expect(p.parse("Kwanza hadi Tatu Yoh").osis()).toEqual "1John.1-3John.1" it "should handle boundaries (sw)", -> p.set_options {book_alone_strategy: "full"} expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28" expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
65684
bcv_parser = require("../../js/sw_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","<NAME>","<NAME>","<NAME>","<NAME>mos","<NAME>ad","<NAME>","<NAME>","<NAME>ah","Hab","Zeph","Hag","Zech","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gen (sw)", -> ` expect(p.parse("Kitabu cha Kwanza cha Musa 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Mwanzo 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Mwa 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA KWANZA CHA MUSA 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("MWANZO 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("MWA 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Exod (sw)", -> ` expect(p.parse("Kitabu cha Pili cha Musa 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Kutoka 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Kut 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA PILI CHA MUSA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("KUTOKA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("KUT 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bel (sw)", -> ` expect(p.parse("<NAME>i na Makuhani wa Beli 1:1").osis()).toEqual("Bel.1.1") expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lev (sw)", -> ` expect(p.parse("Kitabu cha Tatu cha Musa 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Mambo ya Walawi 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Walawi 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Law 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Wal 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA TATU CHA MUSA 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("MAMBO YA WALAWI 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("WALAWI 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LAW 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("WAL 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Num (sw)", -> ` expect(p.parse("Kitabu cha Nne cha Musa 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Hesabu 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Hes 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA NNE CHA MUSA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("HESABU 1:1").osis()).toEqual("Num.1.1") expect(p.parse("HES 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sir (sw)", -> ` expect(p.parse("<NAME> bin Sira 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Sira 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("YbS 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Wis (sw)", -> ` expect(p.parse("Hekima ya Solomoni 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Hekima 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Hek 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lam (sw)", -> ` expect(p.parse("Maombolezo ya Yeremia 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Maombolezo 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Mao 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Omb 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("MAOMBOLEZO YA YEREMIA 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("MAOMBOLEZO 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("MAO 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("OMB 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: EpJer (sw)", -> ` expect(p.parse("Barua ya Yeremia 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rev (sw)", -> ` expect(p.parse("Ufunua wa Yohana 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ufunuo wa Yohana 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ufunuo wa Yohane 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ufunuo 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ufu 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Uf 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("UFUNUA WA YOHANA 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UFUNUO WA YOHANA 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UFUNUO WA YOHANE 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UFUNUO 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UFU 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UF 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrMan (sw)", -> ` expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Deut (sw)", -> ` expect(p.parse("Kitabu cha Tano cha Musa 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kumbukumbu la Sheria 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kumbukumbu la Torati 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kumbukumbu 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kumb 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kum 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA TANO CHA MUSA 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUMBUKUMBU LA SHERIA 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUMBUKUMBU LA TORATI 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUMBUKUMBU 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUMB 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUM 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book <NAME> (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (sw)", -> ` expect(p.parse("Yoshua 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Yos 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("YOSHUA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("YOS 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Judg (sw)", -> ` expect(p.parse("Waamuzi 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Waam 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Amu 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("WAAMUZI 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("WAAM 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("AMU 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ruth (sw)", -> ` expect(p.parse("Kitabu cha Ruthi 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Kitabu cha Ruthu 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruthi 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruthu 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA RUTHI 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("KITABU CHA RUTHU 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTHI 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTHU 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Esd (sw)", -> ` expect(p.parse("Kitabu cha Kwanza cha Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("Kwanza Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("1. Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("I. Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("1 Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("I Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Esd (sw)", -> ` expect(p.parse("Kitabu cha Pili cha Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("Pili Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("II. Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("2. Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("II Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("2 Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Isa (sw)", -> ` expect(p.parse("Isaya 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Is 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("ISAYA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("IS 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Sam (sw)", -> ` expect(p.parse("Kitabu cha Pili cha Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Pili Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Pili Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Samueli II 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Pili Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("<NAME>ABU CHA PILI CHA SAM<NAME>LI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAM<NAME>LI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAM<NAME>LI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAM<NAME>LI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAMWELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAMUELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAMWELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SAMUELI II 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMUELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMWELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("PILI SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Sam (sw)", -> ` expect(p.parse("Kitabu cha Kwanza cha Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Kwanza Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Kwanza Samweli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Sam<NAME> 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Sam<NAME>li 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. <NAME> 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("<NAME> Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Samweli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Samweli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Samueli I 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. <NAME> 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. <NAME> 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA KWANZA CHA SAM<NAME>LI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("KWANZA SAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("KWANZA SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAM<NAME>LI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAM<NAME>LI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("KWANZA SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("SAMUELI I 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Kgs (sw)", -> ` expect(p.parse("Kitabu cha Pili cha Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Pili Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Wafalme II 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Pili Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA PILI CHA WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("PILI WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("WAFALME II 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("PILI FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Kgs (sw)", -> ` expect(p.parse("Kitabu cha Kwanza cha Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Kwanza Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Kwanza Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Wafalme I 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA KWANZA CHA WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("KWANZA WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("KWANZA FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("WAFALME I 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Chr (sw)", -> ` expect(p.parse("Pili Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Mambo ya Nyakati II 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Pili Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1") p.include_apocrypha(false) expect(p.parse("PILI MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("MAMBO YA NYAKATI II 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("PILI NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Chr (sw)", -> ` expect(p.parse("Kwanza Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Mambo ya Nyakati I 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Kwanza Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1") p.include_apocrypha(false) expect(p.parse("KWANZA MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("MAMBO YA NYAKATI I 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("KWANZA NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezra (sw)", -> ` expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezr 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZR 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Neh (sw)", -> ` expect(p.parse("Nehemia 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEHEMIA 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: GkEsth (sw)", -> ` expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Esth (sw)", -> ` expect(p.parse("Esther 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Ester 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esta 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTHER 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTER 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTA 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Job (sw)", -> ` expect(p.parse("Kitabu cha Ayubu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Kitabu cha Yobu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Ayubu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Yobu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Ayu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Yob 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA AYUBU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("KITABU CHA YOBU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("AYUBU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("YOBU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("AYU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") expect(p.parse("YOB 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ps (sw)", -> ` expect(p.parse("Zaburi 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Zab 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("ZABURI 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("ZAB 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrAzar (sw)", -> ` expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Prov (sw)", -> ` expect(p.parse("Methali 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Mithali 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Meth 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Mith 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Mit 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("METHALI 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("MITHALI 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("METH 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("MITH 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("MIT 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eccl (sw)", -> ` expect(p.parse("Mhubiri 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Mhu 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("MHUBIRI 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("MHU 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: SgThree (sw)", -> ` expect(p.parse("Wimbo wa Vijana Watatu 1:1").osis()).toEqual("SgThree.1.1") expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Song (sw)", -> ` expect(p.parse("Wimbo Ulio Bora 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Wimbo Bora 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Wim 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("WIMBO ULIO BORA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("WIMBO BORA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("WIM 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book Jer (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jer (sw)", -> ` expect(p.parse("Yeremia 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Yer 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("YEREMIA 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("YER 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book Ezek (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezek (sw)", -> ` expect(p.parse("Ezekieli 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Eze 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("EZEKIELI 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZE 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book <NAME> (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (sw)", -> ` expect(p.parse("Danieli 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("DANIELI 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hos (sw)", -> ` expect(p.parse("Hosea 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("HOSEA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Joel (sw)", -> ` expect(p.parse("Yoeli 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Yoe 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("YOELI 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("YOE 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Amos (sw)", -> ` expect(p.parse("Amosi 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amo 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("AMOSI 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMO 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Obad (sw)", -> ` expect(p.parse("Obadia 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Oba 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Ob 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("OBADIA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OB 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book <NAME> (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (sw)", -> ` expect(p.parse("<NAME> 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Yona 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Yon 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("YONA 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("YON 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book <NAME>ic (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mic (sw)", -> ` expect(p.parse("Mika 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mik 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MIKA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIK 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Nah (sw)", -> ` expect(p.parse("Nahumu 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nahum 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAHUMU 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAHUM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hab (sw)", -> ` expect(p.parse("Habakuki 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("HABAKUKI 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zeph (sw)", -> ` expect(p.parse("Sefania 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sef 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SEFANIA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SEF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hag (sw)", -> ` expect(p.parse("Hagai 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("HAGAI 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zech (sw)", -> ` expect(p.parse("Zekaria 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zek 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("ZEKARIA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZEK 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mal (sw)", -> ` expect(p.parse("Malaki 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALAKI 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book <NAME>att (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME>att (sw)", -> ` expect(p.parse("Injili ya Mathayo 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mathayo 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matayo 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Math 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mat 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1") p.include_apocrypha(false) expect(p.parse("INJILI YA MATHAYO 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATHAYO 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATAYO 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATH 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MAT 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1") ` true describe "Localized book Mark (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mark (sw)", -> ` expect(p.parse("Injili ya Marko 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Marko 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mk 1:1").osis()).toEqual("Mark.1.1") p.include_apocrypha(false) expect(p.parse("INJILI YA MARKO 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARKO 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MK 1:1").osis()).toEqual("Mark.1.1") ` true describe "Localized book <NAME> (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (sw)", -> ` expect(p.parse("Injili ya Luka 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luka 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("INJILI YA LUKA 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKA 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book <NAME> (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (sw)", -> ` expect(p.parse("Waraka wa Kwanza wa Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Barua ya Kwanza ya Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Kwanza Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Kwanza Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Kwanza Yoh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Yohane I 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yoh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yoh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yoh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yoh 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA WA YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("BARUA YA KWANZA YA YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("KWANZA YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("KWANZA YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("KWANZA YOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("YOHANE I 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JO<NAME> 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOH 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book <NAME>John (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2John (sw)", -> ` expect(p.parse("Waraka wa Pili wa Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Barua ya Pili ya Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Pili Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Pili Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Yohane II 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Pili Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI WA YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("BARUA YA PILI YA YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("PILI YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("PILI YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("YOHANE II 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("PILI YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book 3John (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3John (sw)", -> ` expect(p.parse("Waraka wa Tatu wa Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Barua ya Tatu ya Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Tatu Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Tatu Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Yohane III 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Tatu Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA TATU WA YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("BARUA YA TATU YA YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("TATU YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("TATU YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("YOHANE III 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("TATU YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book John (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (sw)", -> ` expect(p.parse("Injili ya Yohana 1:1").osis()).toEqual("John.1.1") expect(p.parse("Injili ya Yohane 1:1").osis()).toEqual("John.1.1") expect(p.parse("Yohana 1:1").osis()).toEqual("John.1.1") expect(p.parse("Yohane 1:1").osis()).toEqual("John.1.1") expect(p.parse("John 1:1").osis()).toEqual("John.1.1") expect(p.parse("Yoh 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("INJILI YA YOHANA 1:1").osis()).toEqual("John.1.1") expect(p.parse("INJILI YA YOHANE 1:1").osis()).toEqual("John.1.1") expect(p.parse("YOHANA 1:1").osis()).toEqual("John.1.1") expect(p.parse("YOHANE 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1") expect(p.parse("YOH 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Acts (sw)", -> ` expect(p.parse("Matendo ya Mitume 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Matendo 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Mdo 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("MATENDO YA MITUME 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("MATENDO 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("MDO 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rom (sw)", -> ` expect(p.parse("Waraka kwa Waroma 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Waraka kwa Warumi 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Barua kwa Waroma 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Waroma 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Warumi 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rum 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAROMA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("WARAKA KWA WARUMI 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BARUA KWA WAROMA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("WAROMA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("WARUMI 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RUM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Cor (sw)", -> ` expect(p.parse("Waraka wa Pili kwa Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Barua ya Pili kwa Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Waraka wa Pili kwa Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Pili Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Pili Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Wakorintho II 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Pili Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI KWA WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("BARUA YA PILI KWA WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("WARAKA WA PILI KWA WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("PILI WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("PILI WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("WAKORINTHO II 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("PILI KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Cor (sw)", -> ` expect(p.parse("Waraka wa Kwanza kwa Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Barua ya Kwanza kwa Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Waraka wa Kwanza kwa Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Kwanza Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Kwanza Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Wakorintho I 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Kwanza Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA KWA WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("BARUA YA KWANZA KWA WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("WARAKA WA KWANZA KWA WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("KWANZA WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("KWANZA WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("WAKORINTHO I 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("KWANZA KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gal (sw)", -> ` expect(p.parse("Barua kwa Wagalatia 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Wagalatia 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("BARUA KWA WAGALATIA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("WAGALATIA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eph (sw)", -> ` expect(p.parse("Waraka kwa Waefeso 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Barua kwa Waefeso 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Waefeso 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efe 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAEFESO 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("BARUA KWA WAEFESO 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("WAEFESO 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFE 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1") ` true describe "Localized book Phil (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (sw)", -> ` expect(p.parse("Waraka kwa Wafilipi 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Barua kwa Wafilipi 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Wafilipi 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Flp 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAFILIPI 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BARUA KWA WAFILIPI 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("WAFILIPI 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FLP 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Col (sw)", -> ` expect(p.parse("Waraka kwa Wakolosai 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Barua kwa Wakolosai 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Wakolosai 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAKOLOSAI 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BARUA KWA WAKOLOSAI 1:1").osis()).toEqual("Col.1.1") expect(p.parse("WAKOLOSAI 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Thess (sw)", -> ` expect(p.parse("Waraka wa Pili kwa Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Waraka wa Pili kwa Wathesaloniki 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Barua ya Pili kwa Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Pili Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Wathesalonike II 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Pili Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Pili The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Pili Th 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Th 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Th 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Th 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Th 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI KWA WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("WARAKA WA PILI KWA WATHESALONIKI 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("BARUA YA PILI KWA WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("PILI WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("WATHESALONIKE II 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("PILI THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("PILI THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("PILI TH 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. TH 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. TH 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II TH 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TH 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Thess (sw)", -> ` expect(p.parse("Waraka wa Kwanza kwa Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Waraka wa Kwanza kwa Wathesaloniki 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Barua ya Kwanza kwa Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Kwanza Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Wathesalonike I 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Kwanza Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Kwanza The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Kwanza Th 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Th 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Th 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Th 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Th 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA KWA WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("WARAKA WA KWANZA KWA WATHESALONIKI 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("BARUA YA KWANZA KWA WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("KWANZA WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("WATHESALONIKE I 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("KWANZA THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("KWANZA THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("KWANZA TH 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. TH 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. TH 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TH 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I TH 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Tim (sw)", -> ` expect(p.parse("Waraka wa Pili kwa Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Barua ya Pili kwa Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Pili Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Timotheo II 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Pili Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI KWA TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("BARUA YA PILI KWA TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("PILI TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("TIMOTHEO II 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("PILI TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Tim (sw)", -> ` expect(p.parse("Waraka wa Kwanza kwa Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Barua ya Kwanza kwa Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Kwanza Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Kwanza Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Timotheo I 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA KWA TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("BARUA YA KWANZA KWA TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("KWANZA TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("KWANZA TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("TIMOTHEO I 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Titus (sw)", -> ` expect(p.parse("Waraka kwa Tito 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Barua kwa Tito 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tito 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA TITO 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BARUA KWA TITO 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITO 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phlm (sw)", -> ` expect(p.parse("Waraka kwa Filemoni 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Barua kwa Filemoni 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Filemoni 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Film 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Flm 1:1").osis()).toEqual("Phlm.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA FILEMONI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BARUA KWA FILEMONI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILEMONI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FLM 1:1").osis()).toEqual("Phlm.1.1") ` true describe "Localized book Heb (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Heb (sw)", -> ` expect(p.parse("Waraka kwa Waebrania 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Barua kwa Waebrania 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Waebrania 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Ebr 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Eb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAEBRANIA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("BARUA KWA WAEBRANIA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("WAEBRANIA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("EBR 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("EB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jas (sw)", -> ` expect(p.parse("Waraka wa Yakobo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Barua ya Yakobo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Yakobo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Yak 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA YAKOBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("BARUA YA YAKOBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("YAKOBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("YAK 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Pet (sw)", -> ` expect(p.parse("Waraka wa Pili wa Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Barua ya Pili ya Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Pili Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Petro II 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Pili Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI WA PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("BARUA YA PILI YA PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("PILI PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("PETRO II 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("PILI PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Pet (sw)", -> ` expect(p.parse("Waraka wa Kwanza wa Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Barua ya Kwanza ya Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Kwanza Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Kwanza Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Petro I 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA WA PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("BARUA YA KWANZA YA PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("KWANZA PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("KWANZA PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("PETRO I 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book Jude (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jude (sw)", -> ` expect(p.parse("Barua ya Yuda 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Yuda 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Yud 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("BARUA YA YUDA 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("YUDA 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("YUD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Tob (sw)", -> ` expect(p.parse("Tobiti 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jdt (sw)", -> ` expect(p.parse("Yudithi 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Yudith 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Yuditi 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Yudit 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Yudt 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bar (sw)", -> ` expect(p.parse("Baruku 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Baruk 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sus (sw)", -> ` expect(p.parse("Susana 1:1").osis()).toEqual("Sus.1.1") expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Macc (sw)", -> ` expect(p.parse("Kitabu cha Wamakabayo II 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Pili Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II. Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2. Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Wamakabayo II 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2 Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Pili Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II. Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2. Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2 Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3Macc (sw)", -> ` expect(p.parse("Kitabu cha Wamakabayo III 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III. Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("Tatu Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("Wamakabayo III 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3. Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3 Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III. Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("Tatu Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3. Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3 Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 4Macc (sw)", -> ` expect(p.parse("Kitabu cha Wamakabayo IV 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV. Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Nne Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4. Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Wamakabayo IV 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4 Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV. Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Nne Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4. Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4 Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Macc (sw)", -> ` expect(p.parse("Kitabu cha Wamakabayo I 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("Kwanza Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1. Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I. Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1 Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("Wamakabayo I 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("Kwanza Mak 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1. Mak 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I. Mak 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1 Mak 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I Mak 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Localized book <NAME>,Jon<NAME> (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME>,<NAME> (sw)", -> ` expect(p.parse("Yn 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("YN 1:1").osis()).toEqual("John.1.1") ` true describe "Miscellaneous tests", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete" p.include_apocrypha true it "should return the expected language", -> expect(p.languages).toEqual ["sw"] it "should handle ranges (sw)", -> expect(p.parse("Titus 1:1 hadi 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1hadi2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 HADI 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (sw)", -> expect(p.parse("Titus 1:1, sura 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 SURA 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (sw)", -> expect(p.parse("Exod 1:1 mistari 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm MISTARI 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (sw)", -> expect(p.parse("Exod 1:1 taz. 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 TAZ. 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" expect(p.parse("Exod 1:1 taz 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 TAZ 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" expect(p.parse("Exod 1:1 na 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 NA 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (sw)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (sw)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (sw)", -> expect(p.parse("Lev 1 (HN)").osis_and_translations()).toEqual [["Lev.1", "HN"]] expect(p.parse("lev 1 hn").osis_and_translations()).toEqual [["Lev.1", "HN"]] expect(p.parse("Lev 1 (SUV)").osis_and_translations()).toEqual [["Lev.1", "SUV"]] expect(p.parse("lev 1 suv").osis_and_translations()).toEqual [["Lev.1", "SUV"]] it "should handle book ranges (sw)", -> p.set_options {book_alone_strategy: "full", book_range_strategy: "include"} expect(p.parse("K<NAME> Yoh").osis()).toEqual "1John.1-3John.1" it "should handle boundaries (sw)", -> p.set_options {book_alone_strategy: "full"} expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28" expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
true
bcv_parser = require("../../js/sw_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PImos","PI:NAME:<NAME>END_PIad","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PIah","Hab","Zeph","Hag","Zech","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gen (sw)", -> ` expect(p.parse("Kitabu cha Kwanza cha Musa 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Mwanzo 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Mwa 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA KWANZA CHA MUSA 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("MWANZO 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("MWA 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Exod (sw)", -> ` expect(p.parse("Kitabu cha Pili cha Musa 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Kutoka 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Kut 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA PILI CHA MUSA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("KUTOKA 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("KUT 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bel (sw)", -> ` expect(p.parse("PI:NAME:<NAME>END_PIi na Makuhani wa Beli 1:1").osis()).toEqual("Bel.1.1") expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lev (sw)", -> ` expect(p.parse("Kitabu cha Tatu cha Musa 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Mambo ya Walawi 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Walawi 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Law 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Wal 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA TATU CHA MUSA 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("MAMBO YA WALAWI 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("WALAWI 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LAW 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("WAL 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Num (sw)", -> ` expect(p.parse("Kitabu cha Nne cha Musa 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Hesabu 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Hes 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA NNE CHA MUSA 1:1").osis()).toEqual("Num.1.1") expect(p.parse("HESABU 1:1").osis()).toEqual("Num.1.1") expect(p.parse("HES 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sir (sw)", -> ` expect(p.parse("PI:NAME:<NAME>END_PI bin Sira 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Sira 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("YbS 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Wis (sw)", -> ` expect(p.parse("Hekima ya Solomoni 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Hekima 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Hek 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lam (sw)", -> ` expect(p.parse("Maombolezo ya Yeremia 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Maombolezo 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Mao 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Omb 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("MAOMBOLEZO YA YEREMIA 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("MAOMBOLEZO 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("MAO 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("OMB 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: EpJer (sw)", -> ` expect(p.parse("Barua ya Yeremia 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rev (sw)", -> ` expect(p.parse("Ufunua wa Yohana 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ufunuo wa Yohana 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ufunuo wa Yohane 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ufunuo 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Ufu 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Uf 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("UFUNUA WA YOHANA 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UFUNUO WA YOHANA 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UFUNUO WA YOHANE 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UFUNUO 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UFU 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("UF 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrMan (sw)", -> ` expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Deut (sw)", -> ` expect(p.parse("Kitabu cha Tano cha Musa 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kumbukumbu la Sheria 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kumbukumbu la Torati 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kumbukumbu 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kumb 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Kum 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA TANO CHA MUSA 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUMBUKUMBU LA SHERIA 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUMBUKUMBU LA TORATI 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUMBUKUMBU 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUMB 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("KUM 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (sw)", -> ` expect(p.parse("Yoshua 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Yos 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("YOSHUA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("YOS 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Judg (sw)", -> ` expect(p.parse("Waamuzi 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Waam 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Amu 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("WAAMUZI 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("WAAM 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("AMU 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ruth (sw)", -> ` expect(p.parse("Kitabu cha Ruthi 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Kitabu cha Ruthu 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruthi 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruthu 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA RUTHI 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("KITABU CHA RUTHU 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTHI 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTHU 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Esd (sw)", -> ` expect(p.parse("Kitabu cha Kwanza cha Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("Kwanza Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("1. Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("I. Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("1 Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("I Ezra 1:1").osis()).toEqual("1Esd.1.1") expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Esd (sw)", -> ` expect(p.parse("Kitabu cha Pili cha Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("Pili Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("II. Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("2. Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("II Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("2 Ezra 1:1").osis()).toEqual("2Esd.1.1") expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Isa (sw)", -> ` expect(p.parse("Isaya 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Is 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("ISAYA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("IS 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Sam (sw)", -> ` expect(p.parse("Kitabu cha Pili cha Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Pili Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Pili Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Samueli II 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Samueli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Samweli 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Pili Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("PI:NAME:<NAME>END_PIABU CHA PILI CHA SAMPI:NAME:<NAME>END_PILI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAMPI:NAME:<NAME>END_PILI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAMPI:NAME:<NAME>END_PILI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAMPI:NAME:<NAME>END_PILI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAMWELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAMUELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAMWELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SAMUELI II 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMUELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMWELI 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("PILI SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Sam (sw)", -> ` expect(p.parse("Kitabu cha Kwanza cha Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Kwanza Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Kwanza Samweli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SamPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SamPI:NAME:<NAME>END_PIli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("PI:NAME:<NAME>END_PI Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Samweli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Samueli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Samweli 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Samueli I 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA KWANZA CHA SAMPI:NAME:<NAME>END_PILI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("KWANZA SAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("KWANZA SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAMPI:NAME:<NAME>END_PILI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAMPI:NAME:<NAME>END_PILI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("KWANZA SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAMUELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAMWELI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("SAMUELI I 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Kgs (sw)", -> ` expect(p.parse("Kitabu cha Pili cha Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Pili Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Wafalme II 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Wafalme 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Pili Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Fal 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA PILI CHA WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("PILI WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("WAFALME II 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 WAFALME 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("PILI FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 FAL 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Kgs (sw)", -> ` expect(p.parse("Kitabu cha Kwanza cha Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Kwanza Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Kwanza Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Wafalme 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Wafalme I 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Fal 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA KWANZA CHA WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("KWANZA WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("KWANZA FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I WAFALME 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("WAFALME I 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I FAL 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Chr (sw)", -> ` expect(p.parse("Pili Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Mambo ya Nyakati II 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Mambo ya Nyakati 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Pili Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Nya 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1") p.include_apocrypha(false) expect(p.parse("PILI MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("MAMBO YA NYAKATI II 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 MAMBO YA NYAKATI 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("PILI NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 NYA 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Chr (sw)", -> ` expect(p.parse("Kwanza Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Mambo ya Nyakati 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Mambo ya Nyakati I 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Kwanza Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Nya 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1") p.include_apocrypha(false) expect(p.parse("KWANZA MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I MAMBO YA NYAKATI 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("MAMBO YA NYAKATI I 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("KWANZA NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I NYA 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezra (sw)", -> ` expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezr 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZR 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Neh (sw)", -> ` expect(p.parse("Nehemia 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEHEMIA 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: GkEsth (sw)", -> ` expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Esth (sw)", -> ` expect(p.parse("Esther 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Ester 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esta 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTHER 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTER 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTA 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Job (sw)", -> ` expect(p.parse("Kitabu cha Ayubu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Kitabu cha Yobu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Ayubu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Yobu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Ayu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Yob 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("KITABU CHA AYUBU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("KITABU CHA YOBU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("AYUBU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("YOBU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("AYU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") expect(p.parse("YOB 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ps (sw)", -> ` expect(p.parse("Zaburi 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Zab 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("ZABURI 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("ZAB 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrAzar (sw)", -> ` expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Prov (sw)", -> ` expect(p.parse("Methali 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Mithali 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Meth 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Mith 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Mit 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("METHALI 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("MITHALI 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("METH 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("MITH 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("MIT 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eccl (sw)", -> ` expect(p.parse("Mhubiri 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Mhu 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("MHUBIRI 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("MHU 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: SgThree (sw)", -> ` expect(p.parse("Wimbo wa Vijana Watatu 1:1").osis()).toEqual("SgThree.1.1") expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Song (sw)", -> ` expect(p.parse("Wimbo Ulio Bora 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Wimbo Bora 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Wim 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("WIMBO ULIO BORA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("WIMBO BORA 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("WIM 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book Jer (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jer (sw)", -> ` expect(p.parse("Yeremia 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Yer 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("YEREMIA 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("YER 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book Ezek (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezek (sw)", -> ` expect(p.parse("Ezekieli 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Eze 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("EZEKIELI 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZE 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (sw)", -> ` expect(p.parse("Danieli 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("DANIELI 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hos (sw)", -> ` expect(p.parse("Hosea 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("HOSEA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Joel (sw)", -> ` expect(p.parse("Yoeli 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Yoe 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("YOELI 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("YOE 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Amos (sw)", -> ` expect(p.parse("Amosi 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amo 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("AMOSI 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMO 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Obad (sw)", -> ` expect(p.parse("Obadia 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Oba 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Ob 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("OBADIA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OB 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (sw)", -> ` expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Yona 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Yon 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("YONA 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("YON 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PIic (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mic (sw)", -> ` expect(p.parse("Mika 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mik 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MIKA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIK 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Nah (sw)", -> ` expect(p.parse("Nahumu 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nahum 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAHUMU 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAHUM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hab (sw)", -> ` expect(p.parse("Habakuki 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("HABAKUKI 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zeph (sw)", -> ` expect(p.parse("Sefania 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sef 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SEFANIA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SEF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hag (sw)", -> ` expect(p.parse("Hagai 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("HAGAI 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zech (sw)", -> ` expect(p.parse("Zekaria 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zek 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("ZEKARIA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZEK 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mal (sw)", -> ` expect(p.parse("Malaki 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALAKI 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PIatt (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PIatt (sw)", -> ` expect(p.parse("Injili ya Mathayo 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mathayo 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matayo 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Math 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mat 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1") p.include_apocrypha(false) expect(p.parse("INJILI YA MATHAYO 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATHAYO 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATAYO 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATH 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MAT 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1") ` true describe "Localized book Mark (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mark (sw)", -> ` expect(p.parse("Injili ya Marko 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Marko 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mk 1:1").osis()).toEqual("Mark.1.1") p.include_apocrypha(false) expect(p.parse("INJILI YA MARKO 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARKO 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MK 1:1").osis()).toEqual("Mark.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (sw)", -> ` expect(p.parse("Injili ya Luka 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luka 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("INJILI YA LUKA 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKA 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (sw)", -> ` expect(p.parse("Waraka wa Kwanza wa Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Barua ya Kwanza ya Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Kwanza Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Kwanza Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Kwanza Yoh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yohana 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yohane 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Yohane I 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yoh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yoh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yoh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yoh 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA WA YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("BARUA YA KWANZA YA YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("KWANZA YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("KWANZA YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("KWANZA YOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOHANA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOHANE 1:1").osis()).toEqual("1John.1.1") expect(p.parse("YOHANE I 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOH 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PIJohn (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2John (sw)", -> ` expect(p.parse("Waraka wa Pili wa Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Barua ya Pili ya Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Pili Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Pili Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Yohane II 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yohana 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yohane 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Pili Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yoh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI WA YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("BARUA YA PILI YA YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("PILI YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("PILI YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("YOHANE II 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOHANA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOHANE 1:1").osis()).toEqual("2John.1.1") expect(p.parse("PILI YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book 3John (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3John (sw)", -> ` expect(p.parse("Waraka wa Tatu wa Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Barua ya Tatu ya Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Tatu Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Tatu Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Yohane III 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yohana 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yohane 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Tatu Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yoh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA TATU WA YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("BARUA YA TATU YA YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("TATU YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("TATU YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("YOHANE III 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOHANA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOHANE 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("TATU YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book John (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (sw)", -> ` expect(p.parse("Injili ya Yohana 1:1").osis()).toEqual("John.1.1") expect(p.parse("Injili ya Yohane 1:1").osis()).toEqual("John.1.1") expect(p.parse("Yohana 1:1").osis()).toEqual("John.1.1") expect(p.parse("Yohane 1:1").osis()).toEqual("John.1.1") expect(p.parse("John 1:1").osis()).toEqual("John.1.1") expect(p.parse("Yoh 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("INJILI YA YOHANA 1:1").osis()).toEqual("John.1.1") expect(p.parse("INJILI YA YOHANE 1:1").osis()).toEqual("John.1.1") expect(p.parse("YOHANA 1:1").osis()).toEqual("John.1.1") expect(p.parse("YOHANE 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1") expect(p.parse("YOH 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Acts (sw)", -> ` expect(p.parse("Matendo ya Mitume 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Matendo 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Mdo 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("MATENDO YA MITUME 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("MATENDO 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("MDO 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rom (sw)", -> ` expect(p.parse("Waraka kwa Waroma 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Waraka kwa Warumi 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Barua kwa Waroma 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Waroma 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Warumi 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rum 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAROMA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("WARAKA KWA WARUMI 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BARUA KWA WAROMA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("WAROMA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("WARUMI 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RUM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Cor (sw)", -> ` expect(p.parse("Waraka wa Pili kwa Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Barua ya Pili kwa Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Waraka wa Pili kwa Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Pili Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Pili Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Wakorintho II 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Wakorintho 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Wakorinto 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Pili Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI KWA WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("BARUA YA PILI KWA WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("WARAKA WA PILI KWA WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("PILI WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("PILI WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("WAKORINTHO II 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 WAKORINTHO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 WAKORINTO 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("PILI KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Cor (sw)", -> ` expect(p.parse("Waraka wa Kwanza kwa Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Barua ya Kwanza kwa Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Waraka wa Kwanza kwa Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Kwanza Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Kwanza Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Wakorintho 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Wakorintho I 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Wakorinto 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Kwanza Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA KWA WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("BARUA YA KWANZA KWA WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("WARAKA WA KWANZA KWA WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("KWANZA WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("KWANZA WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I WAKORINTHO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("WAKORINTHO I 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I WAKORINTO 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("KWANZA KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gal (sw)", -> ` expect(p.parse("Barua kwa Wagalatia 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Wagalatia 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("BARUA KWA WAGALATIA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("WAGALATIA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eph (sw)", -> ` expect(p.parse("Waraka kwa Waefeso 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Barua kwa Waefeso 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Waefeso 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efe 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAEFESO 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("BARUA KWA WAEFESO 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("WAEFESO 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFE 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1") ` true describe "Localized book Phil (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (sw)", -> ` expect(p.parse("Waraka kwa Wafilipi 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Barua kwa Wafilipi 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Wafilipi 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Flp 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAFILIPI 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BARUA KWA WAFILIPI 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("WAFILIPI 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FLP 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Col (sw)", -> ` expect(p.parse("Waraka kwa Wakolosai 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Barua kwa Wakolosai 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Wakolosai 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAKOLOSAI 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BARUA KWA WAKOLOSAI 1:1").osis()).toEqual("Col.1.1") expect(p.parse("WAKOLOSAI 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Thess (sw)", -> ` expect(p.parse("Waraka wa Pili kwa Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Waraka wa Pili kwa Wathesaloniki 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Barua ya Pili kwa Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Pili Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Wathesalonike II 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Wathesalonike 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Pili Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Pili The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Pili Th 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Thes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Th 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 The 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Th 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Th 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Th 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI KWA WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("WARAKA WA PILI KWA WATHESALONIKI 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("BARUA YA PILI KWA WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("PILI WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("WATHESALONIKE II 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 WATHESALONIKE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("PILI THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("PILI THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("PILI TH 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 THES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. TH 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 THE 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. TH 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II TH 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TH 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Thess (sw)", -> ` expect(p.parse("Waraka wa Kwanza kwa Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Waraka wa Kwanza kwa Wathesaloniki 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Barua ya Kwanza kwa Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Kwanza Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Wathesalonike 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Wathesalonike I 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Kwanza Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Kwanza The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Kwanza Th 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Thes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Th 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I The 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Th 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Th 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Th 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA KWA WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("WARAKA WA KWANZA KWA WATHESALONIKI 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("BARUA YA KWANZA KWA WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("KWANZA WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I WATHESALONIKE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("WATHESALONIKE I 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("KWANZA THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("KWANZA THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("KWANZA TH 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I THES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. TH 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I THE 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. TH 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TH 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I TH 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Tim (sw)", -> ` expect(p.parse("Waraka wa Pili kwa Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Barua ya Pili kwa Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Pili Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Timotheo II 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Timotheo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Pili Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI KWA TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("BARUA YA PILI KWA TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("PILI TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("TIMOTHEO II 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIMOTHEO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("PILI TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Tim (sw)", -> ` expect(p.parse("Waraka wa Kwanza kwa Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Barua ya Kwanza kwa Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Kwanza Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Timotheo 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Kwanza Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Timotheo I 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA KWA TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("BARUA YA KWANZA KWA TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("KWANZA TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIMOTHEO 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("KWANZA TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("TIMOTHEO I 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Titus (sw)", -> ` expect(p.parse("Waraka kwa Tito 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Barua kwa Tito 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tito 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA TITO 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BARUA KWA TITO 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITO 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phlm (sw)", -> ` expect(p.parse("Waraka kwa Filemoni 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Barua kwa Filemoni 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Filemoni 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Film 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Flm 1:1").osis()).toEqual("Phlm.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA FILEMONI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BARUA KWA FILEMONI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILEMONI 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FLM 1:1").osis()).toEqual("Phlm.1.1") ` true describe "Localized book Heb (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Heb (sw)", -> ` expect(p.parse("Waraka kwa Waebrania 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Barua kwa Waebrania 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Waebrania 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Ebr 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Eb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA KWA WAEBRANIA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("BARUA KWA WAEBRANIA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("WAEBRANIA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("EBR 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("EB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jas (sw)", -> ` expect(p.parse("Waraka wa Yakobo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Barua ya Yakobo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Yakobo 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Yak 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA YAKOBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("BARUA YA YAKOBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("YAKOBO 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("YAK 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Pet (sw)", -> ` expect(p.parse("Waraka wa Pili wa Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Barua ya Pili ya Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Pili Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Petro II 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Pili Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Petro 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA PILI WA PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("BARUA YA PILI YA PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("PILI PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("PETRO II 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("PILI PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PETRO 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Pet (sw)", -> ` expect(p.parse("Waraka wa Kwanza wa Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Barua ya Kwanza ya Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Kwanza Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Kwanza Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Petro 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Petro I 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("WARAKA WA KWANZA WA PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("BARUA YA KWANZA YA PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("KWANZA PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("KWANZA PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I PETRO 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("PETRO I 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book Jude (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jude (sw)", -> ` expect(p.parse("Barua ya Yuda 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Yuda 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Yud 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("BARUA YA YUDA 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("YUDA 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("YUD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Tob (sw)", -> ` expect(p.parse("Tobiti 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jdt (sw)", -> ` expect(p.parse("Yudithi 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Yudith 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Yuditi 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Yudit 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Yudt 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bar (sw)", -> ` expect(p.parse("Baruku 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Baruk 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sus (sw)", -> ` expect(p.parse("Susana 1:1").osis()).toEqual("Sus.1.1") expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Macc (sw)", -> ` expect(p.parse("Kitabu cha Wamakabayo II 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Pili Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II. Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2. Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Wamakabayo II 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2 Wamakabayo 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Pili Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II. Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2. Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2 Mak 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3Macc (sw)", -> ` expect(p.parse("Kitabu cha Wamakabayo III 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III. Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("Tatu Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("Wamakabayo III 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3. Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3 Wamakabayo 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III. Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("Tatu Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3. Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3 Mak 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 4Macc (sw)", -> ` expect(p.parse("Kitabu cha Wamakabayo IV 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV. Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Nne Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4. Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Wamakabayo IV 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4 Wamakabayo 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV. Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Nne Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4. Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4 Mak 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Macc (sw)", -> ` expect(p.parse("Kitabu cha Wamakabayo I 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("Kwanza Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1. Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I. Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1 Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I Wamakabayo 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("Wamakabayo I 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("Kwanza Mak 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1. Mak 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I. Mak 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1 Mak 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I Mak 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI,JonPI:NAME:<NAME>END_PI (sw)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI (sw)", -> ` expect(p.parse("Yn 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("YN 1:1").osis()).toEqual("John.1.1") ` true describe "Miscellaneous tests", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete" p.include_apocrypha true it "should return the expected language", -> expect(p.languages).toEqual ["sw"] it "should handle ranges (sw)", -> expect(p.parse("Titus 1:1 hadi 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1hadi2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 HADI 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (sw)", -> expect(p.parse("Titus 1:1, sura 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 SURA 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (sw)", -> expect(p.parse("Exod 1:1 mistari 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm MISTARI 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (sw)", -> expect(p.parse("Exod 1:1 taz. 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 TAZ. 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" expect(p.parse("Exod 1:1 taz 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 TAZ 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" expect(p.parse("Exod 1:1 na 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 NA 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (sw)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (sw)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (sw)", -> expect(p.parse("Lev 1 (HN)").osis_and_translations()).toEqual [["Lev.1", "HN"]] expect(p.parse("lev 1 hn").osis_and_translations()).toEqual [["Lev.1", "HN"]] expect(p.parse("Lev 1 (SUV)").osis_and_translations()).toEqual [["Lev.1", "SUV"]] expect(p.parse("lev 1 suv").osis_and_translations()).toEqual [["Lev.1", "SUV"]] it "should handle book ranges (sw)", -> p.set_options {book_alone_strategy: "full", book_range_strategy: "include"} expect(p.parse("KPI:NAME:<NAME>END_PI Yoh").osis()).toEqual "1John.1-3John.1" it "should handle boundaries (sw)", -> p.set_options {book_alone_strategy: "full"} expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28" expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
[ { "context": "ter open and before close array brackets\n# @author Jan Peer Stöcklmair <https://github.com/JPeer264>\n###\n\n'use strict'\n\n", "end": 120, "score": 0.9999021291732788, "start": 101, "tag": "NAME", "value": "Jan Peer Stöcklmair" }, { "context": "# @author Jan Peer Stöc...
src/rules/array-bracket-newline.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Rule to enforce linebreaks after open and before close array brackets # @author Jan Peer Stöcklmair <https://github.com/JPeer264> ### 'use strict' astUtils = require '../eslint-ast-utils' {hasIndentedLastLine} = require '../util/ast-utils' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce linebreaks after opening and before closing array brackets' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/array-bracket-newline' # fixable: 'whitespace' schema: [ oneOf: [ enum: ['always', 'never', 'consistent'] , type: 'object' properties: multiline: type: 'boolean' minItems: type: ['integer', 'null'] minimum: 0 additionalProperties: no ] ] messages: unexpectedOpeningLinebreak: "There should be no linebreak after '['." unexpectedClosingLinebreak: "There should be no linebreak before ']'." missingOpeningLinebreak: "A linebreak is required after '['." missingClosingLinebreak: "A linebreak is required before ']'." create: (context) -> sourceCode = context.getSourceCode() #---------------------------------------------------------------------- # Helpers #---------------------------------------------------------------------- ###* # Normalizes a given option value. # # @param {string|Object|undefined} option - An option value to parse. # @returns {{multiline: boolean, minItems: number}} Normalized option object. ### normalizeOptionValue = (option) -> consistent = no multiline = no minItems = 0 if option if option is 'consistent' consistent = yes minItems = Number.POSITIVE_INFINITY else if option is 'always' or option.minItems is 0 minItems = 0 else if option is 'never' minItems = Number.POSITIVE_INFINITY else multiline = Boolean option.multiline minItems = option.minItems or Number.POSITIVE_INFINITY else consistent = no multiline = yes minItems = Number.POSITIVE_INFINITY {consistent, multiline, minItems} ###* # Normalizes a given option value. # # @param {string|Object|undefined} options - An option value to parse. # @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object. ### normalizeOptions = (options) -> value = normalizeOptionValue options ArrayExpression: value, ArrayPattern: value ###* # Reports that there shouldn't be a linebreak after the first token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportNoBeginningLinebreak = (node, token) -> context.report { node loc: token.loc messageId: 'unexpectedOpeningLinebreak' # fix: (fixer) -> # nextToken = sourceCode.getTokenAfter token, includeComments: yes # return null if astUtils.isCommentToken nextToken # fixer.removeRange [token.range[1], nextToken.range[0]] } ###* # Reports that there shouldn't be a linebreak before the last token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportNoEndingLinebreak = (node, token) -> context.report { node loc: token.loc messageId: 'unexpectedClosingLinebreak' # fix: (fixer) -> # previousToken = sourceCode.getTokenBefore token, includeComments: yes # return null if astUtils.isCommentToken previousToken # fixer.removeRange [previousToken.range[1], token.range[0]] } ###* # Reports that there should be a linebreak after the first token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportRequiredBeginningLinebreak = (node, token) -> context.report { node loc: token.loc messageId: 'missingOpeningLinebreak' # fix: (fixer) -> fixer.insertTextAfter token, '\n' } ###* # Reports that there should be a linebreak before the last token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportRequiredEndingLinebreak = (node, token) -> context.report { node loc: token.loc messageId: 'missingClosingLinebreak' # fix: (fixer) -> fixer.insertTextBefore token, '\n' } # getIndentSize: ({node, openBracket}) -> # openBracketLine = openBracket.loc.start.line # currentMin = null # for element in node.elements when node.loc.start.line > openBracketLine # {column} = element.loc.start # currentMin = column if not currentMin? or column < currentMin ###* # Reports a given node if it violated this rule. # # @param {ASTNode} node - A node to check. This is an ArrayExpression node or an ArrayPattern node. # @returns {void} ### check = (node) -> {elements} = node normalizedOptions = normalizeOptions context.options[0] options = normalizedOptions[node.type] openBracket = sourceCode.getFirstToken node closeBracket = sourceCode.getLastToken node firstIncComment = sourceCode.getTokenAfter openBracket, includeComments: yes lastIncComment = sourceCode.getTokenBefore closeBracket, includeComments: yes first = sourceCode.getTokenAfter openBracket last = sourceCode.getTokenBefore closeBracket # indentSize = getIndentSize {node, openBracket} lastElementHasIndentedBody = do -> return no unless elements.length lastElement = elements[elements.length - 1] return no unless lastElement return no unless lastElement.loc.start.line < lastElement.loc.end.line return yes if lastElement.loc.start.line is openBracket.loc.start.line hasIndentedLastLine {node: lastElement, sourceCode} needsLinebreaks = elements.length >= options.minItems or (options.multiline and elements.length > 0 and firstIncComment.loc.start.line isnt lastIncComment.loc.end.line) or (elements.length is 0 and firstIncComment.type is 'Block' and firstIncComment.loc.start.line isnt lastIncComment.loc.end.line and firstIncComment is lastIncComment) or (options.consistent and firstIncComment.loc.start.line isnt openBracket.loc.end.line) ### # Use tokens or comments to check multiline or not. # But use only tokens to check whether linebreaks are needed. # This allows: # var arr = [ // eslint-disable-line foo # 'a' # ] ### if needsLinebreaks if astUtils.isTokenOnSameLine openBracket, first reportRequiredBeginningLinebreak node, openBracket if astUtils.isTokenOnSameLine last, closeBracket reportRequiredEndingLinebreak node, closeBracket else unless astUtils.isTokenOnSameLine openBracket, first reportNoBeginningLinebreak node, openBracket if ( not lastElementHasIndentedBody and not astUtils.isTokenOnSameLine last, closeBracket ) reportNoEndingLinebreak node, closeBracket #---------------------------------------------------------------------- # Public #---------------------------------------------------------------------- ArrayPattern: check ArrayExpression: check
179736
###* # @fileoverview Rule to enforce linebreaks after open and before close array brackets # @author <NAME> <https://github.com/JPeer264> ### 'use strict' astUtils = require '../eslint-ast-utils' {hasIndentedLastLine} = require '../util/ast-utils' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce linebreaks after opening and before closing array brackets' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/array-bracket-newline' # fixable: 'whitespace' schema: [ oneOf: [ enum: ['always', 'never', 'consistent'] , type: 'object' properties: multiline: type: 'boolean' minItems: type: ['integer', 'null'] minimum: 0 additionalProperties: no ] ] messages: unexpectedOpeningLinebreak: "There should be no linebreak after '['." unexpectedClosingLinebreak: "There should be no linebreak before ']'." missingOpeningLinebreak: "A linebreak is required after '['." missingClosingLinebreak: "A linebreak is required before ']'." create: (context) -> sourceCode = context.getSourceCode() #---------------------------------------------------------------------- # Helpers #---------------------------------------------------------------------- ###* # Normalizes a given option value. # # @param {string|Object|undefined} option - An option value to parse. # @returns {{multiline: boolean, minItems: number}} Normalized option object. ### normalizeOptionValue = (option) -> consistent = no multiline = no minItems = 0 if option if option is 'consistent' consistent = yes minItems = Number.POSITIVE_INFINITY else if option is 'always' or option.minItems is 0 minItems = 0 else if option is 'never' minItems = Number.POSITIVE_INFINITY else multiline = Boolean option.multiline minItems = option.minItems or Number.POSITIVE_INFINITY else consistent = no multiline = yes minItems = Number.POSITIVE_INFINITY {consistent, multiline, minItems} ###* # Normalizes a given option value. # # @param {string|Object|undefined} options - An option value to parse. # @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object. ### normalizeOptions = (options) -> value = normalizeOptionValue options ArrayExpression: value, ArrayPattern: value ###* # Reports that there shouldn't be a linebreak after the first token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportNoBeginningLinebreak = (node, token) -> context.report { node loc: token.loc messageId: 'unexpectedOpeningLinebreak' # fix: (fixer) -> # nextToken = sourceCode.getTokenAfter token, includeComments: yes # return null if astUtils.isCommentToken nextToken # fixer.removeRange [token.range[1], nextToken.range[0]] } ###* # Reports that there shouldn't be a linebreak before the last token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportNoEndingLinebreak = (node, token) -> context.report { node loc: token.loc messageId: 'unexpectedClosingLinebreak' # fix: (fixer) -> # previousToken = sourceCode.getTokenBefore token, includeComments: yes # return null if astUtils.isCommentToken previousToken # fixer.removeRange [previousToken.range[1], token.range[0]] } ###* # Reports that there should be a linebreak after the first token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportRequiredBeginningLinebreak = (node, token) -> context.report { node loc: token.loc messageId: 'missingOpeningLinebreak' # fix: (fixer) -> fixer.insertTextAfter token, '\n' } ###* # Reports that there should be a linebreak before the last token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportRequiredEndingLinebreak = (node, token) -> context.report { node loc: token.loc messageId: 'missingClosingLinebreak' # fix: (fixer) -> fixer.insertTextBefore token, '\n' } # getIndentSize: ({node, openBracket}) -> # openBracketLine = openBracket.loc.start.line # currentMin = null # for element in node.elements when node.loc.start.line > openBracketLine # {column} = element.loc.start # currentMin = column if not currentMin? or column < currentMin ###* # Reports a given node if it violated this rule. # # @param {ASTNode} node - A node to check. This is an ArrayExpression node or an ArrayPattern node. # @returns {void} ### check = (node) -> {elements} = node normalizedOptions = normalizeOptions context.options[0] options = normalizedOptions[node.type] openBracket = sourceCode.getFirstToken node closeBracket = sourceCode.getLastToken node firstIncComment = sourceCode.getTokenAfter openBracket, includeComments: yes lastIncComment = sourceCode.getTokenBefore closeBracket, includeComments: yes first = sourceCode.getTokenAfter openBracket last = sourceCode.getTokenBefore closeBracket # indentSize = getIndentSize {node, openBracket} lastElementHasIndentedBody = do -> return no unless elements.length lastElement = elements[elements.length - 1] return no unless lastElement return no unless lastElement.loc.start.line < lastElement.loc.end.line return yes if lastElement.loc.start.line is openBracket.loc.start.line hasIndentedLastLine {node: lastElement, sourceCode} needsLinebreaks = elements.length >= options.minItems or (options.multiline and elements.length > 0 and firstIncComment.loc.start.line isnt lastIncComment.loc.end.line) or (elements.length is 0 and firstIncComment.type is 'Block' and firstIncComment.loc.start.line isnt lastIncComment.loc.end.line and firstIncComment is lastIncComment) or (options.consistent and firstIncComment.loc.start.line isnt openBracket.loc.end.line) ### # Use tokens or comments to check multiline or not. # But use only tokens to check whether linebreaks are needed. # This allows: # var arr = [ // eslint-disable-line foo # 'a' # ] ### if needsLinebreaks if astUtils.isTokenOnSameLine openBracket, first reportRequiredBeginningLinebreak node, openBracket if astUtils.isTokenOnSameLine last, closeBracket reportRequiredEndingLinebreak node, closeBracket else unless astUtils.isTokenOnSameLine openBracket, first reportNoBeginningLinebreak node, openBracket if ( not lastElementHasIndentedBody and not astUtils.isTokenOnSameLine last, closeBracket ) reportNoEndingLinebreak node, closeBracket #---------------------------------------------------------------------- # Public #---------------------------------------------------------------------- ArrayPattern: check ArrayExpression: check
true
###* # @fileoverview Rule to enforce linebreaks after open and before close array brackets # @author PI:NAME:<NAME>END_PI <https://github.com/JPeer264> ### 'use strict' astUtils = require '../eslint-ast-utils' {hasIndentedLastLine} = require '../util/ast-utils' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce linebreaks after opening and before closing array brackets' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/array-bracket-newline' # fixable: 'whitespace' schema: [ oneOf: [ enum: ['always', 'never', 'consistent'] , type: 'object' properties: multiline: type: 'boolean' minItems: type: ['integer', 'null'] minimum: 0 additionalProperties: no ] ] messages: unexpectedOpeningLinebreak: "There should be no linebreak after '['." unexpectedClosingLinebreak: "There should be no linebreak before ']'." missingOpeningLinebreak: "A linebreak is required after '['." missingClosingLinebreak: "A linebreak is required before ']'." create: (context) -> sourceCode = context.getSourceCode() #---------------------------------------------------------------------- # Helpers #---------------------------------------------------------------------- ###* # Normalizes a given option value. # # @param {string|Object|undefined} option - An option value to parse. # @returns {{multiline: boolean, minItems: number}} Normalized option object. ### normalizeOptionValue = (option) -> consistent = no multiline = no minItems = 0 if option if option is 'consistent' consistent = yes minItems = Number.POSITIVE_INFINITY else if option is 'always' or option.minItems is 0 minItems = 0 else if option is 'never' minItems = Number.POSITIVE_INFINITY else multiline = Boolean option.multiline minItems = option.minItems or Number.POSITIVE_INFINITY else consistent = no multiline = yes minItems = Number.POSITIVE_INFINITY {consistent, multiline, minItems} ###* # Normalizes a given option value. # # @param {string|Object|undefined} options - An option value to parse. # @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object. ### normalizeOptions = (options) -> value = normalizeOptionValue options ArrayExpression: value, ArrayPattern: value ###* # Reports that there shouldn't be a linebreak after the first token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportNoBeginningLinebreak = (node, token) -> context.report { node loc: token.loc messageId: 'unexpectedOpeningLinebreak' # fix: (fixer) -> # nextToken = sourceCode.getTokenAfter token, includeComments: yes # return null if astUtils.isCommentToken nextToken # fixer.removeRange [token.range[1], nextToken.range[0]] } ###* # Reports that there shouldn't be a linebreak before the last token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportNoEndingLinebreak = (node, token) -> context.report { node loc: token.loc messageId: 'unexpectedClosingLinebreak' # fix: (fixer) -> # previousToken = sourceCode.getTokenBefore token, includeComments: yes # return null if astUtils.isCommentToken previousToken # fixer.removeRange [previousToken.range[1], token.range[0]] } ###* # Reports that there should be a linebreak after the first token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportRequiredBeginningLinebreak = (node, token) -> context.report { node loc: token.loc messageId: 'missingOpeningLinebreak' # fix: (fixer) -> fixer.insertTextAfter token, '\n' } ###* # Reports that there should be a linebreak before the last token # @param {ASTNode} node - The node to report in the event of an error. # @param {Token} token - The token to use for the report. # @returns {void} ### reportRequiredEndingLinebreak = (node, token) -> context.report { node loc: token.loc messageId: 'missingClosingLinebreak' # fix: (fixer) -> fixer.insertTextBefore token, '\n' } # getIndentSize: ({node, openBracket}) -> # openBracketLine = openBracket.loc.start.line # currentMin = null # for element in node.elements when node.loc.start.line > openBracketLine # {column} = element.loc.start # currentMin = column if not currentMin? or column < currentMin ###* # Reports a given node if it violated this rule. # # @param {ASTNode} node - A node to check. This is an ArrayExpression node or an ArrayPattern node. # @returns {void} ### check = (node) -> {elements} = node normalizedOptions = normalizeOptions context.options[0] options = normalizedOptions[node.type] openBracket = sourceCode.getFirstToken node closeBracket = sourceCode.getLastToken node firstIncComment = sourceCode.getTokenAfter openBracket, includeComments: yes lastIncComment = sourceCode.getTokenBefore closeBracket, includeComments: yes first = sourceCode.getTokenAfter openBracket last = sourceCode.getTokenBefore closeBracket # indentSize = getIndentSize {node, openBracket} lastElementHasIndentedBody = do -> return no unless elements.length lastElement = elements[elements.length - 1] return no unless lastElement return no unless lastElement.loc.start.line < lastElement.loc.end.line return yes if lastElement.loc.start.line is openBracket.loc.start.line hasIndentedLastLine {node: lastElement, sourceCode} needsLinebreaks = elements.length >= options.minItems or (options.multiline and elements.length > 0 and firstIncComment.loc.start.line isnt lastIncComment.loc.end.line) or (elements.length is 0 and firstIncComment.type is 'Block' and firstIncComment.loc.start.line isnt lastIncComment.loc.end.line and firstIncComment is lastIncComment) or (options.consistent and firstIncComment.loc.start.line isnt openBracket.loc.end.line) ### # Use tokens or comments to check multiline or not. # But use only tokens to check whether linebreaks are needed. # This allows: # var arr = [ // eslint-disable-line foo # 'a' # ] ### if needsLinebreaks if astUtils.isTokenOnSameLine openBracket, first reportRequiredBeginningLinebreak node, openBracket if astUtils.isTokenOnSameLine last, closeBracket reportRequiredEndingLinebreak node, closeBracket else unless astUtils.isTokenOnSameLine openBracket, first reportNoBeginningLinebreak node, openBracket if ( not lastElementHasIndentedBody and not astUtils.isTokenOnSameLine last, closeBracket ) reportNoEndingLinebreak node, closeBracket #---------------------------------------------------------------------- # Public #---------------------------------------------------------------------- ArrayPattern: check ArrayExpression: check
[ { "context": "ostly true game of thrones spoilers\n\n# Author:\n# matt.strenz@readytalk.com\n\nmodule.exports = (robot) ->\n\n spoil = ['GOT: Jo", "end": 223, "score": 0.9999265074729919, "start": 198, "tag": "EMAIL", "value": "matt.strenz@readytalk.com" }, { "context": "com\n\nmo...
scripts/spoilers.coffee
mstrenz/theMountain
0
# Description # random mostly true game of thrones spoilers trigger on the word #spoilit # # Commands: # mountain #spoilit - Generates random mostly true game of thrones spoilers # Author: # matt.strenz@readytalk.com module.exports = (robot) -> spoil = ['GOT: Jon Snow is killed by the night watch', 'GOT: Jon Snow is brought back to life by Melisandre', 'GOT: Jon Snow is a Targaryen', 'GOT: Ayra kills Walder Frey', 'GOT: Hold the Door = HODOR', 'GOT: Daenerys defeats the masters at Meereen', 'GOT: Daenerys kills all the dothraki leaders with fire', 'GOT: Tyrion kills Tywin', 'GOT: Ramsay wins the battle of the bastards', 'GOT: Ayra kills the many faced god', 'GOT: Ned Stark comes back to life', 'WESTWORLD: William IS the man in black', 'WESTWORLD: Bernard is a host in the likeness of Arnold', 'WESTWORLD: Dolores is self aware', 'WESTWORLD: Dolores kills Arnold', 'WESTWORLD: Wyatt is not a person but a storyline', 'Everybody is a host, there are no humans', 'WESTWORLD: Maeve blows up westworld', 'WESTWORLD: Dolores hooks up with Robert'] robot.respond /#spoilit/i, (res) -> res.send res.random spoil
102199
# Description # random mostly true game of thrones spoilers trigger on the word #spoilit # # Commands: # mountain #spoilit - Generates random mostly true game of thrones spoilers # Author: # <EMAIL> module.exports = (robot) -> spoil = ['GOT: <NAME> is killed by the night watch', 'GOT: <NAME> is brought back to life by Melisandre', 'GOT: <NAME> is a Targaryen', 'GOT: Ayra kills Walder Frey', 'GOT: Hold the Door = HODOR', 'GOT: Daenerys defeats the masters at Meereen', 'GOT: Daenerys kills all the dothraki leaders with fire', 'GOT: Tyrion kills Tywin', 'GOT: <NAME>ay wins the battle of the bastards', 'GOT: Ayra kills the many faced god', 'GOT: <NAME> comes back to life', 'WESTWORLD: <NAME> IS the man in black', 'WESTWORLD: Bernard is a host in the likeness of <NAME>old', 'WESTWORLD: Dolores is self aware', 'WESTWORLD: Dolores kills Arnold', 'WESTWORLD: Wyatt is not a person but a storyline', 'Everybody is a host, there are no humans', 'WESTWORLD: Maeve blows up westworld', 'WESTWORLD: Dolores hooks up with <NAME>'] robot.respond /#spoilit/i, (res) -> res.send res.random spoil
true
# Description # random mostly true game of thrones spoilers trigger on the word #spoilit # # Commands: # mountain #spoilit - Generates random mostly true game of thrones spoilers # Author: # PI:EMAIL:<EMAIL>END_PI module.exports = (robot) -> spoil = ['GOT: PI:NAME:<NAME>END_PI is killed by the night watch', 'GOT: PI:NAME:<NAME>END_PI is brought back to life by Melisandre', 'GOT: PI:NAME:<NAME>END_PI is a Targaryen', 'GOT: Ayra kills Walder Frey', 'GOT: Hold the Door = HODOR', 'GOT: Daenerys defeats the masters at Meereen', 'GOT: Daenerys kills all the dothraki leaders with fire', 'GOT: Tyrion kills Tywin', 'GOT: PI:NAME:<NAME>END_PIay wins the battle of the bastards', 'GOT: Ayra kills the many faced god', 'GOT: PI:NAME:<NAME>END_PI comes back to life', 'WESTWORLD: PI:NAME:<NAME>END_PI IS the man in black', 'WESTWORLD: Bernard is a host in the likeness of PI:NAME:<NAME>END_PIold', 'WESTWORLD: Dolores is self aware', 'WESTWORLD: Dolores kills Arnold', 'WESTWORLD: Wyatt is not a person but a storyline', 'Everybody is a host, there are no humans', 'WESTWORLD: Maeve blows up westworld', 'WESTWORLD: Dolores hooks up with PI:NAME:<NAME>END_PI'] robot.respond /#spoilit/i, (res) -> res.send res.random spoil
[ { "context": ", match:[0,255], card=\"1\" }\n # \"string:James\" { type:\"string\", oper:\"eq\", match:Ja", "end": 3225, "score": 0.9950094223022461, "start": 3220, "tag": "NAME", "value": "James" } ]
lib/src/test/Spec.coffee
axiom6/aug
0
import Type from "./Type.js" class Spec extends Type constructor:() -> super() # -- is... Spec assertions isSpec:( arg ) -> type = @toType(arg) switch type when "string" @isSpecParse( arg ) when "object" if @isSpecObject( arg ) true else pass = true pass = pass and @isSpec(val) for own key, val of arg pass when "array" pass = true pass = pass and @isSpec(val) for val in arg pass else false isSpecParse:( arg ) -> type = @toType( arg ) @isDef(arg) and type isnt("object") and ( type is "regexp" or ( type is "string" and arg.includes(":") ) ) isSpecObject: ( arg ) -> @isObject(arg) and @isIn(arg.type,"results") and arg.match? and @isMatch(arg.match) and arg.card? and @isCard(arg.card) isMatch:( match ) -> switch when @isRegexp(match) then true when @isEnums(match) then true when @isRange(match) then true else false # let re = /ab+c/i; // literal notation # let re = new RegExp('ab+c', 'i') // constructor with string pattern as first argument # let re = new RegExp(/ab+c/, 'i') // constructor with regular express isRegexp:( arg ) -> @isType(arg,"regexp") # Asserts range with for types "string" or "int" or "float" # internal functions verify an array of type "string" or "int" or "float" # is an array of type "string" or "int" or "float" # rangeStr = "| a-z, 0-9, A-Z |" # rangeRgb = "| 0-255 |" # rangeHsv = "| 0-360, 0-100, 0-100 |" # rangeFlt = "| 0-360+0.001, 0-100+0.001, 0-100+0.001 |" isRange:(range) -> return @isRanges(@toRanges(range)) if range.includes(",") a = @toRangeArray(range) isStrRange = (a) -> a.length is 2 and a[0] <= a[1] # Foa 'staing' isIntRange = (a) -> a.length is 2 and a[0] <= a[1] # Foa 'int' isFloatRange = (a) -> a.length is 3 and a[0]-a[2] <= a[1]+a[2] # Foa 'float' a[2] is tol switch @toType(a[0]) when 'string' then isStrRange(a) when 'int' then isIntRange(a) when 'float' then isFloatRange(a) else false isRanges:(ranges) -> pass = true pass = pass and @isRange(range) for range in ranges pass # Moved to Type.coffee isEnums:( arg ) -> super.isEnums(arg) isResult:( result ) -> type = @toType(result) @isDef(result) and @isIn( type, "results" ) isExpect:( expect ) -> type = @toType(expect) @isDef(expect) and @isIn( type, "expects" ) # -- to... Spec conversions toSpec:( arg ) -> switch when @isSpecParse( arg ) @toSpecParse( arg ) when @isSpecObject( arg ) @toSpecObject( arg ) when @isArray( arg ) array = [] array.push(@toSpec(val)) for val in arg array when @isObject( arg ) obj = {} obj[key] = @toSpec(val) for own key, val of arg obj else @toSpecInit() # @toSpecInit() creates a do nothing spec # toSpecParse:( spec, arg ) # Examples # "array:[0,255]" } { type:"array", oper:"range", match:[0,255], card="1" } # "string:James" { type:"string", oper:"eq", match:James, card="1" } # "string:a|b|c" { type:"string", oper:"enums", match:"a|b|c", card="1" } # "int:[0,100]" { type:"int", oper:"range", match:[0,100], card="1" } # "float:[0.0,100.0,1.0] { type:"float", oper:"range", match:[0.0,100.0,1.0], card="1" } # "string:["","zzz"] { type:"string", oper:"range", match:["","zzz"], card="1" } # "boolean" { type:"boolean", oper:"any", match:"any", card="1" } # "object:{r:[0,255],g:[0,255],b:[0,255]} # { type:"object", oper:"range", match:{r:[0,255],g:[0,255],b:[0,255]}, card="1" } # "array:[[0,360],[0,100],[0,100]]:?" # { type:"array", oper:"range", match:[[0,360],[0,100],[0,100]], card="?" } toSpecParse:( arg ) -> spec = @toSpecInit() return spec if not @isSpecParse(arg) splits = arg.split(":") length = splits.length if length >= 1 then spec.type = splits[0] # type if length >= 1 # match type = @toType(splits[1]) spec.match = switch type when "regexp" then "regexp" # regex when "string" switch when splits[1].includes("|") then @toEnums( splits[1] ) # enums when @isEnclosed( "[", splits[1], "]" ) then @toArray( splits[1] ) # range when @isEnclosed( "{", splits[1], "}" ) then @toObject( splits[1] ) # object? else "any" else "any" if length >= 2 then spec.card = splits[2] # card i.e cardinaliry spec toSpecObject:( arg ) -> spec = @toSpecInit() return spec if not @isSpecObject(arg) spec.type = if arg.type? then arg.type else "any" spec.match = if arg.match? then arg.match else "any" spec.card = if arg.card? then arg.card else "1" # required spec toSpecInit:() -> { type:"any", match:"any", card:"1" } toRange:( arg ) -> if @isType(arg,"range") then arg else "any" toRanges:(range) -> range = @strip( range, "|", "|") range = range.replaceAll( " ", "" ) # remove white space range.split(",") # |a-z| |0-100| |0-100+0.001| toRangeArray:( range ) -> a = [] range = @strip( range, "|", "|") range = range.replaceAll( " ", "" ) # remove white space splits = range.split("-") # Append the optional 3rd parameter tolerance for 'float' ranges if splits.length is 2 and splits[1].includes("+") splits2 = splits[1].split("+") splits[1] = splits2[0] splits.push(splits2[1]) switch @toType(splits[0]) when "string" and splits.length is 2 # 'string' a.push(splits[0]) a.push(splits[1]) when "int" and splits.length is 2 # 'int' a.push(@toInt(splits[0])) a.push(@toInt(splits[1])) when "float" and splits.length is 3 # 'float' a.push(@toFloat(splits[0])) a.push(@toFloat(splits[1])) a.push(@toFloat(splits[2])) else a # Moved to Type.coffee toEnums:( arg ) -> super.toEnums(arg) # Arg types must be 'regexp' or 'string', otherwise returns 'any' toRegexp:( arg ) -> switch @toType(arg) when "regexp" then arg when "string" then new RegExp(arg) else "any" # -- in... Spec matches inSpec:( result, spec ) -> return false if @isNot(spec) or not ( @isSpec(spec) and @toType(result) is spec.type and @inCard(result,spec) ) match = spec.match switch when @isArray(result) and @isArray(spec) then @inSpecArray( result, spec ) when @isObject(result) and @isObject(spec) then @inSpecObject( result, spec ) when @isRange( match ) then @isRange( result, match ) when @isEnums( match ) then @isEnums( result, match ) when @isRegexp( match ) then @isRegexp( result, match ) else false # Here only minimum length of spec and result are checked inSpecArray:( result, spec ) -> pass = true min = Math.min( result.length, spec.length ) pass = pass and @inSpec(result[i],spec[i]) for i in [0...min] pass # Here only the keys common to both spec and result are checked inSpecObject:( result, spec ) -> pass = true for own key, val of spec when result[key]? pass = pass and @inSpec(result[key],spec[key]) pass # Determine if a result is bounded witnin a range. # This method is here in Tester because it call @examine() inRange:( result, range ) -> return @inRanges(result,@toRanges(range)) if range.includes(",") return false if not @isType(range) # @isRange(range) a = @toRangeArray(range) # Convers the range to an array inStrRange = ( string, a ) -> a[0] <= string and string <= a[1] inIntRange = ( int, a ) -> a[0] <= int and int <= a[1] inFloatRange = ( float, a ) -> a[0]-a[2] <= float and float <= a[1]+a[2] switch @toType(result) when "string" then inStrRange( result, a ) when "int" then inIntRange( result, a ) when "float" then inFloatRange( result, a ) else false # Ony apply the ranges we have are applied # if ranges is just a single range applied then it is applied to each result inRanges:( results, ranges ) -> pass = true switch when @isArray(results) and @isArray(ranges) min = Math.min( results.length, ranges.length ) # Ony apply the ranges we ga pass = pass and @inRange(results[i],ranges[i]) for i in [0...min] when @isArray(results) pass = pass and @inRange(results,ranges) for result in results else pass = false pass # Determine if a result is enumerated. # inEnums:( result, enums ) -> # super.toEnums( result, enums ) inRegexp:( result, regexp ) -> return false if not @isRegexp(regexp) regexp = @toRegexp( regexp ) regexp.test(result) isCard:( card ) -> @isStr(card) and ( @isType(card,"int") or card.includes(":") or @isIn(card,"cards") ) # ... more to come for checking cardinallity inCard:( result, spec ) -> card = spec.card switch when @isType(card,"int") then true when @isStr(card) and card.includes("-") minMax = @toMinMax(card) num = minMax[0] # Dummy number minMax[0] <= num <= minMax[1] else switch card when "1" then true when "?" then true when "*" then true when "+" then true else false toMinMax:( card ) -> splits = card.split(":") min = @toInt(splits[0]) max = @toInt(splits[1]) [min,max] export spec = new Spec() # Export a singleton instence of type export default Spec
152121
import Type from "./Type.js" class Spec extends Type constructor:() -> super() # -- is... Spec assertions isSpec:( arg ) -> type = @toType(arg) switch type when "string" @isSpecParse( arg ) when "object" if @isSpecObject( arg ) true else pass = true pass = pass and @isSpec(val) for own key, val of arg pass when "array" pass = true pass = pass and @isSpec(val) for val in arg pass else false isSpecParse:( arg ) -> type = @toType( arg ) @isDef(arg) and type isnt("object") and ( type is "regexp" or ( type is "string" and arg.includes(":") ) ) isSpecObject: ( arg ) -> @isObject(arg) and @isIn(arg.type,"results") and arg.match? and @isMatch(arg.match) and arg.card? and @isCard(arg.card) isMatch:( match ) -> switch when @isRegexp(match) then true when @isEnums(match) then true when @isRange(match) then true else false # let re = /ab+c/i; // literal notation # let re = new RegExp('ab+c', 'i') // constructor with string pattern as first argument # let re = new RegExp(/ab+c/, 'i') // constructor with regular express isRegexp:( arg ) -> @isType(arg,"regexp") # Asserts range with for types "string" or "int" or "float" # internal functions verify an array of type "string" or "int" or "float" # is an array of type "string" or "int" or "float" # rangeStr = "| a-z, 0-9, A-Z |" # rangeRgb = "| 0-255 |" # rangeHsv = "| 0-360, 0-100, 0-100 |" # rangeFlt = "| 0-360+0.001, 0-100+0.001, 0-100+0.001 |" isRange:(range) -> return @isRanges(@toRanges(range)) if range.includes(",") a = @toRangeArray(range) isStrRange = (a) -> a.length is 2 and a[0] <= a[1] # Foa 'staing' isIntRange = (a) -> a.length is 2 and a[0] <= a[1] # Foa 'int' isFloatRange = (a) -> a.length is 3 and a[0]-a[2] <= a[1]+a[2] # Foa 'float' a[2] is tol switch @toType(a[0]) when 'string' then isStrRange(a) when 'int' then isIntRange(a) when 'float' then isFloatRange(a) else false isRanges:(ranges) -> pass = true pass = pass and @isRange(range) for range in ranges pass # Moved to Type.coffee isEnums:( arg ) -> super.isEnums(arg) isResult:( result ) -> type = @toType(result) @isDef(result) and @isIn( type, "results" ) isExpect:( expect ) -> type = @toType(expect) @isDef(expect) and @isIn( type, "expects" ) # -- to... Spec conversions toSpec:( arg ) -> switch when @isSpecParse( arg ) @toSpecParse( arg ) when @isSpecObject( arg ) @toSpecObject( arg ) when @isArray( arg ) array = [] array.push(@toSpec(val)) for val in arg array when @isObject( arg ) obj = {} obj[key] = @toSpec(val) for own key, val of arg obj else @toSpecInit() # @toSpecInit() creates a do nothing spec # toSpecParse:( spec, arg ) # Examples # "array:[0,255]" } { type:"array", oper:"range", match:[0,255], card="1" } # "string:<NAME>" { type:"string", oper:"eq", match:James, card="1" } # "string:a|b|c" { type:"string", oper:"enums", match:"a|b|c", card="1" } # "int:[0,100]" { type:"int", oper:"range", match:[0,100], card="1" } # "float:[0.0,100.0,1.0] { type:"float", oper:"range", match:[0.0,100.0,1.0], card="1" } # "string:["","zzz"] { type:"string", oper:"range", match:["","zzz"], card="1" } # "boolean" { type:"boolean", oper:"any", match:"any", card="1" } # "object:{r:[0,255],g:[0,255],b:[0,255]} # { type:"object", oper:"range", match:{r:[0,255],g:[0,255],b:[0,255]}, card="1" } # "array:[[0,360],[0,100],[0,100]]:?" # { type:"array", oper:"range", match:[[0,360],[0,100],[0,100]], card="?" } toSpecParse:( arg ) -> spec = @toSpecInit() return spec if not @isSpecParse(arg) splits = arg.split(":") length = splits.length if length >= 1 then spec.type = splits[0] # type if length >= 1 # match type = @toType(splits[1]) spec.match = switch type when "regexp" then "regexp" # regex when "string" switch when splits[1].includes("|") then @toEnums( splits[1] ) # enums when @isEnclosed( "[", splits[1], "]" ) then @toArray( splits[1] ) # range when @isEnclosed( "{", splits[1], "}" ) then @toObject( splits[1] ) # object? else "any" else "any" if length >= 2 then spec.card = splits[2] # card i.e cardinaliry spec toSpecObject:( arg ) -> spec = @toSpecInit() return spec if not @isSpecObject(arg) spec.type = if arg.type? then arg.type else "any" spec.match = if arg.match? then arg.match else "any" spec.card = if arg.card? then arg.card else "1" # required spec toSpecInit:() -> { type:"any", match:"any", card:"1" } toRange:( arg ) -> if @isType(arg,"range") then arg else "any" toRanges:(range) -> range = @strip( range, "|", "|") range = range.replaceAll( " ", "" ) # remove white space range.split(",") # |a-z| |0-100| |0-100+0.001| toRangeArray:( range ) -> a = [] range = @strip( range, "|", "|") range = range.replaceAll( " ", "" ) # remove white space splits = range.split("-") # Append the optional 3rd parameter tolerance for 'float' ranges if splits.length is 2 and splits[1].includes("+") splits2 = splits[1].split("+") splits[1] = splits2[0] splits.push(splits2[1]) switch @toType(splits[0]) when "string" and splits.length is 2 # 'string' a.push(splits[0]) a.push(splits[1]) when "int" and splits.length is 2 # 'int' a.push(@toInt(splits[0])) a.push(@toInt(splits[1])) when "float" and splits.length is 3 # 'float' a.push(@toFloat(splits[0])) a.push(@toFloat(splits[1])) a.push(@toFloat(splits[2])) else a # Moved to Type.coffee toEnums:( arg ) -> super.toEnums(arg) # Arg types must be 'regexp' or 'string', otherwise returns 'any' toRegexp:( arg ) -> switch @toType(arg) when "regexp" then arg when "string" then new RegExp(arg) else "any" # -- in... Spec matches inSpec:( result, spec ) -> return false if @isNot(spec) or not ( @isSpec(spec) and @toType(result) is spec.type and @inCard(result,spec) ) match = spec.match switch when @isArray(result) and @isArray(spec) then @inSpecArray( result, spec ) when @isObject(result) and @isObject(spec) then @inSpecObject( result, spec ) when @isRange( match ) then @isRange( result, match ) when @isEnums( match ) then @isEnums( result, match ) when @isRegexp( match ) then @isRegexp( result, match ) else false # Here only minimum length of spec and result are checked inSpecArray:( result, spec ) -> pass = true min = Math.min( result.length, spec.length ) pass = pass and @inSpec(result[i],spec[i]) for i in [0...min] pass # Here only the keys common to both spec and result are checked inSpecObject:( result, spec ) -> pass = true for own key, val of spec when result[key]? pass = pass and @inSpec(result[key],spec[key]) pass # Determine if a result is bounded witnin a range. # This method is here in Tester because it call @examine() inRange:( result, range ) -> return @inRanges(result,@toRanges(range)) if range.includes(",") return false if not @isType(range) # @isRange(range) a = @toRangeArray(range) # Convers the range to an array inStrRange = ( string, a ) -> a[0] <= string and string <= a[1] inIntRange = ( int, a ) -> a[0] <= int and int <= a[1] inFloatRange = ( float, a ) -> a[0]-a[2] <= float and float <= a[1]+a[2] switch @toType(result) when "string" then inStrRange( result, a ) when "int" then inIntRange( result, a ) when "float" then inFloatRange( result, a ) else false # Ony apply the ranges we have are applied # if ranges is just a single range applied then it is applied to each result inRanges:( results, ranges ) -> pass = true switch when @isArray(results) and @isArray(ranges) min = Math.min( results.length, ranges.length ) # Ony apply the ranges we ga pass = pass and @inRange(results[i],ranges[i]) for i in [0...min] when @isArray(results) pass = pass and @inRange(results,ranges) for result in results else pass = false pass # Determine if a result is enumerated. # inEnums:( result, enums ) -> # super.toEnums( result, enums ) inRegexp:( result, regexp ) -> return false if not @isRegexp(regexp) regexp = @toRegexp( regexp ) regexp.test(result) isCard:( card ) -> @isStr(card) and ( @isType(card,"int") or card.includes(":") or @isIn(card,"cards") ) # ... more to come for checking cardinallity inCard:( result, spec ) -> card = spec.card switch when @isType(card,"int") then true when @isStr(card) and card.includes("-") minMax = @toMinMax(card) num = minMax[0] # Dummy number minMax[0] <= num <= minMax[1] else switch card when "1" then true when "?" then true when "*" then true when "+" then true else false toMinMax:( card ) -> splits = card.split(":") min = @toInt(splits[0]) max = @toInt(splits[1]) [min,max] export spec = new Spec() # Export a singleton instence of type export default Spec
true
import Type from "./Type.js" class Spec extends Type constructor:() -> super() # -- is... Spec assertions isSpec:( arg ) -> type = @toType(arg) switch type when "string" @isSpecParse( arg ) when "object" if @isSpecObject( arg ) true else pass = true pass = pass and @isSpec(val) for own key, val of arg pass when "array" pass = true pass = pass and @isSpec(val) for val in arg pass else false isSpecParse:( arg ) -> type = @toType( arg ) @isDef(arg) and type isnt("object") and ( type is "regexp" or ( type is "string" and arg.includes(":") ) ) isSpecObject: ( arg ) -> @isObject(arg) and @isIn(arg.type,"results") and arg.match? and @isMatch(arg.match) and arg.card? and @isCard(arg.card) isMatch:( match ) -> switch when @isRegexp(match) then true when @isEnums(match) then true when @isRange(match) then true else false # let re = /ab+c/i; // literal notation # let re = new RegExp('ab+c', 'i') // constructor with string pattern as first argument # let re = new RegExp(/ab+c/, 'i') // constructor with regular express isRegexp:( arg ) -> @isType(arg,"regexp") # Asserts range with for types "string" or "int" or "float" # internal functions verify an array of type "string" or "int" or "float" # is an array of type "string" or "int" or "float" # rangeStr = "| a-z, 0-9, A-Z |" # rangeRgb = "| 0-255 |" # rangeHsv = "| 0-360, 0-100, 0-100 |" # rangeFlt = "| 0-360+0.001, 0-100+0.001, 0-100+0.001 |" isRange:(range) -> return @isRanges(@toRanges(range)) if range.includes(",") a = @toRangeArray(range) isStrRange = (a) -> a.length is 2 and a[0] <= a[1] # Foa 'staing' isIntRange = (a) -> a.length is 2 and a[0] <= a[1] # Foa 'int' isFloatRange = (a) -> a.length is 3 and a[0]-a[2] <= a[1]+a[2] # Foa 'float' a[2] is tol switch @toType(a[0]) when 'string' then isStrRange(a) when 'int' then isIntRange(a) when 'float' then isFloatRange(a) else false isRanges:(ranges) -> pass = true pass = pass and @isRange(range) for range in ranges pass # Moved to Type.coffee isEnums:( arg ) -> super.isEnums(arg) isResult:( result ) -> type = @toType(result) @isDef(result) and @isIn( type, "results" ) isExpect:( expect ) -> type = @toType(expect) @isDef(expect) and @isIn( type, "expects" ) # -- to... Spec conversions toSpec:( arg ) -> switch when @isSpecParse( arg ) @toSpecParse( arg ) when @isSpecObject( arg ) @toSpecObject( arg ) when @isArray( arg ) array = [] array.push(@toSpec(val)) for val in arg array when @isObject( arg ) obj = {} obj[key] = @toSpec(val) for own key, val of arg obj else @toSpecInit() # @toSpecInit() creates a do nothing spec # toSpecParse:( spec, arg ) # Examples # "array:[0,255]" } { type:"array", oper:"range", match:[0,255], card="1" } # "string:PI:NAME:<NAME>END_PI" { type:"string", oper:"eq", match:James, card="1" } # "string:a|b|c" { type:"string", oper:"enums", match:"a|b|c", card="1" } # "int:[0,100]" { type:"int", oper:"range", match:[0,100], card="1" } # "float:[0.0,100.0,1.0] { type:"float", oper:"range", match:[0.0,100.0,1.0], card="1" } # "string:["","zzz"] { type:"string", oper:"range", match:["","zzz"], card="1" } # "boolean" { type:"boolean", oper:"any", match:"any", card="1" } # "object:{r:[0,255],g:[0,255],b:[0,255]} # { type:"object", oper:"range", match:{r:[0,255],g:[0,255],b:[0,255]}, card="1" } # "array:[[0,360],[0,100],[0,100]]:?" # { type:"array", oper:"range", match:[[0,360],[0,100],[0,100]], card="?" } toSpecParse:( arg ) -> spec = @toSpecInit() return spec if not @isSpecParse(arg) splits = arg.split(":") length = splits.length if length >= 1 then spec.type = splits[0] # type if length >= 1 # match type = @toType(splits[1]) spec.match = switch type when "regexp" then "regexp" # regex when "string" switch when splits[1].includes("|") then @toEnums( splits[1] ) # enums when @isEnclosed( "[", splits[1], "]" ) then @toArray( splits[1] ) # range when @isEnclosed( "{", splits[1], "}" ) then @toObject( splits[1] ) # object? else "any" else "any" if length >= 2 then spec.card = splits[2] # card i.e cardinaliry spec toSpecObject:( arg ) -> spec = @toSpecInit() return spec if not @isSpecObject(arg) spec.type = if arg.type? then arg.type else "any" spec.match = if arg.match? then arg.match else "any" spec.card = if arg.card? then arg.card else "1" # required spec toSpecInit:() -> { type:"any", match:"any", card:"1" } toRange:( arg ) -> if @isType(arg,"range") then arg else "any" toRanges:(range) -> range = @strip( range, "|", "|") range = range.replaceAll( " ", "" ) # remove white space range.split(",") # |a-z| |0-100| |0-100+0.001| toRangeArray:( range ) -> a = [] range = @strip( range, "|", "|") range = range.replaceAll( " ", "" ) # remove white space splits = range.split("-") # Append the optional 3rd parameter tolerance for 'float' ranges if splits.length is 2 and splits[1].includes("+") splits2 = splits[1].split("+") splits[1] = splits2[0] splits.push(splits2[1]) switch @toType(splits[0]) when "string" and splits.length is 2 # 'string' a.push(splits[0]) a.push(splits[1]) when "int" and splits.length is 2 # 'int' a.push(@toInt(splits[0])) a.push(@toInt(splits[1])) when "float" and splits.length is 3 # 'float' a.push(@toFloat(splits[0])) a.push(@toFloat(splits[1])) a.push(@toFloat(splits[2])) else a # Moved to Type.coffee toEnums:( arg ) -> super.toEnums(arg) # Arg types must be 'regexp' or 'string', otherwise returns 'any' toRegexp:( arg ) -> switch @toType(arg) when "regexp" then arg when "string" then new RegExp(arg) else "any" # -- in... Spec matches inSpec:( result, spec ) -> return false if @isNot(spec) or not ( @isSpec(spec) and @toType(result) is spec.type and @inCard(result,spec) ) match = spec.match switch when @isArray(result) and @isArray(spec) then @inSpecArray( result, spec ) when @isObject(result) and @isObject(spec) then @inSpecObject( result, spec ) when @isRange( match ) then @isRange( result, match ) when @isEnums( match ) then @isEnums( result, match ) when @isRegexp( match ) then @isRegexp( result, match ) else false # Here only minimum length of spec and result are checked inSpecArray:( result, spec ) -> pass = true min = Math.min( result.length, spec.length ) pass = pass and @inSpec(result[i],spec[i]) for i in [0...min] pass # Here only the keys common to both spec and result are checked inSpecObject:( result, spec ) -> pass = true for own key, val of spec when result[key]? pass = pass and @inSpec(result[key],spec[key]) pass # Determine if a result is bounded witnin a range. # This method is here in Tester because it call @examine() inRange:( result, range ) -> return @inRanges(result,@toRanges(range)) if range.includes(",") return false if not @isType(range) # @isRange(range) a = @toRangeArray(range) # Convers the range to an array inStrRange = ( string, a ) -> a[0] <= string and string <= a[1] inIntRange = ( int, a ) -> a[0] <= int and int <= a[1] inFloatRange = ( float, a ) -> a[0]-a[2] <= float and float <= a[1]+a[2] switch @toType(result) when "string" then inStrRange( result, a ) when "int" then inIntRange( result, a ) when "float" then inFloatRange( result, a ) else false # Ony apply the ranges we have are applied # if ranges is just a single range applied then it is applied to each result inRanges:( results, ranges ) -> pass = true switch when @isArray(results) and @isArray(ranges) min = Math.min( results.length, ranges.length ) # Ony apply the ranges we ga pass = pass and @inRange(results[i],ranges[i]) for i in [0...min] when @isArray(results) pass = pass and @inRange(results,ranges) for result in results else pass = false pass # Determine if a result is enumerated. # inEnums:( result, enums ) -> # super.toEnums( result, enums ) inRegexp:( result, regexp ) -> return false if not @isRegexp(regexp) regexp = @toRegexp( regexp ) regexp.test(result) isCard:( card ) -> @isStr(card) and ( @isType(card,"int") or card.includes(":") or @isIn(card,"cards") ) # ... more to come for checking cardinallity inCard:( result, spec ) -> card = spec.card switch when @isType(card,"int") then true when @isStr(card) and card.includes("-") minMax = @toMinMax(card) num = minMax[0] # Dummy number minMax[0] <= num <= minMax[1] else switch card when "1" then true when "?" then true when "*" then true when "+" then true else false toMinMax:( card ) -> splits = card.split(":") min = @toInt(splits[0]) max = @toInt(splits[1]) [min,max] export spec = new Spec() # Export a singleton instence of type export default Spec
[ { "context": " backbone-orm.js 0.7.14\n Copyright (c) 2013-2016 Vidigami\n License: MIT (http://www.opensource.org/license", "end": 63, "score": 0.9998626708984375, "start": 55, "tag": "NAME", "value": "Vidigami" }, { "context": "ses/mit-license.php)\n Source: https://github.com/...
src/extensions/model_interval.coffee
dk-dev/backbone-orm
54
### backbone-orm.js 0.7.14 Copyright (c) 2013-2016 Vidigami License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/vidigami/backbone-orm Dependencies: Backbone.js and Underscore.js. ### _ = require 'underscore' Queue = require '../lib/queue' Utils = require '../lib/utils' JSONUtils = require '../lib/json_utils' DateUtils = require '../lib/date_utils' INTERVAL_TYPES = ['milliseconds', 'seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'years'] module.exports = (model_type, query, iterator, callback) -> options = query.$interval or {} throw new Error 'missing option: key' unless key = options.key throw new Error 'missing option: type' unless options.type throw new Error("type is not recognized: #{options.type}, #{_.contains(INTERVAL_TYPES, options.type)}") unless _.contains(INTERVAL_TYPES, options.type) iteration_info = _.clone(options) iteration_info.range = {} unless iteration_info.range range = iteration_info.range no_models = false queue = new Queue(1) # start queue.defer (callback) -> # find the first record unless start = (range.$gte or range.$gt) model_type.cursor(query).limit(1).sort(key).toModels (err, models) -> return callback(err) if err (no_models = true; return callback()) unless models.length range.start = iteration_info.first = models[0].get(key) callback() # find the closest record to the start else range.start = start model_type.findOneNearestDate start, {key: key, reverse: true}, query, (err, model) -> return callback(err) if err (no_models = true; return callback()) unless model iteration_info.first = model.get(key) callback() # end queue.defer (callback) -> return callback() if no_models # find the last record unless end = (range.$lte or range.$lt) model_type.cursor(query).limit(1).sort("-#{key}").toModels (err, models) -> return callback(err) if err (no_models = true; return callback()) unless models.length range.end = iteration_info.last = models[0].get(key) callback() # find the closest record to the end else range.end = end model_type.findOneNearestDate end, {key: key}, query, (err, model) -> return callback(err) if err (no_models = true; return callback()) unless model iteration_info.last = model.get(key) callback() # process queue.await (err) -> return callback(err) if err return callback() if no_models # interval length start_ms = range.start.getTime() length_ms = DateUtils.durationAsMilliseconds((if _.isUndefined(options.length) then 1 else options.length), options.type) throw Error("length_ms is invalid: #{length_ms} for range: #{JSONUtils.stringify(range)}") unless length_ms query = _.omit(query, '$interval') query.$sort = [key] processed_count = 0 iteration_info.index = 0 runInterval = (current) -> return callback() if DateUtils.isAfter(current, range.end) # done # find the next entry query[key] = {$gte: current, $lte: iteration_info.last} model_type.findOne query, (err, model) -> return callback(err) if err return callback() unless model # done # skip to next next = model.get(key) iteration_info.index = Math.floor((next.getTime() - start_ms) / length_ms) current = new Date(range.start.getTime() + iteration_info.index * length_ms) iteration_info.start = current next = new Date(current.getTime() + length_ms) iteration_info.end = next query[key] = {$gte: current, $lt: next} iterator query, iteration_info, (err) -> return callback(err) if err runInterval(next) runInterval(range.start)
219522
### backbone-orm.js 0.7.14 Copyright (c) 2013-2016 <NAME> License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/vidigami/backbone-orm Dependencies: Backbone.js and Underscore.js. ### _ = require 'underscore' Queue = require '../lib/queue' Utils = require '../lib/utils' JSONUtils = require '../lib/json_utils' DateUtils = require '../lib/date_utils' INTERVAL_TYPES = ['milliseconds', 'seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'years'] module.exports = (model_type, query, iterator, callback) -> options = query.$interval or {} throw new Error 'missing option: key' unless key = options.key throw new Error 'missing option: type' unless options.type throw new Error("type is not recognized: #{options.type}, #{_.contains(INTERVAL_TYPES, options.type)}") unless _.contains(INTERVAL_TYPES, options.type) iteration_info = _.clone(options) iteration_info.range = {} unless iteration_info.range range = iteration_info.range no_models = false queue = new Queue(1) # start queue.defer (callback) -> # find the first record unless start = (range.$gte or range.$gt) model_type.cursor(query).limit(1).sort(key).toModels (err, models) -> return callback(err) if err (no_models = true; return callback()) unless models.length range.start = iteration_info.first = models[0].get(key) callback() # find the closest record to the start else range.start = start model_type.findOneNearestDate start, {key: key, reverse: true}, query, (err, model) -> return callback(err) if err (no_models = true; return callback()) unless model iteration_info.first = model.get(key) callback() # end queue.defer (callback) -> return callback() if no_models # find the last record unless end = (range.$lte or range.$lt) model_type.cursor(query).limit(1).sort("-#{key}").toModels (err, models) -> return callback(err) if err (no_models = true; return callback()) unless models.length range.end = iteration_info.last = models[0].get(key) callback() # find the closest record to the end else range.end = end model_type.findOneNearestDate end, {key: key}, query, (err, model) -> return callback(err) if err (no_models = true; return callback()) unless model iteration_info.last = model.get(key) callback() # process queue.await (err) -> return callback(err) if err return callback() if no_models # interval length start_ms = range.start.getTime() length_ms = DateUtils.durationAsMilliseconds((if _.isUndefined(options.length) then 1 else options.length), options.type) throw Error("length_ms is invalid: #{length_ms} for range: #{JSONUtils.stringify(range)}") unless length_ms query = _.omit(query, '$interval') query.$sort = [key] processed_count = 0 iteration_info.index = 0 runInterval = (current) -> return callback() if DateUtils.isAfter(current, range.end) # done # find the next entry query[key] = {$gte: current, $lte: iteration_info.last} model_type.findOne query, (err, model) -> return callback(err) if err return callback() unless model # done # skip to next next = model.get(key) iteration_info.index = Math.floor((next.getTime() - start_ms) / length_ms) current = new Date(range.start.getTime() + iteration_info.index * length_ms) iteration_info.start = current next = new Date(current.getTime() + length_ms) iteration_info.end = next query[key] = {$gte: current, $lt: next} iterator query, iteration_info, (err) -> return callback(err) if err runInterval(next) runInterval(range.start)
true
### backbone-orm.js 0.7.14 Copyright (c) 2013-2016 PI:NAME:<NAME>END_PI License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/vidigami/backbone-orm Dependencies: Backbone.js and Underscore.js. ### _ = require 'underscore' Queue = require '../lib/queue' Utils = require '../lib/utils' JSONUtils = require '../lib/json_utils' DateUtils = require '../lib/date_utils' INTERVAL_TYPES = ['milliseconds', 'seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'years'] module.exports = (model_type, query, iterator, callback) -> options = query.$interval or {} throw new Error 'missing option: key' unless key = options.key throw new Error 'missing option: type' unless options.type throw new Error("type is not recognized: #{options.type}, #{_.contains(INTERVAL_TYPES, options.type)}") unless _.contains(INTERVAL_TYPES, options.type) iteration_info = _.clone(options) iteration_info.range = {} unless iteration_info.range range = iteration_info.range no_models = false queue = new Queue(1) # start queue.defer (callback) -> # find the first record unless start = (range.$gte or range.$gt) model_type.cursor(query).limit(1).sort(key).toModels (err, models) -> return callback(err) if err (no_models = true; return callback()) unless models.length range.start = iteration_info.first = models[0].get(key) callback() # find the closest record to the start else range.start = start model_type.findOneNearestDate start, {key: key, reverse: true}, query, (err, model) -> return callback(err) if err (no_models = true; return callback()) unless model iteration_info.first = model.get(key) callback() # end queue.defer (callback) -> return callback() if no_models # find the last record unless end = (range.$lte or range.$lt) model_type.cursor(query).limit(1).sort("-#{key}").toModels (err, models) -> return callback(err) if err (no_models = true; return callback()) unless models.length range.end = iteration_info.last = models[0].get(key) callback() # find the closest record to the end else range.end = end model_type.findOneNearestDate end, {key: key}, query, (err, model) -> return callback(err) if err (no_models = true; return callback()) unless model iteration_info.last = model.get(key) callback() # process queue.await (err) -> return callback(err) if err return callback() if no_models # interval length start_ms = range.start.getTime() length_ms = DateUtils.durationAsMilliseconds((if _.isUndefined(options.length) then 1 else options.length), options.type) throw Error("length_ms is invalid: #{length_ms} for range: #{JSONUtils.stringify(range)}") unless length_ms query = _.omit(query, '$interval') query.$sort = [key] processed_count = 0 iteration_info.index = 0 runInterval = (current) -> return callback() if DateUtils.isAfter(current, range.end) # done # find the next entry query[key] = {$gte: current, $lte: iteration_info.last} model_type.findOne query, (err, model) -> return callback(err) if err return callback() unless model # done # skip to next next = model.get(key) iteration_info.index = Math.floor((next.getTime() - start_ms) / length_ms) current = new Date(range.start.getTime() + iteration_info.index * length_ms) iteration_info.start = current next = new Date(current.getTime() + length_ms) iteration_info.end = next query[key] = {$gte: current, $lt: next} iterator query, iteration_info, (err) -> return callback(err) if err runInterval(next) runInterval(range.start)
[ { "context": "t #273\"\n# Eg. \"Merge please: https://github.com/martinemde/hubot-slack-github-issue-link/pull/1\"\n#\n# Defau", "end": 284, "score": 0.999704897403717, "start": 274, "tag": "USERNAME", "value": "martinemde" }, { "context": " I've never used github enterprise\n#\n...
src/slack-github-issue-link.coffee
martinemde/hubot-slack-github-pull-requests
4
# Description: # Slack Github issue link looks for #nnn, and pull or issue urls # and posts an informative Slack attachment that show detailed information # about the issue or pull request. # # Eg. "Hey guys check out #273" # Eg. "Merge please: https://github.com/martinemde/hubot-slack-github-issue-link/pull/1" # # Defaults to issues in HUBOT_GITHUB_REPO when only matching #NNN, # unless a repo is specified Eg. "Hey guys, check out awesome-repo#273" # # If HUBOT_GITHUB_IGNORE_PUBLIC_LINKS is set, this scirpt will ignore # links outside of the org set in HUBOT_GITHUB_ORG, and all non-private # project links to avoid double posting public projects. Slackbot will # post (less pretty) links to public github urls, which cannot be avoided. # # Dependencies: # "githubot": "0.4.x" # # Configuration: # HUBOT_GITHUB_REPO # HUBOT_GITHUB_TOKEN # HUBOT_GITHUB_API # HUBOT_GITHUB_HOSTNAME # HUBOT_GITHUB_ISSUE_LINK_IGNORE_USERS # HUBOT_GITHUB_IGNORE_PUBLIC_LINKS # HUBOT_GITHUB_ORG # # Commands: # repo#nnn - link to GitHub issue nnn for repo project # user/repo#nnn - link to GitHub issue nnn for user/repo project # https://github.com/org/repo/issue/1234 - show details for github issue # https://github.com/org/repo/pull/1234 - show details for github pullrequest # # Notes: # HUBOT_GITHUB_HOSTNAME, if set, expects the scheme (https://). Defaults to "https://github.com/" # HUBOT_GITHUB_API allows you to set a custom URL path (for Github enterprise users) but the links won't match your domain since this only looks for github.com domains. I've never used github enterprise # # Author: # Martin Emde <me@martinemde.com> # Originally by tenfef module.exports = (robot) -> github = require("githubot")(robot) githubIgnoreUsers = process.env.HUBOT_GITHUB_ISSUE_LINK_IGNORE_USERS or "github|hubot" githubHostname = process.env.HUBOT_GITHUB_HOSTNAME or "https://github.com/" githubProjectMatch = if process.env.HUBOT_GITHUB_IGNORE_PUBLIC_LINKS != undefined && process.env.HUBOT_GITHUB_ORG != undefined "#{process.env.HUBOT_GITHUB_ORG}/" else "\\S" githubIssueUrlPattern = ///(#{githubHostname}\/?)?((#{githubProjectMatch}*|^)?(/issues?/|/pulls?/)(\d+)).*///i attachmentColor = (obj) -> if obj.labels && obj.labels[0] color = obj.labels[0].color else if obj.merged color = "#6e5494" else switch obj.state when "closed" color = "#bd2c00" else color = "good" makeAttachment = (obj, type, repo_name) -> issue_title = obj.title html_url = obj.html_url body = if obj.body.length > 80 then obj.body.substring(0,80) + "..." else obj.body color = attachmentColor(obj) state = obj.state.charAt(0).toUpperCase() + obj.state.slice(1) if obj.commits if obj.commits == 1 commits = "commit" else commits = "commits" merged = if obj.merged then "merged by #{obj.merged_by.login}" else "unmerged" merged_commits = "#{obj.commits || 0} #{commits} #{merged}" fields = [{ title: state value: merged_commits short: true }] else fields = [{ title: state short: true }] if obj.head && obj.head.ref fields.push title: "#{obj.changed_files} files (++#{obj.additions} / --#{obj.deletions})" value: "<#{obj.html_url}/files|#{obj.head.ref}>" short: true return { fallback: "[#{repo_name}] #{type} ##{obj.number} (#{state}): #{issue_title} #{html_url}" pretext: "[#{repo_name}] #{type} ##{obj.number}" title: issue_title title_link: html_url text: body color: color author_name: obj.user.login author_link: obj.user.html_url author_icon: obj.user.avatar_url fields: fields } matchRepo = (repo) -> if repo == undefined return github.qualified_repo process.env.HUBOT_GITHUB_REPO else if process.env.HUBOT_GITHUB_IGNORE_PUBLIC_LINKS && process.env.HUBOT_GITHUB_ORG && !repo.match(new RegExp(process.env.HUBOT_GITHUB_ORG, "i")) return undefined else return github.qualified_repo repo robot.hear githubIssueUrlPattern, id: "hubot-slack-github-issue-link", (msg) -> if msg.message.user.name.match(new RegExp(githubIgnoreUsers, "gi")) return issue_number = msg.match[5] if isNaN(issue_number) return repo_name = matchRepo(msg.match[3]) if repo_name == undefined return base_url = process.env.HUBOT_GITHUB_API || 'https://api.github.com' if msg.match[4] == undefined || msg.match[4] == '#' path = "/issues/" else path = msg.match[4] if path.match /\/pulls?\// type = "Pull Request" api_path = "pulls" else type = "Issue" api_path = "issues" api_url = "#{base_url}/repos/#{repo_name}/#{api_path}/" + issue_number github.get api_url, (obj) -> # We usually don't post public PRs, Slack will show them if process.env.HUBOT_GITHUB_IGNORE_PUBLIC_LINKS && obj.base?.repo?.private == false return # need to figure out how to exclude public issues attachment = makeAttachment(obj, type, repo_name) msg.send text: 'GitHub Info', attachments: [attachment]
181838
# Description: # Slack Github issue link looks for #nnn, and pull or issue urls # and posts an informative Slack attachment that show detailed information # about the issue or pull request. # # Eg. "Hey guys check out #273" # Eg. "Merge please: https://github.com/martinemde/hubot-slack-github-issue-link/pull/1" # # Defaults to issues in HUBOT_GITHUB_REPO when only matching #NNN, # unless a repo is specified Eg. "Hey guys, check out awesome-repo#273" # # If HUBOT_GITHUB_IGNORE_PUBLIC_LINKS is set, this scirpt will ignore # links outside of the org set in HUBOT_GITHUB_ORG, and all non-private # project links to avoid double posting public projects. Slackbot will # post (less pretty) links to public github urls, which cannot be avoided. # # Dependencies: # "githubot": "0.4.x" # # Configuration: # HUBOT_GITHUB_REPO # HUBOT_GITHUB_TOKEN # HUBOT_GITHUB_API # HUBOT_GITHUB_HOSTNAME # HUBOT_GITHUB_ISSUE_LINK_IGNORE_USERS # HUBOT_GITHUB_IGNORE_PUBLIC_LINKS # HUBOT_GITHUB_ORG # # Commands: # repo#nnn - link to GitHub issue nnn for repo project # user/repo#nnn - link to GitHub issue nnn for user/repo project # https://github.com/org/repo/issue/1234 - show details for github issue # https://github.com/org/repo/pull/1234 - show details for github pullrequest # # Notes: # HUBOT_GITHUB_HOSTNAME, if set, expects the scheme (https://). Defaults to "https://github.com/" # HUBOT_GITHUB_API allows you to set a custom URL path (for Github enterprise users) but the links won't match your domain since this only looks for github.com domains. I've never used github enterprise # # Author: # <NAME> <<EMAIL>> # Originally by tenfef module.exports = (robot) -> github = require("githubot")(robot) githubIgnoreUsers = process.env.HUBOT_GITHUB_ISSUE_LINK_IGNORE_USERS or "github|hubot" githubHostname = process.env.HUBOT_GITHUB_HOSTNAME or "https://github.com/" githubProjectMatch = if process.env.HUBOT_GITHUB_IGNORE_PUBLIC_LINKS != undefined && process.env.HUBOT_GITHUB_ORG != undefined "#{process.env.HUBOT_GITHUB_ORG}/" else "\\S" githubIssueUrlPattern = ///(#{githubHostname}\/?)?((#{githubProjectMatch}*|^)?(/issues?/|/pulls?/)(\d+)).*///i attachmentColor = (obj) -> if obj.labels && obj.labels[0] color = obj.labels[0].color else if obj.merged color = "#6e5494" else switch obj.state when "closed" color = "#bd2c00" else color = "good" makeAttachment = (obj, type, repo_name) -> issue_title = obj.title html_url = obj.html_url body = if obj.body.length > 80 then obj.body.substring(0,80) + "..." else obj.body color = attachmentColor(obj) state = obj.state.charAt(0).toUpperCase() + obj.state.slice(1) if obj.commits if obj.commits == 1 commits = "commit" else commits = "commits" merged = if obj.merged then "merged by #{obj.merged_by.login}" else "unmerged" merged_commits = "#{obj.commits || 0} #{commits} #{merged}" fields = [{ title: state value: merged_commits short: true }] else fields = [{ title: state short: true }] if obj.head && obj.head.ref fields.push title: "#{obj.changed_files} files (++#{obj.additions} / --#{obj.deletions})" value: "<#{obj.html_url}/files|#{obj.head.ref}>" short: true return { fallback: "[#{repo_name}] #{type} ##{obj.number} (#{state}): #{issue_title} #{html_url}" pretext: "[#{repo_name}] #{type} ##{obj.number}" title: issue_title title_link: html_url text: body color: color author_name: obj.user.login author_link: obj.user.html_url author_icon: obj.user.avatar_url fields: fields } matchRepo = (repo) -> if repo == undefined return github.qualified_repo process.env.HUBOT_GITHUB_REPO else if process.env.HUBOT_GITHUB_IGNORE_PUBLIC_LINKS && process.env.HUBOT_GITHUB_ORG && !repo.match(new RegExp(process.env.HUBOT_GITHUB_ORG, "i")) return undefined else return github.qualified_repo repo robot.hear githubIssueUrlPattern, id: "hubot-slack-github-issue-link", (msg) -> if msg.message.user.name.match(new RegExp(githubIgnoreUsers, "gi")) return issue_number = msg.match[5] if isNaN(issue_number) return repo_name = matchRepo(msg.match[3]) if repo_name == undefined return base_url = process.env.HUBOT_GITHUB_API || 'https://api.github.com' if msg.match[4] == undefined || msg.match[4] == '#' path = "/issues/" else path = msg.match[4] if path.match /\/pulls?\// type = "Pull Request" api_path = "pulls" else type = "Issue" api_path = "issues" api_url = "#{base_url}/repos/#{repo_name}/#{api_path}/" + issue_number github.get api_url, (obj) -> # We usually don't post public PRs, Slack will show them if process.env.HUBOT_GITHUB_IGNORE_PUBLIC_LINKS && obj.base?.repo?.private == false return # need to figure out how to exclude public issues attachment = makeAttachment(obj, type, repo_name) msg.send text: 'GitHub Info', attachments: [attachment]
true
# Description: # Slack Github issue link looks for #nnn, and pull or issue urls # and posts an informative Slack attachment that show detailed information # about the issue or pull request. # # Eg. "Hey guys check out #273" # Eg. "Merge please: https://github.com/martinemde/hubot-slack-github-issue-link/pull/1" # # Defaults to issues in HUBOT_GITHUB_REPO when only matching #NNN, # unless a repo is specified Eg. "Hey guys, check out awesome-repo#273" # # If HUBOT_GITHUB_IGNORE_PUBLIC_LINKS is set, this scirpt will ignore # links outside of the org set in HUBOT_GITHUB_ORG, and all non-private # project links to avoid double posting public projects. Slackbot will # post (less pretty) links to public github urls, which cannot be avoided. # # Dependencies: # "githubot": "0.4.x" # # Configuration: # HUBOT_GITHUB_REPO # HUBOT_GITHUB_TOKEN # HUBOT_GITHUB_API # HUBOT_GITHUB_HOSTNAME # HUBOT_GITHUB_ISSUE_LINK_IGNORE_USERS # HUBOT_GITHUB_IGNORE_PUBLIC_LINKS # HUBOT_GITHUB_ORG # # Commands: # repo#nnn - link to GitHub issue nnn for repo project # user/repo#nnn - link to GitHub issue nnn for user/repo project # https://github.com/org/repo/issue/1234 - show details for github issue # https://github.com/org/repo/pull/1234 - show details for github pullrequest # # Notes: # HUBOT_GITHUB_HOSTNAME, if set, expects the scheme (https://). Defaults to "https://github.com/" # HUBOT_GITHUB_API allows you to set a custom URL path (for Github enterprise users) but the links won't match your domain since this only looks for github.com domains. I've never used github enterprise # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Originally by tenfef module.exports = (robot) -> github = require("githubot")(robot) githubIgnoreUsers = process.env.HUBOT_GITHUB_ISSUE_LINK_IGNORE_USERS or "github|hubot" githubHostname = process.env.HUBOT_GITHUB_HOSTNAME or "https://github.com/" githubProjectMatch = if process.env.HUBOT_GITHUB_IGNORE_PUBLIC_LINKS != undefined && process.env.HUBOT_GITHUB_ORG != undefined "#{process.env.HUBOT_GITHUB_ORG}/" else "\\S" githubIssueUrlPattern = ///(#{githubHostname}\/?)?((#{githubProjectMatch}*|^)?(/issues?/|/pulls?/)(\d+)).*///i attachmentColor = (obj) -> if obj.labels && obj.labels[0] color = obj.labels[0].color else if obj.merged color = "#6e5494" else switch obj.state when "closed" color = "#bd2c00" else color = "good" makeAttachment = (obj, type, repo_name) -> issue_title = obj.title html_url = obj.html_url body = if obj.body.length > 80 then obj.body.substring(0,80) + "..." else obj.body color = attachmentColor(obj) state = obj.state.charAt(0).toUpperCase() + obj.state.slice(1) if obj.commits if obj.commits == 1 commits = "commit" else commits = "commits" merged = if obj.merged then "merged by #{obj.merged_by.login}" else "unmerged" merged_commits = "#{obj.commits || 0} #{commits} #{merged}" fields = [{ title: state value: merged_commits short: true }] else fields = [{ title: state short: true }] if obj.head && obj.head.ref fields.push title: "#{obj.changed_files} files (++#{obj.additions} / --#{obj.deletions})" value: "<#{obj.html_url}/files|#{obj.head.ref}>" short: true return { fallback: "[#{repo_name}] #{type} ##{obj.number} (#{state}): #{issue_title} #{html_url}" pretext: "[#{repo_name}] #{type} ##{obj.number}" title: issue_title title_link: html_url text: body color: color author_name: obj.user.login author_link: obj.user.html_url author_icon: obj.user.avatar_url fields: fields } matchRepo = (repo) -> if repo == undefined return github.qualified_repo process.env.HUBOT_GITHUB_REPO else if process.env.HUBOT_GITHUB_IGNORE_PUBLIC_LINKS && process.env.HUBOT_GITHUB_ORG && !repo.match(new RegExp(process.env.HUBOT_GITHUB_ORG, "i")) return undefined else return github.qualified_repo repo robot.hear githubIssueUrlPattern, id: "hubot-slack-github-issue-link", (msg) -> if msg.message.user.name.match(new RegExp(githubIgnoreUsers, "gi")) return issue_number = msg.match[5] if isNaN(issue_number) return repo_name = matchRepo(msg.match[3]) if repo_name == undefined return base_url = process.env.HUBOT_GITHUB_API || 'https://api.github.com' if msg.match[4] == undefined || msg.match[4] == '#' path = "/issues/" else path = msg.match[4] if path.match /\/pulls?\// type = "Pull Request" api_path = "pulls" else type = "Issue" api_path = "issues" api_url = "#{base_url}/repos/#{repo_name}/#{api_path}/" + issue_number github.get api_url, (obj) -> # We usually don't post public PRs, Slack will show them if process.env.HUBOT_GITHUB_IGNORE_PUBLIC_LINKS && obj.base?.repo?.private == false return # need to figure out how to exclude public issues attachment = makeAttachment(obj, type, repo_name) msg.send text: 'GitHub Info', attachments: [attachment]
[ { "context": " email: user.email\n password: ndx.generateHash req.body.password\n , where\n ", "end": 1728, "score": 0.7566696405410767, "start": 1716, "tag": "PASSWORD", "value": "ndx.generate" } ]
src/forgot.coffee
ndxbxrme/ndx-passport
0
'use strict' module.exports = (ndx) -> if ndx.settings.HAS_FORGOT or process.env.HAS_FORGOT ndx.forgot = fetchTemplate: (data, cb) -> cb subject: "forgot password" body: 'h1 forgot password\np\n a(href="#{code}")= code' from: "System" ndx.setForgotTemplate = (template) -> forgotTemplate = template ndx.app.post '/get-forgot-code', (req, res, next) -> ndx.passport.fetchByEmail req.body.email, (users) -> if users and users.length ndx.invite.tokenFromUser users[0], (token) -> host = process.env.HOST or ndx.settings.HOST or "#{req.protocol}://#{req.hostname}" ndx.forgot.fetchTemplate req.body, (forgotTemplate) -> if ndx.email ndx.email.send to: req.body.email from: forgotTemplate.from subject: forgotTemplate.subject body: forgotTemplate.body code: "#{host}/forgot/#{token}" host: host user: users[0] ndx.passport.syncCallback 'resetPasswordRequest', obj: users[0] code: token res.end token else return next 'No user found' ndx.app.post '/forgot-update/:code', (req, res, next) -> user = JSON.parse ndx.parseToken(req.params.code, true) ndx.invite.userFromToken req.params.code, (err, user) -> if req.body.password where = {} where[ndx.settings.AUTO_ID] = user[ndx.settings.AUTO_ID] ndx.database.update ndx.settings.USER_TABLE, local: email: user.email password: ndx.generateHash req.body.password , where if ndx.shortToken ndx.shortToken.remove req.params.code ndx.passport.syncCallback 'resetPassword', obj: user code: req.params.code res.end 'OK' else next 'No password'
220825
'use strict' module.exports = (ndx) -> if ndx.settings.HAS_FORGOT or process.env.HAS_FORGOT ndx.forgot = fetchTemplate: (data, cb) -> cb subject: "forgot password" body: 'h1 forgot password\np\n a(href="#{code}")= code' from: "System" ndx.setForgotTemplate = (template) -> forgotTemplate = template ndx.app.post '/get-forgot-code', (req, res, next) -> ndx.passport.fetchByEmail req.body.email, (users) -> if users and users.length ndx.invite.tokenFromUser users[0], (token) -> host = process.env.HOST or ndx.settings.HOST or "#{req.protocol}://#{req.hostname}" ndx.forgot.fetchTemplate req.body, (forgotTemplate) -> if ndx.email ndx.email.send to: req.body.email from: forgotTemplate.from subject: forgotTemplate.subject body: forgotTemplate.body code: "#{host}/forgot/#{token}" host: host user: users[0] ndx.passport.syncCallback 'resetPasswordRequest', obj: users[0] code: token res.end token else return next 'No user found' ndx.app.post '/forgot-update/:code', (req, res, next) -> user = JSON.parse ndx.parseToken(req.params.code, true) ndx.invite.userFromToken req.params.code, (err, user) -> if req.body.password where = {} where[ndx.settings.AUTO_ID] = user[ndx.settings.AUTO_ID] ndx.database.update ndx.settings.USER_TABLE, local: email: user.email password: <PASSWORD>Hash req.body.password , where if ndx.shortToken ndx.shortToken.remove req.params.code ndx.passport.syncCallback 'resetPassword', obj: user code: req.params.code res.end 'OK' else next 'No password'
true
'use strict' module.exports = (ndx) -> if ndx.settings.HAS_FORGOT or process.env.HAS_FORGOT ndx.forgot = fetchTemplate: (data, cb) -> cb subject: "forgot password" body: 'h1 forgot password\np\n a(href="#{code}")= code' from: "System" ndx.setForgotTemplate = (template) -> forgotTemplate = template ndx.app.post '/get-forgot-code', (req, res, next) -> ndx.passport.fetchByEmail req.body.email, (users) -> if users and users.length ndx.invite.tokenFromUser users[0], (token) -> host = process.env.HOST or ndx.settings.HOST or "#{req.protocol}://#{req.hostname}" ndx.forgot.fetchTemplate req.body, (forgotTemplate) -> if ndx.email ndx.email.send to: req.body.email from: forgotTemplate.from subject: forgotTemplate.subject body: forgotTemplate.body code: "#{host}/forgot/#{token}" host: host user: users[0] ndx.passport.syncCallback 'resetPasswordRequest', obj: users[0] code: token res.end token else return next 'No user found' ndx.app.post '/forgot-update/:code', (req, res, next) -> user = JSON.parse ndx.parseToken(req.params.code, true) ndx.invite.userFromToken req.params.code, (err, user) -> if req.body.password where = {} where[ndx.settings.AUTO_ID] = user[ndx.settings.AUTO_ID] ndx.database.update ndx.settings.USER_TABLE, local: email: user.email password: PI:PASSWORD:<PASSWORD>END_PIHash req.body.password , where if ndx.shortToken ndx.shortToken.remove req.params.code ndx.passport.syncCallback 'resetPassword', obj: user code: req.params.code res.end 'OK' else next 'No password'
[ { "context": "onent'\n # flex: 0\n # html: 'Gallons'\n # cls: 'field-label-text'\n ", "end": 3034, "score": 0.5767993927001953, "start": 3027, "tag": "NAME", "value": "Gallons" }, { "context": " # xtype: 'sliderfield'\n # id...
src/app/view/RequestForm.coffee
Purple-Services/app
2
Ext.define 'Purple.view.RequestForm', extend: 'Ext.form.Panel' xtype: 'requestform' requires: [ 'Ext.form.*' 'Ext.field.*' 'Ext.Button' ] config: layout: type: 'hbox' pack: 'start' align: 'start' height: '100%' submitOnAction: no cls: [ 'request-form' 'accent-bg' 'slideable' ] scrollable: direction: 'vertical' directionLock: yes translatable: translationMethod: 'auto' items: [ { xtype: 'spacer' flex: 1 } { xtype: 'container' flex: 0 width: '85%' layout: type: 'vbox' pack: 'start' align: 'start' items: [ { xtype: 'component' flex: 0 cls: 'heading' html: 'Request Gas' } { xtype: 'component' flex: 0 cls: [ 'horizontal-rule' 'purple-rule' ] } { xtype: 'selectfield' ctype: 'requestFormVehicleSelect' flex: 0 name: 'vehicle' label: 'Vehicle' labelWidth: 87 listPicker: title: 'Select a Vehicle' cls: [ 'click-to-edit' 'bottom-margin' ] options: [ ] } { xtype: 'selectfield' ctype: 'requestFormGallonsSelect' flex: 0 name: 'gallons' label: 'Gallons' labelWidth: 100 listPicker: title: 'Number of Gallons' cls: [ 'click-to-edit' 'bottom-margin' 'visibly-disabled' ] disabled: yes options: [ ] } { xtype: 'selectfield' ctype: 'requestFormTimeSelect' flex: 0 name: 'time' label: 'Time' listPicker: title: 'Select a Time' cls: [ 'click-to-edit' 'bottom-margin' 'visibly-disabled' ] disabled: yes options: [ ] } { xtype: 'checkboxfield' ctype: 'requestFormTirePressureCheck' flex: 0 name: 'tire_pressure_check' label: 'Tire Fill-up?' # also change in requestFormVehicleSelectChange func labelWidth: 200 cls: [ 'bottom-margin' ] } { xtype: 'hiddenfield' ctype: 'requestFormTirePressureCheckPrice' name: 'tire_pressure_check_price' } # { # xtype: 'component' # flex: 0 # cls: 'horizontal-rule' # } # { # xtype: 'component' # flex: 0 # html: 'Gallons' # cls: 'field-label-text' # } # { # xtype: 'sliderfield' # id: 'gallons' # flex: 0 # width: '100%' # padding: 0 # margin: 0 # minValue: 5 # maxValue: 15 # increment: 5 # listeners: # drag: (field, ignore, ignore2, newValue) -> # #@adjustBrightness newValue # true # change: (field, ignore, ignore2, newValue) -> # #@adjustBrightness newValue # true # } # { # xtype: 'component' # flex: 0 # width: '100%' # html: """ # <div class="tick-label-container"> # <div class="tick-label" style="margin-left: 0px;">5</div> # <div class="tick-label" style="left: 50%;">10</div> # <div class="tick-label" style="right: 0px;">15</div> # </div> # """ # } { xtype: 'component' flex: 0 cls: 'horizontal-rule' } { xtype: 'component' flex: 0 html: 'Special Instructions' cls: 'field-label-text' } { xtype: 'textareafield' ctype: 'requestFormSpecialInstructions' name: 'special_instructions' maxRows: 3 } # hidden fields for flowing data { xtype: 'hiddenfield' name: 'lat' } { xtype: 'hiddenfield' name: 'lng' } { xtype: 'hiddenfield' name: 'address_street' } { xtype: 'hiddenfield' name: 'address_zip' } { xtype: 'container' id: 'sendRequestButtonContainer' flex: 0 height: 110 width: '100%' padding: '0 0 5 0' layout: type: 'vbox' pack: 'center' align: 'center' items: [ { xtype: 'button' ctype: 'sendRequestButton' ui: 'action' cls: 'button-pop' text: 'Review Order' disabled: yes flex: 0 handler: -> @up().up().up().fireEvent 'sendRequest' } ] } ] } { xtype: 'spacer' flex: 1 } ]
28935
Ext.define 'Purple.view.RequestForm', extend: 'Ext.form.Panel' xtype: 'requestform' requires: [ 'Ext.form.*' 'Ext.field.*' 'Ext.Button' ] config: layout: type: 'hbox' pack: 'start' align: 'start' height: '100%' submitOnAction: no cls: [ 'request-form' 'accent-bg' 'slideable' ] scrollable: direction: 'vertical' directionLock: yes translatable: translationMethod: 'auto' items: [ { xtype: 'spacer' flex: 1 } { xtype: 'container' flex: 0 width: '85%' layout: type: 'vbox' pack: 'start' align: 'start' items: [ { xtype: 'component' flex: 0 cls: 'heading' html: 'Request Gas' } { xtype: 'component' flex: 0 cls: [ 'horizontal-rule' 'purple-rule' ] } { xtype: 'selectfield' ctype: 'requestFormVehicleSelect' flex: 0 name: 'vehicle' label: 'Vehicle' labelWidth: 87 listPicker: title: 'Select a Vehicle' cls: [ 'click-to-edit' 'bottom-margin' ] options: [ ] } { xtype: 'selectfield' ctype: 'requestFormGallonsSelect' flex: 0 name: 'gallons' label: 'Gallons' labelWidth: 100 listPicker: title: 'Number of Gallons' cls: [ 'click-to-edit' 'bottom-margin' 'visibly-disabled' ] disabled: yes options: [ ] } { xtype: 'selectfield' ctype: 'requestFormTimeSelect' flex: 0 name: 'time' label: 'Time' listPicker: title: 'Select a Time' cls: [ 'click-to-edit' 'bottom-margin' 'visibly-disabled' ] disabled: yes options: [ ] } { xtype: 'checkboxfield' ctype: 'requestFormTirePressureCheck' flex: 0 name: 'tire_pressure_check' label: 'Tire Fill-up?' # also change in requestFormVehicleSelectChange func labelWidth: 200 cls: [ 'bottom-margin' ] } { xtype: 'hiddenfield' ctype: 'requestFormTirePressureCheckPrice' name: 'tire_pressure_check_price' } # { # xtype: 'component' # flex: 0 # cls: 'horizontal-rule' # } # { # xtype: 'component' # flex: 0 # html: '<NAME>' # cls: 'field-label-text' # } # { # xtype: 'sliderfield' # id: '<NAME>allons' # flex: 0 # width: '100%' # padding: 0 # margin: 0 # minValue: 5 # maxValue: 15 # increment: 5 # listeners: # drag: (field, ignore, ignore2, newValue) -> # #@adjustBrightness newValue # true # change: (field, ignore, ignore2, newValue) -> # #@adjustBrightness newValue # true # } # { # xtype: 'component' # flex: 0 # width: '100%' # html: """ # <div class="tick-label-container"> # <div class="tick-label" style="margin-left: 0px;">5</div> # <div class="tick-label" style="left: 50%;">10</div> # <div class="tick-label" style="right: 0px;">15</div> # </div> # """ # } { xtype: 'component' flex: 0 cls: 'horizontal-rule' } { xtype: 'component' flex: 0 html: 'Special Instructions' cls: 'field-label-text' } { xtype: 'textareafield' ctype: 'requestFormSpecialInstructions' name: 'special_instructions' maxRows: 3 } # hidden fields for flowing data { xtype: 'hiddenfield' name: 'lat' } { xtype: 'hiddenfield' name: 'lng' } { xtype: 'hiddenfield' name: 'address_street' } { xtype: 'hiddenfield' name: 'address_zip' } { xtype: 'container' id: 'sendRequestButtonContainer' flex: 0 height: 110 width: '100%' padding: '0 0 5 0' layout: type: 'vbox' pack: 'center' align: 'center' items: [ { xtype: 'button' ctype: 'sendRequestButton' ui: 'action' cls: 'button-pop' text: 'Review Order' disabled: yes flex: 0 handler: -> @up().up().up().fireEvent 'sendRequest' } ] } ] } { xtype: 'spacer' flex: 1 } ]
true
Ext.define 'Purple.view.RequestForm', extend: 'Ext.form.Panel' xtype: 'requestform' requires: [ 'Ext.form.*' 'Ext.field.*' 'Ext.Button' ] config: layout: type: 'hbox' pack: 'start' align: 'start' height: '100%' submitOnAction: no cls: [ 'request-form' 'accent-bg' 'slideable' ] scrollable: direction: 'vertical' directionLock: yes translatable: translationMethod: 'auto' items: [ { xtype: 'spacer' flex: 1 } { xtype: 'container' flex: 0 width: '85%' layout: type: 'vbox' pack: 'start' align: 'start' items: [ { xtype: 'component' flex: 0 cls: 'heading' html: 'Request Gas' } { xtype: 'component' flex: 0 cls: [ 'horizontal-rule' 'purple-rule' ] } { xtype: 'selectfield' ctype: 'requestFormVehicleSelect' flex: 0 name: 'vehicle' label: 'Vehicle' labelWidth: 87 listPicker: title: 'Select a Vehicle' cls: [ 'click-to-edit' 'bottom-margin' ] options: [ ] } { xtype: 'selectfield' ctype: 'requestFormGallonsSelect' flex: 0 name: 'gallons' label: 'Gallons' labelWidth: 100 listPicker: title: 'Number of Gallons' cls: [ 'click-to-edit' 'bottom-margin' 'visibly-disabled' ] disabled: yes options: [ ] } { xtype: 'selectfield' ctype: 'requestFormTimeSelect' flex: 0 name: 'time' label: 'Time' listPicker: title: 'Select a Time' cls: [ 'click-to-edit' 'bottom-margin' 'visibly-disabled' ] disabled: yes options: [ ] } { xtype: 'checkboxfield' ctype: 'requestFormTirePressureCheck' flex: 0 name: 'tire_pressure_check' label: 'Tire Fill-up?' # also change in requestFormVehicleSelectChange func labelWidth: 200 cls: [ 'bottom-margin' ] } { xtype: 'hiddenfield' ctype: 'requestFormTirePressureCheckPrice' name: 'tire_pressure_check_price' } # { # xtype: 'component' # flex: 0 # cls: 'horizontal-rule' # } # { # xtype: 'component' # flex: 0 # html: 'PI:NAME:<NAME>END_PI' # cls: 'field-label-text' # } # { # xtype: 'sliderfield' # id: 'PI:NAME:<NAME>END_PIallons' # flex: 0 # width: '100%' # padding: 0 # margin: 0 # minValue: 5 # maxValue: 15 # increment: 5 # listeners: # drag: (field, ignore, ignore2, newValue) -> # #@adjustBrightness newValue # true # change: (field, ignore, ignore2, newValue) -> # #@adjustBrightness newValue # true # } # { # xtype: 'component' # flex: 0 # width: '100%' # html: """ # <div class="tick-label-container"> # <div class="tick-label" style="margin-left: 0px;">5</div> # <div class="tick-label" style="left: 50%;">10</div> # <div class="tick-label" style="right: 0px;">15</div> # </div> # """ # } { xtype: 'component' flex: 0 cls: 'horizontal-rule' } { xtype: 'component' flex: 0 html: 'Special Instructions' cls: 'field-label-text' } { xtype: 'textareafield' ctype: 'requestFormSpecialInstructions' name: 'special_instructions' maxRows: 3 } # hidden fields for flowing data { xtype: 'hiddenfield' name: 'lat' } { xtype: 'hiddenfield' name: 'lng' } { xtype: 'hiddenfield' name: 'address_street' } { xtype: 'hiddenfield' name: 'address_zip' } { xtype: 'container' id: 'sendRequestButtonContainer' flex: 0 height: 110 width: '100%' padding: '0 0 5 0' layout: type: 'vbox' pack: 'center' align: 'center' items: [ { xtype: 'button' ctype: 'sendRequestButton' ui: 'action' cls: 'button-pop' text: 'Review Order' disabled: yes flex: 0 handler: -> @up().up().up().fireEvent 'sendRequest' } ] } ] } { xtype: 'spacer' flex: 1 } ]
[ { "context": ": \"Pagina's\"\n \"posts\": \"Posts\"\n \"authors\": \"Auteurs\"\n \"search\": \"Zoeken\"\n \"bookmarks\": \"bladwij", "end": 418, "score": 0.9978580474853516, "start": 411, "tag": "NAME", "value": "Auteurs" }, { "context": " \"shared\": \"Gedeeld!\"\n\"a...
lib/translations/nl.cson
mysticmetal/wordpress-hybrid-client
1
"pullToRefresh": "Omlaag om te herladen!" "retry": "Opnieuw" "back": "Terug" "error": "Er ging iets mis, probeer het opnieuw." "attemptToConnect": "Poging {{attempt}} van {{attemptMax}}. Om te laden" "yes": "Ja" "no" : "Nee" "emptyList" : "Er is niks hier!" "enabled": "Ingeschakeld" "menu": "title": "Menu" "home": "Home" "tags": "Tags" "pages": "Pagina's" "posts": "Posts" "authors": "Auteurs" "search": "Zoeken" "bookmarks": "bladwijzers" "socialNetworks": "Sociale netwerken" "categories": "Categorieën" "settings": "Instellingen" "customPosts": "Eigen posts" "customTaxonomy": "Eigen taxanomie" "pushNotifications": "newContent": "title": "Nieuwe inhoud!" "text": "Een nieuwe post/pagina: '{{postTitle}}' is nu op {{appTitle}}, wil je het bekijken?" "bookmark": "title": "Bladwijzers" "emptyList" : "Nog geen bladwijzers!" "bookmarked" : "Toegevoegd!" "removed" : "Bladwijzer verwijderd!" "tags": "title": "Tags" "tag": "title": "Tag: {{name}}" "customTaxonomy": "title": "{{term}}: {{name}}" "categories": "title": "Categorieën" "category": "title": "Categorie: {{name}}" "home": "title": "Home" "search": "inputPlaceholder": "Zoeken" "title": "Zoek" "titleQuery": "Resultaten voor: {{query}}" "sharing": "shared": "Gedeeld!" "authors": "title": "Auteurs" "author": "title": "Auteur: {{name}}" "pages": "title": "Pagina's" "posts": "title": "Posts" "featured": "Uitgelicht" "post": "comments": "Reactie's" "openInBrowser": "Open in browser" "about": "title": "Over" "params": "title": "Instellingen" "offlineMode": "Offline mode (binnenkort)" "fontSize": "Post lettertype grootte" "language": "Taal" "pushNotifications": "Push meldingen" "languages": "en": "Engels" "fr": "Frans" "zh": "Chinees" "es": "Spaans" "pl": "Pools" "de": "Duits" "pt": "Portugees" "it": "Italiaans" "nl": "Nederlands" "ru": "Russisch" "tr": "Turks" "fontSize": "small": "Klein" "medium": "Normaal" "large": "Groot" "x-large": "X-Groot" "xx-large": "XX-Groot"
65789
"pullToRefresh": "Omlaag om te herladen!" "retry": "Opnieuw" "back": "Terug" "error": "Er ging iets mis, probeer het opnieuw." "attemptToConnect": "Poging {{attempt}} van {{attemptMax}}. Om te laden" "yes": "Ja" "no" : "Nee" "emptyList" : "Er is niks hier!" "enabled": "Ingeschakeld" "menu": "title": "Menu" "home": "Home" "tags": "Tags" "pages": "Pagina's" "posts": "Posts" "authors": "<NAME>" "search": "Zoeken" "bookmarks": "bladwijzers" "socialNetworks": "Sociale netwerken" "categories": "Categorieën" "settings": "Instellingen" "customPosts": "Eigen posts" "customTaxonomy": "Eigen taxanomie" "pushNotifications": "newContent": "title": "Nieuwe inhoud!" "text": "Een nieuwe post/pagina: '{{postTitle}}' is nu op {{appTitle}}, wil je het bekijken?" "bookmark": "title": "Bladwijzers" "emptyList" : "Nog geen bladwijzers!" "bookmarked" : "Toegevoegd!" "removed" : "Bladwijzer verwijderd!" "tags": "title": "Tags" "tag": "title": "Tag: {{name}}" "customTaxonomy": "title": "{{term}}: {{name}}" "categories": "title": "Categorieën" "category": "title": "Categorie: {{name}}" "home": "title": "Home" "search": "inputPlaceholder": "Zoeken" "title": "Zoek" "titleQuery": "Resultaten voor: {{query}}" "sharing": "shared": "Gedeeld!" "authors": "title": "<NAME>" "author": "title": "Auteur: {{name}}" "pages": "title": "Pagina's" "posts": "title": "Posts" "featured": "Uitgelicht" "post": "comments": "Reactie's" "openInBrowser": "Open in browser" "about": "title": "Over" "params": "title": "Instellingen" "offlineMode": "Offline mode (binnenkort)" "fontSize": "Post lettertype grootte" "language": "Taal" "pushNotifications": "Push meldingen" "languages": "en": "Engels" "fr": "Frans" "zh": "Chinees" "es": "Spaans" "pl": "Pools" "de": "Duits" "pt": "Portugees" "it": "Italiaans" "nl": "Nederlands" "ru": "Russisch" "tr": "Turks" "fontSize": "small": "Klein" "medium": "Normaal" "large": "Groot" "x-large": "X-Groot" "xx-large": "XX-Groot"
true
"pullToRefresh": "Omlaag om te herladen!" "retry": "Opnieuw" "back": "Terug" "error": "Er ging iets mis, probeer het opnieuw." "attemptToConnect": "Poging {{attempt}} van {{attemptMax}}. Om te laden" "yes": "Ja" "no" : "Nee" "emptyList" : "Er is niks hier!" "enabled": "Ingeschakeld" "menu": "title": "Menu" "home": "Home" "tags": "Tags" "pages": "Pagina's" "posts": "Posts" "authors": "PI:NAME:<NAME>END_PI" "search": "Zoeken" "bookmarks": "bladwijzers" "socialNetworks": "Sociale netwerken" "categories": "Categorieën" "settings": "Instellingen" "customPosts": "Eigen posts" "customTaxonomy": "Eigen taxanomie" "pushNotifications": "newContent": "title": "Nieuwe inhoud!" "text": "Een nieuwe post/pagina: '{{postTitle}}' is nu op {{appTitle}}, wil je het bekijken?" "bookmark": "title": "Bladwijzers" "emptyList" : "Nog geen bladwijzers!" "bookmarked" : "Toegevoegd!" "removed" : "Bladwijzer verwijderd!" "tags": "title": "Tags" "tag": "title": "Tag: {{name}}" "customTaxonomy": "title": "{{term}}: {{name}}" "categories": "title": "Categorieën" "category": "title": "Categorie: {{name}}" "home": "title": "Home" "search": "inputPlaceholder": "Zoeken" "title": "Zoek" "titleQuery": "Resultaten voor: {{query}}" "sharing": "shared": "Gedeeld!" "authors": "title": "PI:NAME:<NAME>END_PI" "author": "title": "Auteur: {{name}}" "pages": "title": "Pagina's" "posts": "title": "Posts" "featured": "Uitgelicht" "post": "comments": "Reactie's" "openInBrowser": "Open in browser" "about": "title": "Over" "params": "title": "Instellingen" "offlineMode": "Offline mode (binnenkort)" "fontSize": "Post lettertype grootte" "language": "Taal" "pushNotifications": "Push meldingen" "languages": "en": "Engels" "fr": "Frans" "zh": "Chinees" "es": "Spaans" "pl": "Pools" "de": "Duits" "pt": "Portugees" "it": "Italiaans" "nl": "Nederlands" "ru": "Russisch" "tr": "Turks" "fontSize": "small": "Klein" "medium": "Normaal" "large": "Groot" "x-large": "X-Groot" "xx-large": "XX-Groot"
[ { "context": "on.fullName()\", ->\n eq uEx.person.fullName(), 'John Doe'\n\n it \"person.age\", ->\n eq uEx.person.age, 40", "end": 280, "score": 0.9998511075973511, "start": 272, "tag": "NAME", "value": "John Doe" } ]
source/spec/urequire-example-testbed-spec.coffee
anodynos/urequire-example-testbed
0
# 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-testbed' 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 "has some VERSION", -> fals _.isEmpty uEx.VERSION it "has the correct homeHTML", -> eq uEx.homeHTML, '<html><body><div id="Hello,">Universe!</div><ul><li>Leonardo</li><li>Da Vinci</li></ul></body></html>'
115789
# 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-testbed' 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 "has some VERSION", -> fals _.isEmpty uEx.VERSION it "has the correct homeHTML", -> eq uEx.homeHTML, '<html><body><div id="Hello,">Universe!</div><ul><li>Leonardo</li><li>Da Vinci</li></ul></body></html>'
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-testbed' 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 "has some VERSION", -> fals _.isEmpty uEx.VERSION it "has the correct homeHTML", -> eq uEx.homeHTML, '<html><body><div id="Hello,">Universe!</div><ul><li>Leonardo</li><li>Da Vinci</li></ul></body></html>'
[ { "context": "0c6902213a3e1960cd9d3b\"\n personalAccessToken: \"c9ef7b530582ac552172abdfd0a1b97ed2d5715c\"\n \"tool-bar\":\n iconSize: \"16px\"\n position:", "end": 2837, "score": 0.9784346222877502, "start": 2797, "tag": "KEY", "value": "c9ef7b530582ac552172abdfd0a1b97ed2d5715c" ...
snowblocks/nixpkgs/atom/config.cson
eadwu/dotfiles
0
"*": "atom-clock": dateFormat: " [Cour] Q - MMMM Do YYYY, dddd, h:mm A" showClockIcon: true "atom-ide-ui": "atom-ide-diagnostics-ui": showDirectoryColumn: true hyperclick: darwinTriggerKeys: "ctrlKey,altKey,metaKey" linuxTriggerKeys: "altKey,metaKey" win32TriggerKeys: "altKey,metaKey" use: {} "atom-package-deps": ignored: [ "linter-clang" "linter-eslint" ] "autocomplete-plus": backspaceTriggersAutocomplete: true confirmCompletion: "tab always, enter when suggestion explicitly selected" minimumWordLength: 1 suggestionListFollows: "Cursor" core: autoHideMenuBar: true closeDeletedFileTabs: true disabledPackages: [ "atom-ternjs" "linter-glsl" "linter-clang" "linter-xmllint" "linter-jsonlint" "linter-stylelint" "linter-moonscript" "linter-eslint" ] telemetryConsent: "limited" themes: [ "bliss-ui" "nord-atom-syntax" ] useTreeSitterParsers: true docblockr: lower_case_primitives: true editor: fontFamily: "IBM Plex Mono, Anonymous Pro" fontSize: 12 showInvisibles: true "exception-reporting": userId: "eb41a2a6-f07d-424b-b5c0-352fd0f466a5" filesize: UseDecimal: true "git-diff": showIconsInEditorGutter: true "git-plus": general: splitPane: "Right" tags: signTags: true "ide-flowtype": autoDownloadFlowBinaries: false customFlowPath: enabled: true flowPath: "/usr/bin/flow" "ide-java": javaHome: "/usr/lib/jvm/java-9-openjdk" "ide-typescript": javascriptSupport: false latex: engine: "xelatex" moveResultToSourceDirectory: false opener: "pdf-view" outputDirectory: ".." "linter-eslint": globalNodePath: "/usr" lintHtmlFiles: true scopes: [ "source.js" "source.jsx" "source.js.jsx" "source.babel" "source.js-semantic" "text.html.basic" ] "linter-stylelint": disableWhenNoConfig: false useStandard: true "markdown-preview": useGitHubStyle: true minimap: plugins: "git-diff": true "git-diffDecorationsZIndex": 0 "highlight-selected": true "highlight-selectedDecorationsZIndex": 0 "package-status": packageList: [ "atom-ternjs" "linter-glsl" "linter-clang" "linter-eslint" "linter-xmllint" "linter-jsonlint" "linter-stylelint" "linter-moonscript" ] "pdf-view": paneToUseInSynctex: "right" syncTeXPath: "/usr/bin/synctex" "sync-settings": _lastBackupHash: "b1cb6a97302a7e6655430c7a6c147ea18d79d1b3" gistDescription: "Atom configuration for Arch Linux" gistId: "3cf21fa5a80c6902213a3e1960cd9d3b" personalAccessToken: "c9ef7b530582ac552172abdfd0a1b97ed2d5715c" "tool-bar": iconSize: "16px" position: "Left" welcome: showOnStartup: false
87365
"*": "atom-clock": dateFormat: " [Cour] Q - MMMM Do YYYY, dddd, h:mm A" showClockIcon: true "atom-ide-ui": "atom-ide-diagnostics-ui": showDirectoryColumn: true hyperclick: darwinTriggerKeys: "ctrlKey,altKey,metaKey" linuxTriggerKeys: "altKey,metaKey" win32TriggerKeys: "altKey,metaKey" use: {} "atom-package-deps": ignored: [ "linter-clang" "linter-eslint" ] "autocomplete-plus": backspaceTriggersAutocomplete: true confirmCompletion: "tab always, enter when suggestion explicitly selected" minimumWordLength: 1 suggestionListFollows: "Cursor" core: autoHideMenuBar: true closeDeletedFileTabs: true disabledPackages: [ "atom-ternjs" "linter-glsl" "linter-clang" "linter-xmllint" "linter-jsonlint" "linter-stylelint" "linter-moonscript" "linter-eslint" ] telemetryConsent: "limited" themes: [ "bliss-ui" "nord-atom-syntax" ] useTreeSitterParsers: true docblockr: lower_case_primitives: true editor: fontFamily: "IBM Plex Mono, Anonymous Pro" fontSize: 12 showInvisibles: true "exception-reporting": userId: "eb41a2a6-f07d-424b-b5c0-352fd0f466a5" filesize: UseDecimal: true "git-diff": showIconsInEditorGutter: true "git-plus": general: splitPane: "Right" tags: signTags: true "ide-flowtype": autoDownloadFlowBinaries: false customFlowPath: enabled: true flowPath: "/usr/bin/flow" "ide-java": javaHome: "/usr/lib/jvm/java-9-openjdk" "ide-typescript": javascriptSupport: false latex: engine: "xelatex" moveResultToSourceDirectory: false opener: "pdf-view" outputDirectory: ".." "linter-eslint": globalNodePath: "/usr" lintHtmlFiles: true scopes: [ "source.js" "source.jsx" "source.js.jsx" "source.babel" "source.js-semantic" "text.html.basic" ] "linter-stylelint": disableWhenNoConfig: false useStandard: true "markdown-preview": useGitHubStyle: true minimap: plugins: "git-diff": true "git-diffDecorationsZIndex": 0 "highlight-selected": true "highlight-selectedDecorationsZIndex": 0 "package-status": packageList: [ "atom-ternjs" "linter-glsl" "linter-clang" "linter-eslint" "linter-xmllint" "linter-jsonlint" "linter-stylelint" "linter-moonscript" ] "pdf-view": paneToUseInSynctex: "right" syncTeXPath: "/usr/bin/synctex" "sync-settings": _lastBackupHash: "b1cb6a97302a7e6655430c7a6c147ea18d79d1b3" gistDescription: "Atom configuration for Arch Linux" gistId: "3cf21fa5a80c6902213a3e1960cd9d3b" personalAccessToken: "<KEY>" "tool-bar": iconSize: "16px" position: "Left" welcome: showOnStartup: false
true
"*": "atom-clock": dateFormat: " [Cour] Q - MMMM Do YYYY, dddd, h:mm A" showClockIcon: true "atom-ide-ui": "atom-ide-diagnostics-ui": showDirectoryColumn: true hyperclick: darwinTriggerKeys: "ctrlKey,altKey,metaKey" linuxTriggerKeys: "altKey,metaKey" win32TriggerKeys: "altKey,metaKey" use: {} "atom-package-deps": ignored: [ "linter-clang" "linter-eslint" ] "autocomplete-plus": backspaceTriggersAutocomplete: true confirmCompletion: "tab always, enter when suggestion explicitly selected" minimumWordLength: 1 suggestionListFollows: "Cursor" core: autoHideMenuBar: true closeDeletedFileTabs: true disabledPackages: [ "atom-ternjs" "linter-glsl" "linter-clang" "linter-xmllint" "linter-jsonlint" "linter-stylelint" "linter-moonscript" "linter-eslint" ] telemetryConsent: "limited" themes: [ "bliss-ui" "nord-atom-syntax" ] useTreeSitterParsers: true docblockr: lower_case_primitives: true editor: fontFamily: "IBM Plex Mono, Anonymous Pro" fontSize: 12 showInvisibles: true "exception-reporting": userId: "eb41a2a6-f07d-424b-b5c0-352fd0f466a5" filesize: UseDecimal: true "git-diff": showIconsInEditorGutter: true "git-plus": general: splitPane: "Right" tags: signTags: true "ide-flowtype": autoDownloadFlowBinaries: false customFlowPath: enabled: true flowPath: "/usr/bin/flow" "ide-java": javaHome: "/usr/lib/jvm/java-9-openjdk" "ide-typescript": javascriptSupport: false latex: engine: "xelatex" moveResultToSourceDirectory: false opener: "pdf-view" outputDirectory: ".." "linter-eslint": globalNodePath: "/usr" lintHtmlFiles: true scopes: [ "source.js" "source.jsx" "source.js.jsx" "source.babel" "source.js-semantic" "text.html.basic" ] "linter-stylelint": disableWhenNoConfig: false useStandard: true "markdown-preview": useGitHubStyle: true minimap: plugins: "git-diff": true "git-diffDecorationsZIndex": 0 "highlight-selected": true "highlight-selectedDecorationsZIndex": 0 "package-status": packageList: [ "atom-ternjs" "linter-glsl" "linter-clang" "linter-eslint" "linter-xmllint" "linter-jsonlint" "linter-stylelint" "linter-moonscript" ] "pdf-view": paneToUseInSynctex: "right" syncTeXPath: "/usr/bin/synctex" "sync-settings": _lastBackupHash: "b1cb6a97302a7e6655430c7a6c147ea18d79d1b3" gistDescription: "Atom configuration for Arch Linux" gistId: "3cf21fa5a80c6902213a3e1960cd9d3b" personalAccessToken: "PI:KEY:<KEY>END_PI" "tool-bar": iconSize: "16px" position: "Left" welcome: showOnStartup: false
[ { "context": "xtends LayerInfo\n @shouldParse: (key) -> key is 'luni'\n\n parse: ->\n pos = @file.tell()\n @data = ", "end": 134, "score": 0.8709827661514282, "start": 130, "tag": "KEY", "value": "luni" } ]
lib/psd/layer_info/unicode_name.coffee
LoginovIlya/psd.js
2,218
LayerInfo = require '../layer_info.coffee' module.exports = class UnicodeName extends LayerInfo @shouldParse: (key) -> key is 'luni' parse: -> pos = @file.tell() @data = @file.readUnicodeString() @file.seek pos + @length return @
175884
LayerInfo = require '../layer_info.coffee' module.exports = class UnicodeName extends LayerInfo @shouldParse: (key) -> key is '<KEY>' parse: -> pos = @file.tell() @data = @file.readUnicodeString() @file.seek pos + @length return @
true
LayerInfo = require '../layer_info.coffee' module.exports = class UnicodeName extends LayerInfo @shouldParse: (key) -> key is 'PI:KEY:<KEY>END_PI' parse: -> pos = @file.tell() @data = @file.readUnicodeString() @file.seek pos + @length return @
[ { "context": "ner\n\nThe MIT License (MIT)\nCopyright (c) 2014-2016 GochoMugo <mugo@forfuture.co.ke>\n###\n\n\nexports = module.exp", "end": 94, "score": 0.9330428838729858, "start": 85, "tag": "USERNAME", "value": "GochoMugo" }, { "context": " License (MIT)\nCopyright (c) 2014-2016 ...
Gruntfile.coffee
guyaumetremblay/json-concat
5
### Run script for Grunt, task runner The MIT License (MIT) Copyright (c) 2014-2016 GochoMugo <mugo@forfuture.co.ke> ### exports = module.exports = (grunt) -> "use strict" grunt.initConfig clean: test: [".test/", "concat.json"] coffee: src: expand: true, flatten: false, ext: ".js" extDot: "last", cwd: "src/", src: ["**/*.coffee"], dest: "lib/" test: expand: true, flatten: false, ext: ".js" extDot: "last", cwd: "test/", src: ["**/*.coffee"], dest: ".test/" copy: test: expand: true, cwd: "test/", src: ["data/**/*", "!data/**/*.coffee"], dest: ".test/" mochaTest: test: options: reporter: 'spec', quiet: false, clearRequireCache: false src: ['.test/test.*.js'] grunt.loadNpmTasks("grunt-contrib-clean") grunt.loadNpmTasks("grunt-contrib-coffee") grunt.loadNpmTasks("grunt-contrib-copy") grunt.loadNpmTasks("grunt-mocha-test") grunt.registerTask("default", ["coffee:src"]) grunt.registerTask("test", ["default", "coffee:test", "copy:test", "mochaTest"])
81435
### Run script for Grunt, task runner The MIT License (MIT) Copyright (c) 2014-2016 GochoMugo <<EMAIL>> ### exports = module.exports = (grunt) -> "use strict" grunt.initConfig clean: test: [".test/", "concat.json"] coffee: src: expand: true, flatten: false, ext: ".js" extDot: "last", cwd: "src/", src: ["**/*.coffee"], dest: "lib/" test: expand: true, flatten: false, ext: ".js" extDot: "last", cwd: "test/", src: ["**/*.coffee"], dest: ".test/" copy: test: expand: true, cwd: "test/", src: ["data/**/*", "!data/**/*.coffee"], dest: ".test/" mochaTest: test: options: reporter: 'spec', quiet: false, clearRequireCache: false src: ['.test/test.*.js'] grunt.loadNpmTasks("grunt-contrib-clean") grunt.loadNpmTasks("grunt-contrib-coffee") grunt.loadNpmTasks("grunt-contrib-copy") grunt.loadNpmTasks("grunt-mocha-test") grunt.registerTask("default", ["coffee:src"]) grunt.registerTask("test", ["default", "coffee:test", "copy:test", "mochaTest"])
true
### Run script for Grunt, task runner The MIT License (MIT) Copyright (c) 2014-2016 GochoMugo <PI:EMAIL:<EMAIL>END_PI> ### exports = module.exports = (grunt) -> "use strict" grunt.initConfig clean: test: [".test/", "concat.json"] coffee: src: expand: true, flatten: false, ext: ".js" extDot: "last", cwd: "src/", src: ["**/*.coffee"], dest: "lib/" test: expand: true, flatten: false, ext: ".js" extDot: "last", cwd: "test/", src: ["**/*.coffee"], dest: ".test/" copy: test: expand: true, cwd: "test/", src: ["data/**/*", "!data/**/*.coffee"], dest: ".test/" mochaTest: test: options: reporter: 'spec', quiet: false, clearRequireCache: false src: ['.test/test.*.js'] grunt.loadNpmTasks("grunt-contrib-clean") grunt.loadNpmTasks("grunt-contrib-coffee") grunt.loadNpmTasks("grunt-contrib-copy") grunt.loadNpmTasks("grunt-mocha-test") grunt.registerTask("default", ["coffee:src"]) grunt.registerTask("test", ["default", "coffee:test", "copy:test", "mochaTest"])
[ { "context": " rawData: JSON.stringify {subscriberUuid:'superman', emitterUuid: 'spiderman', type:'broadcast'}\n\n ", "end": 796, "score": 0.7882051467895508, "start": 788, "tag": "USERNAME", "value": "superman" }, { "context": "ringify {subscriberUuid:'superman', emitterUui...
test/create-subscription-spec.coffee
octoblu/meshblu-core-task-create-subscription
1
_ = require 'lodash' mongojs = require 'mongojs' Datastore = require 'meshblu-core-datastore' CreateSubscription = require '../' describe 'CreateSubscription', -> beforeEach (done) -> db = mongojs 'subscription-manager-test', ['subscriptions'] @datastore = new Datastore database: db collection: 'subscriptions' db.subscriptions.remove done beforeEach -> @uuidAliasResolver = resolve: (uuid, callback) => callback(null, uuid) @sut = new CreateSubscription {@datastore, @uuidAliasResolver} describe '->do', -> context 'when given a valid request', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' rawData: JSON.stringify {subscriberUuid:'superman', emitterUuid: 'spiderman', type:'broadcast'} @sut.do request, (error, @response) => done error it 'should still have one subscription', (done) -> @datastore.find {subscriberUuid: 'superman', emitterUuid: 'spiderman', type: 'broadcast'}, (error, subscriptions) => return done error if error? expect(subscriptions).to.deep.equal [ {subscriberUuid: 'superman', emitterUuid: 'spiderman', type: 'broadcast'} ] done() it 'should return a 201', -> expectedResponse = metadata: responseId: 'its-electric' code: 201 status: 'Created' expect(@response).to.deep.equal expectedResponse context 'when given a invalid request', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' rawData: JSON.stringify {emitterUuid: 'spiderman', type:'broadcast'} @sut.do request, (error, @response) => done error it 'should not have a subscription', (done) -> @datastore.find {subscriberUuid: 'superman', emitterUuid: 'spiderman', type: 'broadcast'}, (error, subscriptions) => return done error if error? expect(subscriptions).to.deep.equal [] done() it 'should return a 422', -> expectedResponse = metadata: responseId: 'its-electric' code: 422 status: 'Unprocessable Entity' expect(@response).to.deep.equal expectedResponse
106185
_ = require 'lodash' mongojs = require 'mongojs' Datastore = require 'meshblu-core-datastore' CreateSubscription = require '../' describe 'CreateSubscription', -> beforeEach (done) -> db = mongojs 'subscription-manager-test', ['subscriptions'] @datastore = new Datastore database: db collection: 'subscriptions' db.subscriptions.remove done beforeEach -> @uuidAliasResolver = resolve: (uuid, callback) => callback(null, uuid) @sut = new CreateSubscription {@datastore, @uuidAliasResolver} describe '->do', -> context 'when given a valid request', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' rawData: JSON.stringify {subscriberUuid:'superman', emitterUuid: '<NAME>', type:'broadcast'} @sut.do request, (error, @response) => done error it 'should still have one subscription', (done) -> @datastore.find {subscriberUuid: 'superman', emitterUuid: 'spiderman', type: 'broadcast'}, (error, subscriptions) => return done error if error? expect(subscriptions).to.deep.equal [ {subscriberUuid: '<NAME>man', emitterUuid: '<NAME>', type: 'broadcast'} ] done() it 'should return a 201', -> expectedResponse = metadata: responseId: 'its-electric' code: 201 status: 'Created' expect(@response).to.deep.equal expectedResponse context 'when given a invalid request', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' rawData: JSON.stringify {emitterUuid: '<NAME>man', type:'broadcast'} @sut.do request, (error, @response) => done error it 'should not have a subscription', (done) -> @datastore.find {subscriberUuid: 'superman', emitterUuid: 'spiderman', type: 'broadcast'}, (error, subscriptions) => return done error if error? expect(subscriptions).to.deep.equal [] done() it 'should return a 422', -> expectedResponse = metadata: responseId: 'its-electric' code: 422 status: 'Unprocessable Entity' expect(@response).to.deep.equal expectedResponse
true
_ = require 'lodash' mongojs = require 'mongojs' Datastore = require 'meshblu-core-datastore' CreateSubscription = require '../' describe 'CreateSubscription', -> beforeEach (done) -> db = mongojs 'subscription-manager-test', ['subscriptions'] @datastore = new Datastore database: db collection: 'subscriptions' db.subscriptions.remove done beforeEach -> @uuidAliasResolver = resolve: (uuid, callback) => callback(null, uuid) @sut = new CreateSubscription {@datastore, @uuidAliasResolver} describe '->do', -> context 'when given a valid request', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' rawData: JSON.stringify {subscriberUuid:'superman', emitterUuid: 'PI:NAME:<NAME>END_PI', type:'broadcast'} @sut.do request, (error, @response) => done error it 'should still have one subscription', (done) -> @datastore.find {subscriberUuid: 'superman', emitterUuid: 'spiderman', type: 'broadcast'}, (error, subscriptions) => return done error if error? expect(subscriptions).to.deep.equal [ {subscriberUuid: 'PI:NAME:<NAME>END_PIman', emitterUuid: 'PI:NAME:<NAME>END_PI', type: 'broadcast'} ] done() it 'should return a 201', -> expectedResponse = metadata: responseId: 'its-electric' code: 201 status: 'Created' expect(@response).to.deep.equal expectedResponse context 'when given a invalid request', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' rawData: JSON.stringify {emitterUuid: 'PI:NAME:<NAME>END_PIman', type:'broadcast'} @sut.do request, (error, @response) => done error it 'should not have a subscription', (done) -> @datastore.find {subscriberUuid: 'superman', emitterUuid: 'spiderman', type: 'broadcast'}, (error, subscriptions) => return done error if error? expect(subscriptions).to.deep.equal [] done() it 'should return a 422', -> expectedResponse = metadata: responseId: 'its-electric' code: 422 status: 'Unprocessable Entity' expect(@response).to.deep.equal expectedResponse
[ { "context": "###\nCopyright (c) 2002-2013 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n", "end": 43, "score": 0.5203896164894104, "start": 33, "tag": "NAME", "value": "Technology" } ]
community/server/src/main/coffeescript/neo4j/webadmin/modules/indexmanager/views/IndexView.coffee
rebaze/neo4j
1
### Copyright (c) 2002-2013 "Neo Technology," Network Engine for Objects in Lund AB [http://neotechnology.com] This file is part of Neo4j. Neo4j is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ### define( ['./index' 'ribcage/View' 'lib/amd/jQuery'], (template, View, $) -> class IndexView extends View NODE_INDEX_TYPE : "nodeidx" REL_INDEX_TYPE : "relidx" template : template tagName : "tr" events : "click .delete-index" : "deleteIndex" initialize : (opts) => @index = opts.index @idxMgr = opts.idxMgr @type = opts.type render : => $(@el).html(template(index : @index)) return this deleteIndex : => if confirm "Are you sure?" if @type is @NODE_INDEX_TYPE @idxMgr.deleteNodeIndex({name : @index.name}) else @idxMgr.deleteRelationshipIndex({name : @index.name}) )
218105
### Copyright (c) 2002-2013 "Neo <NAME>," Network Engine for Objects in Lund AB [http://neotechnology.com] This file is part of Neo4j. Neo4j is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ### define( ['./index' 'ribcage/View' 'lib/amd/jQuery'], (template, View, $) -> class IndexView extends View NODE_INDEX_TYPE : "nodeidx" REL_INDEX_TYPE : "relidx" template : template tagName : "tr" events : "click .delete-index" : "deleteIndex" initialize : (opts) => @index = opts.index @idxMgr = opts.idxMgr @type = opts.type render : => $(@el).html(template(index : @index)) return this deleteIndex : => if confirm "Are you sure?" if @type is @NODE_INDEX_TYPE @idxMgr.deleteNodeIndex({name : @index.name}) else @idxMgr.deleteRelationshipIndex({name : @index.name}) )
true
### Copyright (c) 2002-2013 "Neo PI:NAME:<NAME>END_PI," Network Engine for Objects in Lund AB [http://neotechnology.com] This file is part of Neo4j. Neo4j is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ### define( ['./index' 'ribcage/View' 'lib/amd/jQuery'], (template, View, $) -> class IndexView extends View NODE_INDEX_TYPE : "nodeidx" REL_INDEX_TYPE : "relidx" template : template tagName : "tr" events : "click .delete-index" : "deleteIndex" initialize : (opts) => @index = opts.index @idxMgr = opts.idxMgr @type = opts.type render : => $(@el).html(template(index : @index)) return this deleteIndex : => if confirm "Are you sure?" if @type is @NODE_INDEX_TYPE @idxMgr.deleteNodeIndex({name : @index.name}) else @idxMgr.deleteRelationshipIndex({name : @index.name}) )
[ { "context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\nfoldingTextService = requi", "end": 35, "score": 0.9997062683105469, "start": 21, "tag": "NAME", "value": "Jesse Grosjean" } ]
atom/packages/foldingtext-for-atom/lib/extensions/search-status-bar-item.coffee
prookie/dotfiles-1
0
# Copyright (c) 2015 Jesse Grosjean. All rights reserved. foldingTextService = require '../foldingtext-service' {Disposable, CompositeDisposable} = require 'atom' TextInputElement = require './ui/text-input-element' ItemPathGrammar = require './item-path-grammar' exports.consumeStatusBarService = (statusBar) -> searchElement = document.createElement 'ft-text-input' searchElement.classList.add 'inline-block' searchElement.classList.add 'ft-search-status-bar-item' searchElement.cancelOnBlur = false searchElement.setPlaceholderText 'Search' try # Make sure our grammar tokenizeLine hack is working, if not use null grammar searchElement.setGrammar new ItemPathGrammar(atom.grammars) searchElement.setText('test and this and out') searchElement.setText('') catch searchElement.setGrammar(atom.grammars.grammarForScopeName('text.plain.null-grammar')) clearAddon = document.createElement 'span' clearAddon.className = 'icon-remove-close' clearAddon.addEventListener 'click', (e) -> e.preventDefault() searchElement.cancel() searchElement.focusTextEditor() searchElement.addRightAddonElement clearAddon searchElement.setDelegate didChangeText: -> foldingTextService.getActiveOutlineEditor()?.setSearch searchElement.getText() restoreFocus: -> cancelled: -> editor = foldingTextService.getActiveOutlineEditor() if editor.getSearch()?.query editor?.setSearch '' else editor?.focus() confirm: -> foldingTextService.getActiveOutlineEditor()?.focus() searchStatusBarItem = statusBar.addLeftTile(item: searchElement, priority: 0) searchElement.setSizeToFit true activeOutlineEditorSubscriptions = null activeOutlineEditorSubscription = foldingTextService.observeActiveOutlineEditor (outlineEditor) -> activeOutlineEditorSubscriptions?.dispose() if outlineEditor update = -> searchQuery = outlineEditor.getSearch()?.query if searchQuery searchElement.classList.add 'active' clearAddon.style.display = null else searchElement.classList.remove 'active' clearAddon.style.display = 'none' unless searchElement.getText() is searchQuery searchElement.setText searchQuery searchElement.scheduleLayout() searchElement.style.display = null activeOutlineEditorSubscriptions = new CompositeDisposable() activeOutlineEditorSubscriptions.add outlineEditor.onDidChangeSearch -> update() activeOutlineEditorSubscriptions.add outlineEditor.onDidChangeHoistedItem -> update() update() else searchElement.style.display = 'none' commandsSubscriptions = new CompositeDisposable commandsSubscriptions.add atom.commands.add searchElement, 'editor:copy-path': -> foldingTextService.getActiveOutlineEditor()?.copyPathToClipboard() commandsSubscriptions.add atom.commands.add 'ft-outline-editor.outline-mode', 'core:cancel': (e) -> searchElement.focusTextEditor() e.stopPropagation() commandsSubscriptions.add atom.commands.add 'ft-outline-editor', 'find-and-replace:show': (e) -> searchElement.focusTextEditor() e.stopPropagation() 'find-and-replace:show-replace': (e) -> searchElement.focusTextEditor() e.stopPropagation() new Disposable -> activeOutlineEditorSubscription.dispose() activeOutlineEditorSubscriptions?.dispose() commandsSubscriptions.dispose() searchStatusBarItem.destroy()
226016
# Copyright (c) 2015 <NAME>. All rights reserved. foldingTextService = require '../foldingtext-service' {Disposable, CompositeDisposable} = require 'atom' TextInputElement = require './ui/text-input-element' ItemPathGrammar = require './item-path-grammar' exports.consumeStatusBarService = (statusBar) -> searchElement = document.createElement 'ft-text-input' searchElement.classList.add 'inline-block' searchElement.classList.add 'ft-search-status-bar-item' searchElement.cancelOnBlur = false searchElement.setPlaceholderText 'Search' try # Make sure our grammar tokenizeLine hack is working, if not use null grammar searchElement.setGrammar new ItemPathGrammar(atom.grammars) searchElement.setText('test and this and out') searchElement.setText('') catch searchElement.setGrammar(atom.grammars.grammarForScopeName('text.plain.null-grammar')) clearAddon = document.createElement 'span' clearAddon.className = 'icon-remove-close' clearAddon.addEventListener 'click', (e) -> e.preventDefault() searchElement.cancel() searchElement.focusTextEditor() searchElement.addRightAddonElement clearAddon searchElement.setDelegate didChangeText: -> foldingTextService.getActiveOutlineEditor()?.setSearch searchElement.getText() restoreFocus: -> cancelled: -> editor = foldingTextService.getActiveOutlineEditor() if editor.getSearch()?.query editor?.setSearch '' else editor?.focus() confirm: -> foldingTextService.getActiveOutlineEditor()?.focus() searchStatusBarItem = statusBar.addLeftTile(item: searchElement, priority: 0) searchElement.setSizeToFit true activeOutlineEditorSubscriptions = null activeOutlineEditorSubscription = foldingTextService.observeActiveOutlineEditor (outlineEditor) -> activeOutlineEditorSubscriptions?.dispose() if outlineEditor update = -> searchQuery = outlineEditor.getSearch()?.query if searchQuery searchElement.classList.add 'active' clearAddon.style.display = null else searchElement.classList.remove 'active' clearAddon.style.display = 'none' unless searchElement.getText() is searchQuery searchElement.setText searchQuery searchElement.scheduleLayout() searchElement.style.display = null activeOutlineEditorSubscriptions = new CompositeDisposable() activeOutlineEditorSubscriptions.add outlineEditor.onDidChangeSearch -> update() activeOutlineEditorSubscriptions.add outlineEditor.onDidChangeHoistedItem -> update() update() else searchElement.style.display = 'none' commandsSubscriptions = new CompositeDisposable commandsSubscriptions.add atom.commands.add searchElement, 'editor:copy-path': -> foldingTextService.getActiveOutlineEditor()?.copyPathToClipboard() commandsSubscriptions.add atom.commands.add 'ft-outline-editor.outline-mode', 'core:cancel': (e) -> searchElement.focusTextEditor() e.stopPropagation() commandsSubscriptions.add atom.commands.add 'ft-outline-editor', 'find-and-replace:show': (e) -> searchElement.focusTextEditor() e.stopPropagation() 'find-and-replace:show-replace': (e) -> searchElement.focusTextEditor() e.stopPropagation() new Disposable -> activeOutlineEditorSubscription.dispose() activeOutlineEditorSubscriptions?.dispose() commandsSubscriptions.dispose() searchStatusBarItem.destroy()
true
# Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved. foldingTextService = require '../foldingtext-service' {Disposable, CompositeDisposable} = require 'atom' TextInputElement = require './ui/text-input-element' ItemPathGrammar = require './item-path-grammar' exports.consumeStatusBarService = (statusBar) -> searchElement = document.createElement 'ft-text-input' searchElement.classList.add 'inline-block' searchElement.classList.add 'ft-search-status-bar-item' searchElement.cancelOnBlur = false searchElement.setPlaceholderText 'Search' try # Make sure our grammar tokenizeLine hack is working, if not use null grammar searchElement.setGrammar new ItemPathGrammar(atom.grammars) searchElement.setText('test and this and out') searchElement.setText('') catch searchElement.setGrammar(atom.grammars.grammarForScopeName('text.plain.null-grammar')) clearAddon = document.createElement 'span' clearAddon.className = 'icon-remove-close' clearAddon.addEventListener 'click', (e) -> e.preventDefault() searchElement.cancel() searchElement.focusTextEditor() searchElement.addRightAddonElement clearAddon searchElement.setDelegate didChangeText: -> foldingTextService.getActiveOutlineEditor()?.setSearch searchElement.getText() restoreFocus: -> cancelled: -> editor = foldingTextService.getActiveOutlineEditor() if editor.getSearch()?.query editor?.setSearch '' else editor?.focus() confirm: -> foldingTextService.getActiveOutlineEditor()?.focus() searchStatusBarItem = statusBar.addLeftTile(item: searchElement, priority: 0) searchElement.setSizeToFit true activeOutlineEditorSubscriptions = null activeOutlineEditorSubscription = foldingTextService.observeActiveOutlineEditor (outlineEditor) -> activeOutlineEditorSubscriptions?.dispose() if outlineEditor update = -> searchQuery = outlineEditor.getSearch()?.query if searchQuery searchElement.classList.add 'active' clearAddon.style.display = null else searchElement.classList.remove 'active' clearAddon.style.display = 'none' unless searchElement.getText() is searchQuery searchElement.setText searchQuery searchElement.scheduleLayout() searchElement.style.display = null activeOutlineEditorSubscriptions = new CompositeDisposable() activeOutlineEditorSubscriptions.add outlineEditor.onDidChangeSearch -> update() activeOutlineEditorSubscriptions.add outlineEditor.onDidChangeHoistedItem -> update() update() else searchElement.style.display = 'none' commandsSubscriptions = new CompositeDisposable commandsSubscriptions.add atom.commands.add searchElement, 'editor:copy-path': -> foldingTextService.getActiveOutlineEditor()?.copyPathToClipboard() commandsSubscriptions.add atom.commands.add 'ft-outline-editor.outline-mode', 'core:cancel': (e) -> searchElement.focusTextEditor() e.stopPropagation() commandsSubscriptions.add atom.commands.add 'ft-outline-editor', 'find-and-replace:show': (e) -> searchElement.focusTextEditor() e.stopPropagation() 'find-and-replace:show-replace': (e) -> searchElement.focusTextEditor() e.stopPropagation() new Disposable -> activeOutlineEditorSubscription.dispose() activeOutlineEditorSubscriptions?.dispose() commandsSubscriptions.dispose() searchStatusBarItem.destroy()
[ { "context": "L.mapbox.accessToken = 'pk.eyJ1Ijoia25vY2siLCJhIjoiRVdjRFVjRSJ9.nIZeVnR6dJZ0hwNnKAiAlQ'\n\nmap = L.mapbox.map('map', 'knock.l5dpakki').\n ", "end": 86, "score": 0.9996227622032166, "start": 24, "tag": "KEY", "value": "pk.eyJ1Ijoia25vY2siLCJhIjoiRVdjRFVjRSJ9.nIZeVnR6dJZ0hwNnKAi...
app/scripts/main.coffee
harleyholt/hackhousing.knockX2
1
L.mapbox.accessToken = 'pk.eyJ1Ijoia25vY2siLCJhIjoiRVdjRFVjRSJ9.nIZeVnR6dJZ0hwNnKAiAlQ' map = L.mapbox.map('map', 'knock.l5dpakki'). setView([47.61, -122.33], 13) grid = L.mapbox.gridLayer('knock.l5dpakki').addTo(map) gridControl = L.mapbox.gridControl(grid).addTo(map); layers = {} layers.schools = L.mapbox.featureLayer().addTo(map) layers.schools.setStyle(color: 'red') layers.schools.loadURL('/data/school_sites.json') layers.housing = L.mapbox.featureLayer().addTo(map) layers.housing.setStyle(color: 'blue') layers.housing.loadURL('/data/seattle_public_housing_buildings.json')
182046
L.mapbox.accessToken = '<KEY>' map = L.mapbox.map('map', 'knock.l5dpakki'). setView([47.61, -122.33], 13) grid = L.mapbox.gridLayer('knock.l5dpakki').addTo(map) gridControl = L.mapbox.gridControl(grid).addTo(map); layers = {} layers.schools = L.mapbox.featureLayer().addTo(map) layers.schools.setStyle(color: 'red') layers.schools.loadURL('/data/school_sites.json') layers.housing = L.mapbox.featureLayer().addTo(map) layers.housing.setStyle(color: 'blue') layers.housing.loadURL('/data/seattle_public_housing_buildings.json')
true
L.mapbox.accessToken = 'PI:KEY:<KEY>END_PI' map = L.mapbox.map('map', 'knock.l5dpakki'). setView([47.61, -122.33], 13) grid = L.mapbox.gridLayer('knock.l5dpakki').addTo(map) gridControl = L.mapbox.gridControl(grid).addTo(map); layers = {} layers.schools = L.mapbox.featureLayer().addTo(map) layers.schools.setStyle(color: 'red') layers.schools.loadURL('/data/school_sites.json') layers.housing = L.mapbox.featureLayer().addTo(map) layers.housing.setStyle(color: 'blue') layers.housing.loadURL('/data/seattle_public_housing_buildings.json')
[ { "context": "###\n# middleware/disable_cache.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# Middleware to ", "end": 60, "score": 0.9996481537818909, "start": 49, "tag": "NAME", "value": "Dan Nichols" } ]
lib/middleware/disable_cache.coffee
dlnichols/h_media
0
### # middleware/disable_cache.coffee # # © 2014 Dan Nichols # See LICENSE for more details # # Middleware to disable the cache for scripts (mostly for dev) ### 'use strict' ### # disableCache ### module.exports = exports = # Disable caching of javascript (so they are reloaded every refresh) (req, res, next) -> if req.url.indexOf('/scripts/') is 0 res.header 'Cache-Control', 'no-cache, no-store, must-revalidate' res.header 'Pragma', 'no-cache' res.header 'Expires', 0 next()
21157
### # middleware/disable_cache.coffee # # © 2014 <NAME> # See LICENSE for more details # # Middleware to disable the cache for scripts (mostly for dev) ### 'use strict' ### # disableCache ### module.exports = exports = # Disable caching of javascript (so they are reloaded every refresh) (req, res, next) -> if req.url.indexOf('/scripts/') is 0 res.header 'Cache-Control', 'no-cache, no-store, must-revalidate' res.header 'Pragma', 'no-cache' res.header 'Expires', 0 next()
true
### # middleware/disable_cache.coffee # # © 2014 PI:NAME:<NAME>END_PI # See LICENSE for more details # # Middleware to disable the cache for scripts (mostly for dev) ### 'use strict' ### # disableCache ### module.exports = exports = # Disable caching of javascript (so they are reloaded every refresh) (req, res, next) -> if req.url.indexOf('/scripts/') is 0 res.header 'Cache-Control', 'no-cache, no-store, must-revalidate' res.header 'Pragma', 'no-cache' res.header 'Expires', 0 next()
[ { "context": "book = new Book(id: 1, title: \"Hipbone\", author: \"Mateus\", pages: [{book_id: 1}, {book_id: 1}])\n\n it ", "end": 1040, "score": 0.9993476271629333, "start": 1034, "tag": "NAME", "value": "Mateus" }, { "context": ": 1\n title: \"Hipbone\"\n aut...
spec/model_spec/index.coffee
mateusmaso/hipbone
0
module.exports = -> describe "Model", -> require("./syncs_spec").apply(this) require("./store_spec").apply(this) require("./schemes_spec").apply(this) require("./mappings_spec").apply(this) require("./populate_spec").apply(this) require("./validations_spec").apply(this) require("./nested_attributes_spec").apply(this) require("./computed_attributes_spec").apply(this) describe "json", -> class Book extends Hipbone.Model mappings: pages: -> Pages computedAttributes: full_title: "fullTitle" fullTitle: -> "#{@get("title")} by #{@get("author")}" @register "Book" class Page extends Hipbone.Model mappings: book: -> Book @register "Page" class Pages extends Hipbone.Collection model: Page @register "Pages" before -> Hipbone.Model.identityMap.clear() Hipbone.Collection.identityMap.clear() @book = new Book(id: 1, title: "Hipbone", author: "Mateus", pages: [{book_id: 1}, {book_id: 1}]) it "should include by default cid and computed attributes", -> chai.expect(@book.toJSON()).to.be.deep.equal cid: @book.cid id: 1 title: "Hipbone" author: "Mateus" full_title: "Hipbone by Mateus" it "should behave as backbone when sync", -> chai.expect(@book.toJSON(sync: true)).to.be.deep.equal id: 1 title: "Hipbone" author: "Mateus" it "should include mappings when requested", -> chai.expect(@book.toJSON(mappings: {pages: {mappings: book: {}}})).to.be.deep.equal cid: @book.cid id: 1 title: "Hipbone" author: "Mateus" full_title: "Hipbone by Mateus" pages: cid: @book.get("pages").cid length: 2 meta: cid: @book.get("pages").meta.cid models: [{ book: cid: @book.cid id: 1 title: "Hipbone" author: "Mateus" full_title: "Hipbone by Mateus" book_id: 1 cid: @book.get("pages").at(0).cid }, { book: cid: @book.cid id: 1 title: "Hipbone" author: "Mateus" full_title: "Hipbone by Mateus" book_id: 1 cid: @book.get("pages").at(1).cid }]
200676
module.exports = -> describe "Model", -> require("./syncs_spec").apply(this) require("./store_spec").apply(this) require("./schemes_spec").apply(this) require("./mappings_spec").apply(this) require("./populate_spec").apply(this) require("./validations_spec").apply(this) require("./nested_attributes_spec").apply(this) require("./computed_attributes_spec").apply(this) describe "json", -> class Book extends Hipbone.Model mappings: pages: -> Pages computedAttributes: full_title: "fullTitle" fullTitle: -> "#{@get("title")} by #{@get("author")}" @register "Book" class Page extends Hipbone.Model mappings: book: -> Book @register "Page" class Pages extends Hipbone.Collection model: Page @register "Pages" before -> Hipbone.Model.identityMap.clear() Hipbone.Collection.identityMap.clear() @book = new Book(id: 1, title: "Hipbone", author: "<NAME>", pages: [{book_id: 1}, {book_id: 1}]) it "should include by default cid and computed attributes", -> chai.expect(@book.toJSON()).to.be.deep.equal cid: @book.cid id: 1 title: "Hipbone" author: "<NAME>" full_title: "Hipbone by Mateus" it "should behave as backbone when sync", -> chai.expect(@book.toJSON(sync: true)).to.be.deep.equal id: 1 title: "Hipbone" author: "<NAME>" it "should include mappings when requested", -> chai.expect(@book.toJSON(mappings: {pages: {mappings: book: {}}})).to.be.deep.equal cid: @book.cid id: 1 title: "Hipbone" author: "<NAME>" full_title: "Hipbone by <NAME>" pages: cid: @book.get("pages").cid length: 2 meta: cid: @book.get("pages").meta.cid models: [{ book: cid: @book.cid id: 1 title: "Hipbone" author: "<NAME>" full_title: "Hipbone by Mateus" book_id: 1 cid: @book.get("pages").at(0).cid }, { book: cid: @book.cid id: 1 title: "Hipbone" author: "<NAME>" full_title: "Hipbone by Mateus" book_id: 1 cid: @book.get("pages").at(1).cid }]
true
module.exports = -> describe "Model", -> require("./syncs_spec").apply(this) require("./store_spec").apply(this) require("./schemes_spec").apply(this) require("./mappings_spec").apply(this) require("./populate_spec").apply(this) require("./validations_spec").apply(this) require("./nested_attributes_spec").apply(this) require("./computed_attributes_spec").apply(this) describe "json", -> class Book extends Hipbone.Model mappings: pages: -> Pages computedAttributes: full_title: "fullTitle" fullTitle: -> "#{@get("title")} by #{@get("author")}" @register "Book" class Page extends Hipbone.Model mappings: book: -> Book @register "Page" class Pages extends Hipbone.Collection model: Page @register "Pages" before -> Hipbone.Model.identityMap.clear() Hipbone.Collection.identityMap.clear() @book = new Book(id: 1, title: "Hipbone", author: "PI:NAME:<NAME>END_PI", pages: [{book_id: 1}, {book_id: 1}]) it "should include by default cid and computed attributes", -> chai.expect(@book.toJSON()).to.be.deep.equal cid: @book.cid id: 1 title: "Hipbone" author: "PI:NAME:<NAME>END_PI" full_title: "Hipbone by Mateus" it "should behave as backbone when sync", -> chai.expect(@book.toJSON(sync: true)).to.be.deep.equal id: 1 title: "Hipbone" author: "PI:NAME:<NAME>END_PI" it "should include mappings when requested", -> chai.expect(@book.toJSON(mappings: {pages: {mappings: book: {}}})).to.be.deep.equal cid: @book.cid id: 1 title: "Hipbone" author: "PI:NAME:<NAME>END_PI" full_title: "Hipbone by PI:NAME:<NAME>END_PI" pages: cid: @book.get("pages").cid length: 2 meta: cid: @book.get("pages").meta.cid models: [{ book: cid: @book.cid id: 1 title: "Hipbone" author: "PI:NAME:<NAME>END_PI" full_title: "Hipbone by Mateus" book_id: 1 cid: @book.get("pages").at(0).cid }, { book: cid: @book.cid id: 1 title: "Hipbone" author: "PI:NAME:<NAME>END_PI" full_title: "Hipbone by Mateus" book_id: 1 cid: @book.get("pages").at(1).cid }]
[ { "context": "n', (req, res) ->\n login = req.body.login\n pwd = req.body.password\n\n db().then (connection) ->\n connection.clien", "end": 602, "score": 0.9989138841629028, "start": 585, "tag": "PASSWORD", "value": "req.body.password" } ]
server/api/login.coffee
dreimert/foyer
2
express = require('express') app = express() access = require "../accessControl" db = require "../db" utils = require '../utils' Promise = require "bluebird" ### # Entrée : # - req.body.login # - req.body.password # Si logué : # req.session.logged = true # req.session.user = id: id login: login nom: nom prenom: prenom roles: [roleName] montant: montantArdoise # Renvoier : # - 404 : si mdp faut ou login inexistant # - 200 + req.session.user : si valide ### app.post '/login', (req, res) -> login = req.body.login pwd = req.body.password db().then (connection) -> connection.client.query """ SELECT ardoise.id, login, utilisateur.nom AS nom, prenom, montant, utilisateur.id AS utilisateur_id FROM "public"."ardoise" LEFT JOIN utilisateur on "utilisateur".ardoise_id = ardoise.id WHERE login = $1::text AND mdp = MD5($2::text) """, [login, pwd] .then (user) -> if user.rowCount isnt 1 res.status(404).send() else user = user.rows[0] Promise.all [ @connection.client.query """ SELECT role_id AS id, nom FROM "public"."utilisateur_role" INNER JOIN role on role_id = role.id WHERE utilisateur_id = $1::int """, [user.utilisateur_id] , @connection.client.query """ SELECT permission.id AS id, permission.nom AS nom FROM "public"."utilisateur_role" INNER JOIN role on role_id = role.id INNER JOIN permission_role on permission_role.role_id = role.id INNER JOIN permission on permission_role.permission_id = permission.id WHERE utilisateur_id = $1::int """, [user.utilisateur_id] ] .then ([roles, permissions]) -> req.session.logged = true req.session.user = id: user.id login: user.login nom: user.nom prenom: user.prenom montant: user.montant roles : roles.rows permissions: permissions.rows userId: user.utilisateur_id console.log req.session.user res.send req.session.user .catch (err) -> console.error "err::", err res.status(500).send(err) .finally -> @connection.done() app.get '/logged', access.logged, utils.sendUserHandler app.get '/logout', access.logged, (req, res) -> req.session.destroy() res.sendStatus(200) app.post '/loginRf', access.logged, (req, res) -> db().then (connection) -> # mdp_super, , mdp AS pass_hash connection.client.query """ SELECT DISTINCT * FROM utilisateur WHERE login = $1::text AND mdp_super = MD5($2::text) """, [req.session.user.login, req.body.password] .then (user) -> if user.rowCount isnt 1 res.status(404).send() else req.session.user.loginRf = true res.send true .catch (err) -> console.error "err::", err res.status(500).send(err) .finally -> @connection.done() module.exports = app
56899
express = require('express') app = express() access = require "../accessControl" db = require "../db" utils = require '../utils' Promise = require "bluebird" ### # Entrée : # - req.body.login # - req.body.password # Si logué : # req.session.logged = true # req.session.user = id: id login: login nom: nom prenom: prenom roles: [roleName] montant: montantArdoise # Renvoier : # - 404 : si mdp faut ou login inexistant # - 200 + req.session.user : si valide ### app.post '/login', (req, res) -> login = req.body.login pwd = <PASSWORD> db().then (connection) -> connection.client.query """ SELECT ardoise.id, login, utilisateur.nom AS nom, prenom, montant, utilisateur.id AS utilisateur_id FROM "public"."ardoise" LEFT JOIN utilisateur on "utilisateur".ardoise_id = ardoise.id WHERE login = $1::text AND mdp = MD5($2::text) """, [login, pwd] .then (user) -> if user.rowCount isnt 1 res.status(404).send() else user = user.rows[0] Promise.all [ @connection.client.query """ SELECT role_id AS id, nom FROM "public"."utilisateur_role" INNER JOIN role on role_id = role.id WHERE utilisateur_id = $1::int """, [user.utilisateur_id] , @connection.client.query """ SELECT permission.id AS id, permission.nom AS nom FROM "public"."utilisateur_role" INNER JOIN role on role_id = role.id INNER JOIN permission_role on permission_role.role_id = role.id INNER JOIN permission on permission_role.permission_id = permission.id WHERE utilisateur_id = $1::int """, [user.utilisateur_id] ] .then ([roles, permissions]) -> req.session.logged = true req.session.user = id: user.id login: user.login nom: user.nom prenom: user.prenom montant: user.montant roles : roles.rows permissions: permissions.rows userId: user.utilisateur_id console.log req.session.user res.send req.session.user .catch (err) -> console.error "err::", err res.status(500).send(err) .finally -> @connection.done() app.get '/logged', access.logged, utils.sendUserHandler app.get '/logout', access.logged, (req, res) -> req.session.destroy() res.sendStatus(200) app.post '/loginRf', access.logged, (req, res) -> db().then (connection) -> # mdp_super, , mdp AS pass_hash connection.client.query """ SELECT DISTINCT * FROM utilisateur WHERE login = $1::text AND mdp_super = MD5($2::text) """, [req.session.user.login, req.body.password] .then (user) -> if user.rowCount isnt 1 res.status(404).send() else req.session.user.loginRf = true res.send true .catch (err) -> console.error "err::", err res.status(500).send(err) .finally -> @connection.done() module.exports = app
true
express = require('express') app = express() access = require "../accessControl" db = require "../db" utils = require '../utils' Promise = require "bluebird" ### # Entrée : # - req.body.login # - req.body.password # Si logué : # req.session.logged = true # req.session.user = id: id login: login nom: nom prenom: prenom roles: [roleName] montant: montantArdoise # Renvoier : # - 404 : si mdp faut ou login inexistant # - 200 + req.session.user : si valide ### app.post '/login', (req, res) -> login = req.body.login pwd = PI:PASSWORD:<PASSWORD>END_PI db().then (connection) -> connection.client.query """ SELECT ardoise.id, login, utilisateur.nom AS nom, prenom, montant, utilisateur.id AS utilisateur_id FROM "public"."ardoise" LEFT JOIN utilisateur on "utilisateur".ardoise_id = ardoise.id WHERE login = $1::text AND mdp = MD5($2::text) """, [login, pwd] .then (user) -> if user.rowCount isnt 1 res.status(404).send() else user = user.rows[0] Promise.all [ @connection.client.query """ SELECT role_id AS id, nom FROM "public"."utilisateur_role" INNER JOIN role on role_id = role.id WHERE utilisateur_id = $1::int """, [user.utilisateur_id] , @connection.client.query """ SELECT permission.id AS id, permission.nom AS nom FROM "public"."utilisateur_role" INNER JOIN role on role_id = role.id INNER JOIN permission_role on permission_role.role_id = role.id INNER JOIN permission on permission_role.permission_id = permission.id WHERE utilisateur_id = $1::int """, [user.utilisateur_id] ] .then ([roles, permissions]) -> req.session.logged = true req.session.user = id: user.id login: user.login nom: user.nom prenom: user.prenom montant: user.montant roles : roles.rows permissions: permissions.rows userId: user.utilisateur_id console.log req.session.user res.send req.session.user .catch (err) -> console.error "err::", err res.status(500).send(err) .finally -> @connection.done() app.get '/logged', access.logged, utils.sendUserHandler app.get '/logout', access.logged, (req, res) -> req.session.destroy() res.sendStatus(200) app.post '/loginRf', access.logged, (req, res) -> db().then (connection) -> # mdp_super, , mdp AS pass_hash connection.client.query """ SELECT DISTINCT * FROM utilisateur WHERE login = $1::text AND mdp_super = MD5($2::text) """, [req.session.user.login, req.body.password] .then (user) -> if user.rowCount isnt 1 res.status(404).send() else req.session.user.loginRf = true res.send true .catch (err) -> console.error "err::", err res.status(500).send(err) .finally -> @connection.done() module.exports = app
[ { "context": "ents\n $form = $(\"#login-form\")\n $username = $(\"#username\")\n $password = $(\"#password\")\n $submit = $(\"#su", "end": 97, "score": 0.7810696363449097, "start": 89, "tag": "USERNAME", "value": "username" }, { "context": "\")\n $username = $(\"#username\")\n ...
app/assets/javascripts/login.coffee
ojny/oj_web
2
$(document).ready -> # get HTML elements $form = $("#login-form") $username = $("#username") $password = $("#password") $submit = $("#submit") $direct = $("#redirect") $message = $("#message") displayFormError = (field, message) -> if field != null $("#" + field).select() $message.html(message) $submit.removeAttr('disabled') submitForm = (e) -> e.preventDefault() $submit.attr('disabled','disabled') $message.html("Submitting...") console.log "prepare to submit form" # construct submit object data = { "username": $username.val() "password": $password.val() } console.log data # submit the data $.ajax "url": "/asyn/v1/account/login" "type": "post" "contentType": 'application/json' "data": JSON.stringify(data) "success": (ret) -> if ret['status'] == 0 window.location = "/" else displayFormError(ret['field'], ret['message']) "error": -> displayFormError(null, "Server error, please try again.") return false # submitForm $form.on("submit", submitForm) $direct.click -> window.location = "/account/register"
85600
$(document).ready -> # get HTML elements $form = $("#login-form") $username = $("#username") $password = $("#<PASSWORD>") $submit = $("#submit") $direct = $("#redirect") $message = $("#message") displayFormError = (field, message) -> if field != null $("#" + field).select() $message.html(message) $submit.removeAttr('disabled') submitForm = (e) -> e.preventDefault() $submit.attr('disabled','disabled') $message.html("Submitting...") console.log "prepare to submit form" # construct submit object data = { "username": $username.val() "password": $password.val() } console.log data # submit the data $.ajax "url": "/asyn/v1/account/login" "type": "post" "contentType": 'application/json' "data": JSON.stringify(data) "success": (ret) -> if ret['status'] == 0 window.location = "/" else displayFormError(ret['field'], ret['message']) "error": -> displayFormError(null, "Server error, please try again.") return false # submitForm $form.on("submit", submitForm) $direct.click -> window.location = "/account/register"
true
$(document).ready -> # get HTML elements $form = $("#login-form") $username = $("#username") $password = $("#PI:PASSWORD:<PASSWORD>END_PI") $submit = $("#submit") $direct = $("#redirect") $message = $("#message") displayFormError = (field, message) -> if field != null $("#" + field).select() $message.html(message) $submit.removeAttr('disabled') submitForm = (e) -> e.preventDefault() $submit.attr('disabled','disabled') $message.html("Submitting...") console.log "prepare to submit form" # construct submit object data = { "username": $username.val() "password": $password.val() } console.log data # submit the data $.ajax "url": "/asyn/v1/account/login" "type": "post" "contentType": 'application/json' "data": JSON.stringify(data) "success": (ret) -> if ret['status'] == 0 window.location = "/" else displayFormError(ret['field'], ret['message']) "error": -> displayFormError(null, "Server error, please try again.") return false # submitForm $form.on("submit", submitForm) $direct.click -> window.location = "/account/register"
[ { "context": "# Copyright (c) 2008-2013 Michael Dvorkin and contributors.\n#\n# Fat Free CRM is freely dist", "end": 41, "score": 0.9998666644096375, "start": 26, "tag": "NAME", "value": "Michael Dvorkin" } ]
app/assets/javascripts/crm_loginout.js.coffee
roadt/fat_free_crm
1,290
# Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ (($) -> window.crm ||= {} #---------------------------------------------------------------------------- crm.toggle_open_id_login = (first_field = "#authentication_openid_identifier") -> $("#login").toggle() $("#openid").toggle() $("#login_link").toggle() $("#openid_link").toggle() $(first_field).focus() #---------------------------------------------------------------------------- crm.toggle_open_id_signup = -> $("#login").toggle() $("#openid").toggle() $("#login_link").toggle() $("#openid_link").toggle() $("#user_email").focus() ) jQuery
216521
# Copyright (c) 2008-2013 <NAME> and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ (($) -> window.crm ||= {} #---------------------------------------------------------------------------- crm.toggle_open_id_login = (first_field = "#authentication_openid_identifier") -> $("#login").toggle() $("#openid").toggle() $("#login_link").toggle() $("#openid_link").toggle() $(first_field).focus() #---------------------------------------------------------------------------- crm.toggle_open_id_signup = -> $("#login").toggle() $("#openid").toggle() $("#login_link").toggle() $("#openid_link").toggle() $("#user_email").focus() ) jQuery
true
# Copyright (c) 2008-2013 PI:NAME:<NAME>END_PI and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ (($) -> window.crm ||= {} #---------------------------------------------------------------------------- crm.toggle_open_id_login = (first_field = "#authentication_openid_identifier") -> $("#login").toggle() $("#openid").toggle() $("#login_link").toggle() $("#openid_link").toggle() $(first_field).focus() #---------------------------------------------------------------------------- crm.toggle_open_id_signup = -> $("#login").toggle() $("#openid").toggle() $("#login_link").toggle() $("#openid_link").toggle() $("#user_email").focus() ) jQuery
[ { "context": "hrows ->\n userTable.insert {name: 'foo'}, -> test.fail()\n test.done()\n\n ", "end": 1488, "score": 0.6809037327766418, "start": 1485, "tag": "NAME", "value": "foo" }, { "context": "hrows ->\n userTable.update {name: 'foo'}...
test/mesa.coffee
clariture/mesa
0
_ = require 'underscore' mesa = require '../src/postgres' module.exports = 'set and get': (test) -> m = mesa m1 = m.set('string', 'foo') m2 = m1.set('number', 1) m3 = m2.set('string', 'bar') m4 = m3.set('number', 2) m5 = m4.set('string', 'baz') m6 = m5.set('number', 3) test.ok not m.string? test.ok not m.number? test.equal 'foo', m1.string test.ok not m1.number? test.equal 'foo', m2.string test.equal 1, m2.number test.equal 'bar', m3.string test.equal 1, m3.number test.equal 'bar', m4.string test.equal 2, m4.number test.equal 'baz', m5.string test.equal 2, m5.number test.equal 'baz', m6.string test.equal 3, m6.number test.done() 'throw': "when connection wasn't called": (test) -> userTable = mesa test.throws -> userTable.find {id: 1}, -> test.fail() test.done() "when table wasn't called": (test) -> userTable = mesa .connection(-> test.fail) test.throws -> userTable.delete -> test.fail() test.done() "when attributes wasn't called before insert": (test) -> userTable = mesa .connection(-> test.fail) .table('user') test.throws -> userTable.insert {name: 'foo'}, -> test.fail() test.done() "when attributes wasn't called before update": (test) -> userTable = mesa .connection(-> test.fail) .table('user') test.throws -> userTable.update {name: 'foo'}, -> test.fail() test.done() "when including something that has no association": (test) -> test.expect 1 connection = query: -> test.fail() userTable = mesa .table('user') .includes(billing_address: true) test.throws -> userTable.fetchIncludes connection, {id: 3, name: 'foo'}, -> test.fail() test.done() 'command': 'insert a record': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2) RETURNING id' test.deepEqual params, ['foo', 'foo@example.com'] cb null, {rows: [{id: 3}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) userTable.insert {name: 'foo', email: 'foo@example.com', x: 5}, (err, id) -> throw err if err? test.equal id, 3 test.done() 'insert with raw': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "id") VALUES ($1, LOG($2, $3)) RETURNING id' test.deepEqual params, ['foo', 3, 4] cb null, {rows: [{id: 3}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'id']) userTable.insert {name: 'foo', id: userTable.raw('LOG(?, ?)', 3, 4)}, (err, id) -> throw err if err? test.equal id, 3 test.done() 'insert with custom primaryKey': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2) RETURNING my_id' test.deepEqual params, ['foo', 'foo@example.com'] cb null, {rows: [{id: 3, my_id: 5}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) userTable .primaryKey('my_id') .insert {name: 'foo', email: 'foo@example.com', x: 5}, (err, id) -> throw err if err? test.equal id, 5 test.done() 'insert with returning': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2) RETURNING *' test.deepEqual params, ['foo', 'foo@example.com'] cb null, {rows: [{id: 3, name: 'foo', email: 'foo@example.com'}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) userTable .primaryKey('my_id') .returning('*') .insert {name: 'foo', email: 'foo@example.com', x: 5}, (err, record) -> throw err if err? test.deepEqual record, id: 3 name: 'foo' email: 'foo@example.com' test.done() 'insert multiple records': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2), ($3, $4) RETURNING id' test.deepEqual params, ['foo', 'foo@example.com', 'bar', 'bar@example.com'] cb null, {rows: [{id: 3}, {id: 4}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) userTable.insertMany [ {name: 'foo', email: 'foo@example.com', x: 5} {name: 'bar', email: 'bar@example.com', x: 6} ], (err, ids) -> throw err if err? test.deepEqual ids, [3, 4] test.done() 'delete': (test) -> test.expect 2 connection = query: (sql, params, cb) -> test.equal sql, 'DELETE FROM "user" WHERE (id = $1) AND (name = $2)' test.deepEqual params, [3, 'foo'] cb() userTable = mesa .connection(connection) .table('user') userTable.where(id: 3).where(name: 'foo').delete (err) -> throw err if err? test.done() 'update': (test) -> test.expect 2 connection = query: (sql, params, cb) -> test.equal sql, 'UPDATE "user" SET "name" = $1, "email" = $2 WHERE (id = $3) AND (name = $4)' test.deepEqual params, ['bar', 'bar@example.com', 3, 'foo'] cb() userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) updates = {name: 'bar', x: 5, y: 8, email: 'bar@example.com'} userTable.where(id: 3).where(name: 'foo').update updates, (err) -> throw err if err? test.done() 'update with returning': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'UPDATE "user" SET "name" = $1, "email" = $2 WHERE (id = $3) AND (name = $4) RETURNING *' test.deepEqual params, ['bar', 'bar@example.com', 3, 'foo'] cb null, {rows: [{id: 3}, {id: 4}]} userTable = mesa .connection(connection) .table('user') .returning('*') .attributes(['name', 'email']) updates = {name: 'bar', x: 5, y: 8, email: 'bar@example.com'} userTable.where(id: 3).where(name: 'foo').update updates, (err, results) -> throw err if err? test.deepEqual results, [{id: 3}, {id: 4}] test.done() 'update with raw': (test) -> test.expect 2 connection = query: (sql, params, cb) -> test.equal sql, 'UPDATE "user" SET "id" = LOG($1, $2), "name" = $3 WHERE (id = LOG($4, $5)) AND (name = $6)' test.deepEqual params, [7, 8, 'bar', 11, 12, 'foo'] cb() userTable = mesa .connection(connection) .table('user') .attributes(['id', 'name']) updates = name: 'bar' id: userTable.raw('LOG(?, ?)', 7, 8) x: 5 y: 8 email: 'bar@example.com' userTable .where(id: userTable.raw('LOG(?, ?)', 11, 12)) .where(name: 'foo') .update updates, (err) -> throw err if err? test.done() 'query': 'find all': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'SELECT name FROM "user" WHERE id = $1' test.deepEqual params, [3] cb null, {rows: [{name: 'foo'}, {name: 'bar'}]} userTable = mesa .connection(connection) .table('user') userTable.where(id: 3).select('name').find (err, users) -> throw err if err? test.deepEqual users, [{name: 'foo'}, {name: 'bar'}] test.done() 'find the first': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'SELECT name FROM "user" WHERE id = $1' test.deepEqual params, [3] cb null, {rows: [{name: 'foo'}, {name: 'bar'}]} userTable = mesa .connection(connection) .table('user') userTable.where(id: 3).select('name').first (err, user) -> throw err if err? test.deepEqual user, {name: 'foo'} test.done() 'test for existence': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'SELECT * FROM "user" WHERE id = $1' test.deepEqual params, [3] cb null, {rows: [{name: 'foo'}, {name: 'bar'}]} userTable = mesa .connection(connection) .table('user') userTable.where(id: 3).exists (err, exists) -> throw err if err? test.ok exists test.done() 'everything together': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'SELECT user.*, count(project.id) AS project_count FROM "user" JOIN project ON user.id = project.user_id WHERE (id = $1) AND (name = $2) GROUP BY user.id ORDER BY created DESC, name ASC LIMIT $3 OFFSET $4' test.deepEqual params, [3, 'foo', 10, 20] cb null, {rows: [{name: 'foo'}, {name: 'bar'}]} userTable = mesa .connection(connection) .table('user') .select('user.*, count(project.id) AS project_count') .where(id: 3) .where('name = ?', 'foo') .join('JOIN project ON user.id = project.user_id') .group('user.id') .order('created DESC, name ASC') .limit(10) .offset(20) .find (err, users) -> throw err if err? test.deepEqual users, [{name: 'foo'}, {name: 'bar'}] test.done() 'extending': (test) -> test.expect 8 userTable = Object.create mesa userTable.insert = (data, cb) -> @getConnection (err, connection) => return cb err if err? connection.query 'BEGIN;', [], (err) => return cb err if err? # do the original insert, but on the connection we just got # and started the transaction on mesa.insert.call @connection(connection), data, (err, userId) => return cb err if err? test.equal userId, 200 # do other things in the transaction... connection.query 'COMMIT;', [], (err) => return cb err if err? cb null, 500 getConnection = (cb) -> call = 1 cb null, query: (sql, params, cb) -> switch call++ when 1 test.equal sql, 'BEGIN;' test.deepEqual params, [] cb() when 2 test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2) RETURNING id' test.deepEqual params, ['foo', 'foo@example.com'] cb null, {rows: [{id: 200}]} when 3 test.equal sql, 'COMMIT;' test.deepEqual params, [] cb() userTable .table('user') .connection(getConnection) .attributes(['name', 'email']) .insert {name: 'foo', email: 'foo@example.com'}, (err, userId) -> throw err if err? test.equal userId, 500 test.done()
37450
_ = require 'underscore' mesa = require '../src/postgres' module.exports = 'set and get': (test) -> m = mesa m1 = m.set('string', 'foo') m2 = m1.set('number', 1) m3 = m2.set('string', 'bar') m4 = m3.set('number', 2) m5 = m4.set('string', 'baz') m6 = m5.set('number', 3) test.ok not m.string? test.ok not m.number? test.equal 'foo', m1.string test.ok not m1.number? test.equal 'foo', m2.string test.equal 1, m2.number test.equal 'bar', m3.string test.equal 1, m3.number test.equal 'bar', m4.string test.equal 2, m4.number test.equal 'baz', m5.string test.equal 2, m5.number test.equal 'baz', m6.string test.equal 3, m6.number test.done() 'throw': "when connection wasn't called": (test) -> userTable = mesa test.throws -> userTable.find {id: 1}, -> test.fail() test.done() "when table wasn't called": (test) -> userTable = mesa .connection(-> test.fail) test.throws -> userTable.delete -> test.fail() test.done() "when attributes wasn't called before insert": (test) -> userTable = mesa .connection(-> test.fail) .table('user') test.throws -> userTable.insert {name: '<NAME>'}, -> test.fail() test.done() "when attributes wasn't called before update": (test) -> userTable = mesa .connection(-> test.fail) .table('user') test.throws -> userTable.update {name: '<NAME>'}, -> test.fail() test.done() "when including something that has no association": (test) -> test.expect 1 connection = query: -> test.fail() userTable = mesa .table('user') .includes(billing_address: true) test.throws -> userTable.fetchIncludes connection, {id: 3, name: 'foo'}, -> test.fail() test.done() 'command': 'insert a record': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2) RETURNING id' test.deepEqual params, ['foo', '<EMAIL>'] cb null, {rows: [{id: 3}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) userTable.insert {name: 'foo', email: '<EMAIL>', x: 5}, (err, id) -> throw err if err? test.equal id, 3 test.done() 'insert with raw': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "id") VALUES ($1, LOG($2, $3)) RETURNING id' test.deepEqual params, ['foo', 3, 4] cb null, {rows: [{id: 3}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'id']) userTable.insert {name: '<NAME>', id: userTable.raw('LOG(?, ?)', 3, 4)}, (err, id) -> throw err if err? test.equal id, 3 test.done() 'insert with custom primaryKey': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2) RETURNING my_id' test.deepEqual params, ['foo', '<EMAIL>'] cb null, {rows: [{id: 3, my_id: 5}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) userTable .primaryKey('my_id') .insert {name: 'foo', email: '<EMAIL>', x: 5}, (err, id) -> throw err if err? test.equal id, 5 test.done() 'insert with returning': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2) RETURNING *' test.deepEqual params, ['foo', '<EMAIL>'] cb null, {rows: [{id: 3, name: 'foo', email: '<EMAIL>'}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) userTable .primaryKey('my_id') .returning('*') .insert {name: '<NAME>', email: '<EMAIL>', x: 5}, (err, record) -> throw err if err? test.deepEqual record, id: 3 name: '<NAME>' email: '<EMAIL>' test.done() 'insert multiple records': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2), ($3, $4) RETURNING id' test.deepEqual params, ['foo', '<EMAIL>', 'bar', '<EMAIL>'] cb null, {rows: [{id: 3}, {id: 4}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) userTable.insertMany [ {name: 'foo', email: '<EMAIL>', x: 5} {name: 'bar', email: '<EMAIL>', x: 6} ], (err, ids) -> throw err if err? test.deepEqual ids, [3, 4] test.done() 'delete': (test) -> test.expect 2 connection = query: (sql, params, cb) -> test.equal sql, 'DELETE FROM "user" WHERE (id = $1) AND (name = $2)' test.deepEqual params, [3, 'foo'] cb() userTable = mesa .connection(connection) .table('user') userTable.where(id: 3).where(name: 'foo').delete (err) -> throw err if err? test.done() 'update': (test) -> test.expect 2 connection = query: (sql, params, cb) -> test.equal sql, 'UPDATE "user" SET "name" = $1, "email" = $2 WHERE (id = $3) AND (name = $4)' test.deepEqual params, ['bar', '<EMAIL>', 3, 'foo'] cb() userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) updates = {name: 'bar', x: 5, y: 8, email: '<EMAIL>'} userTable.where(id: 3).where(name: 'foo').update updates, (err) -> throw err if err? test.done() 'update with returning': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'UPDATE "user" SET "name" = $1, "email" = $2 WHERE (id = $3) AND (name = $4) RETURNING *' test.deepEqual params, ['bar', '<EMAIL>', 3, 'foo'] cb null, {rows: [{id: 3}, {id: 4}]} userTable = mesa .connection(connection) .table('user') .returning('*') .attributes(['name', 'email']) updates = {name: 'bar', x: 5, y: 8, email: '<EMAIL>'} userTable.where(id: 3).where(name: 'foo').update updates, (err, results) -> throw err if err? test.deepEqual results, [{id: 3}, {id: 4}] test.done() 'update with raw': (test) -> test.expect 2 connection = query: (sql, params, cb) -> test.equal sql, 'UPDATE "user" SET "id" = LOG($1, $2), "name" = $3 WHERE (id = LOG($4, $5)) AND (name = $6)' test.deepEqual params, [7, 8, 'bar', 11, 12, 'foo'] cb() userTable = mesa .connection(connection) .table('user') .attributes(['id', 'name']) updates = name: 'bar' id: userTable.raw('LOG(?, ?)', 7, 8) x: 5 y: 8 email: '<EMAIL>' userTable .where(id: userTable.raw('LOG(?, ?)', 11, 12)) .where(name: 'foo') .update updates, (err) -> throw err if err? test.done() 'query': 'find all': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'SELECT name FROM "user" WHERE id = $1' test.deepEqual params, [3] cb null, {rows: [{name: 'foo'}, {name: 'bar'}]} userTable = mesa .connection(connection) .table('user') userTable.where(id: 3).select('name').find (err, users) -> throw err if err? test.deepEqual users, [{name: 'foo'}, {name: 'bar'}] test.done() 'find the first': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'SELECT name FROM "user" WHERE id = $1' test.deepEqual params, [3] cb null, {rows: [{name: 'foo'}, {name: 'bar'}]} userTable = mesa .connection(connection) .table('user') userTable.where(id: 3).select('name').first (err, user) -> throw err if err? test.deepEqual user, {name: 'foo'} test.done() 'test for existence': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'SELECT * FROM "user" WHERE id = $1' test.deepEqual params, [3] cb null, {rows: [{name: 'foo'}, {name: 'bar'}]} userTable = mesa .connection(connection) .table('user') userTable.where(id: 3).exists (err, exists) -> throw err if err? test.ok exists test.done() 'everything together': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'SELECT user.*, count(project.id) AS project_count FROM "user" JOIN project ON user.id = project.user_id WHERE (id = $1) AND (name = $2) GROUP BY user.id ORDER BY created DESC, name ASC LIMIT $3 OFFSET $4' test.deepEqual params, [3, 'foo', 10, 20] cb null, {rows: [{name: 'foo'}, {name: 'bar'}]} userTable = mesa .connection(connection) .table('user') .select('user.*, count(project.id) AS project_count') .where(id: 3) .where('name = ?', 'foo') .join('JOIN project ON user.id = project.user_id') .group('user.id') .order('created DESC, name ASC') .limit(10) .offset(20) .find (err, users) -> throw err if err? test.deepEqual users, [{name: 'foo'}, {name: 'bar'}] test.done() 'extending': (test) -> test.expect 8 userTable = Object.create mesa userTable.insert = (data, cb) -> @getConnection (err, connection) => return cb err if err? connection.query 'BEGIN;', [], (err) => return cb err if err? # do the original insert, but on the connection we just got # and started the transaction on mesa.insert.call @connection(connection), data, (err, userId) => return cb err if err? test.equal userId, 200 # do other things in the transaction... connection.query 'COMMIT;', [], (err) => return cb err if err? cb null, 500 getConnection = (cb) -> call = 1 cb null, query: (sql, params, cb) -> switch call++ when 1 test.equal sql, 'BEGIN;' test.deepEqual params, [] cb() when 2 test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2) RETURNING id' test.deepEqual params, ['foo', '<EMAIL>'] cb null, {rows: [{id: 200}]} when 3 test.equal sql, 'COMMIT;' test.deepEqual params, [] cb() userTable .table('user') .connection(getConnection) .attributes(['name', 'email']) .insert {name: '<NAME>', email: '<EMAIL>'}, (err, userId) -> throw err if err? test.equal userId, 500 test.done()
true
_ = require 'underscore' mesa = require '../src/postgres' module.exports = 'set and get': (test) -> m = mesa m1 = m.set('string', 'foo') m2 = m1.set('number', 1) m3 = m2.set('string', 'bar') m4 = m3.set('number', 2) m5 = m4.set('string', 'baz') m6 = m5.set('number', 3) test.ok not m.string? test.ok not m.number? test.equal 'foo', m1.string test.ok not m1.number? test.equal 'foo', m2.string test.equal 1, m2.number test.equal 'bar', m3.string test.equal 1, m3.number test.equal 'bar', m4.string test.equal 2, m4.number test.equal 'baz', m5.string test.equal 2, m5.number test.equal 'baz', m6.string test.equal 3, m6.number test.done() 'throw': "when connection wasn't called": (test) -> userTable = mesa test.throws -> userTable.find {id: 1}, -> test.fail() test.done() "when table wasn't called": (test) -> userTable = mesa .connection(-> test.fail) test.throws -> userTable.delete -> test.fail() test.done() "when attributes wasn't called before insert": (test) -> userTable = mesa .connection(-> test.fail) .table('user') test.throws -> userTable.insert {name: 'PI:NAME:<NAME>END_PI'}, -> test.fail() test.done() "when attributes wasn't called before update": (test) -> userTable = mesa .connection(-> test.fail) .table('user') test.throws -> userTable.update {name: 'PI:NAME:<NAME>END_PI'}, -> test.fail() test.done() "when including something that has no association": (test) -> test.expect 1 connection = query: -> test.fail() userTable = mesa .table('user') .includes(billing_address: true) test.throws -> userTable.fetchIncludes connection, {id: 3, name: 'foo'}, -> test.fail() test.done() 'command': 'insert a record': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2) RETURNING id' test.deepEqual params, ['foo', 'PI:EMAIL:<EMAIL>END_PI'] cb null, {rows: [{id: 3}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) userTable.insert {name: 'foo', email: 'PI:EMAIL:<EMAIL>END_PI', x: 5}, (err, id) -> throw err if err? test.equal id, 3 test.done() 'insert with raw': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "id") VALUES ($1, LOG($2, $3)) RETURNING id' test.deepEqual params, ['foo', 3, 4] cb null, {rows: [{id: 3}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'id']) userTable.insert {name: 'PI:NAME:<NAME>END_PI', id: userTable.raw('LOG(?, ?)', 3, 4)}, (err, id) -> throw err if err? test.equal id, 3 test.done() 'insert with custom primaryKey': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2) RETURNING my_id' test.deepEqual params, ['foo', 'PI:EMAIL:<EMAIL>END_PI'] cb null, {rows: [{id: 3, my_id: 5}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) userTable .primaryKey('my_id') .insert {name: 'foo', email: 'PI:EMAIL:<EMAIL>END_PI', x: 5}, (err, id) -> throw err if err? test.equal id, 5 test.done() 'insert with returning': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2) RETURNING *' test.deepEqual params, ['foo', 'PI:EMAIL:<EMAIL>END_PI'] cb null, {rows: [{id: 3, name: 'foo', email: 'PI:EMAIL:<EMAIL>END_PI'}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) userTable .primaryKey('my_id') .returning('*') .insert {name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI', x: 5}, (err, record) -> throw err if err? test.deepEqual record, id: 3 name: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' test.done() 'insert multiple records': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2), ($3, $4) RETURNING id' test.deepEqual params, ['foo', 'PI:EMAIL:<EMAIL>END_PI', 'bar', 'PI:EMAIL:<EMAIL>END_PI'] cb null, {rows: [{id: 3}, {id: 4}]} userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) userTable.insertMany [ {name: 'foo', email: 'PI:EMAIL:<EMAIL>END_PI', x: 5} {name: 'bar', email: 'PI:EMAIL:<EMAIL>END_PI', x: 6} ], (err, ids) -> throw err if err? test.deepEqual ids, [3, 4] test.done() 'delete': (test) -> test.expect 2 connection = query: (sql, params, cb) -> test.equal sql, 'DELETE FROM "user" WHERE (id = $1) AND (name = $2)' test.deepEqual params, [3, 'foo'] cb() userTable = mesa .connection(connection) .table('user') userTable.where(id: 3).where(name: 'foo').delete (err) -> throw err if err? test.done() 'update': (test) -> test.expect 2 connection = query: (sql, params, cb) -> test.equal sql, 'UPDATE "user" SET "name" = $1, "email" = $2 WHERE (id = $3) AND (name = $4)' test.deepEqual params, ['bar', 'PI:EMAIL:<EMAIL>END_PI', 3, 'foo'] cb() userTable = mesa .connection(connection) .table('user') .attributes(['name', 'email']) updates = {name: 'bar', x: 5, y: 8, email: 'PI:EMAIL:<EMAIL>END_PI'} userTable.where(id: 3).where(name: 'foo').update updates, (err) -> throw err if err? test.done() 'update with returning': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'UPDATE "user" SET "name" = $1, "email" = $2 WHERE (id = $3) AND (name = $4) RETURNING *' test.deepEqual params, ['bar', 'PI:EMAIL:<EMAIL>END_PI', 3, 'foo'] cb null, {rows: [{id: 3}, {id: 4}]} userTable = mesa .connection(connection) .table('user') .returning('*') .attributes(['name', 'email']) updates = {name: 'bar', x: 5, y: 8, email: 'PI:EMAIL:<EMAIL>END_PI'} userTable.where(id: 3).where(name: 'foo').update updates, (err, results) -> throw err if err? test.deepEqual results, [{id: 3}, {id: 4}] test.done() 'update with raw': (test) -> test.expect 2 connection = query: (sql, params, cb) -> test.equal sql, 'UPDATE "user" SET "id" = LOG($1, $2), "name" = $3 WHERE (id = LOG($4, $5)) AND (name = $6)' test.deepEqual params, [7, 8, 'bar', 11, 12, 'foo'] cb() userTable = mesa .connection(connection) .table('user') .attributes(['id', 'name']) updates = name: 'bar' id: userTable.raw('LOG(?, ?)', 7, 8) x: 5 y: 8 email: 'PI:EMAIL:<EMAIL>END_PI' userTable .where(id: userTable.raw('LOG(?, ?)', 11, 12)) .where(name: 'foo') .update updates, (err) -> throw err if err? test.done() 'query': 'find all': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'SELECT name FROM "user" WHERE id = $1' test.deepEqual params, [3] cb null, {rows: [{name: 'foo'}, {name: 'bar'}]} userTable = mesa .connection(connection) .table('user') userTable.where(id: 3).select('name').find (err, users) -> throw err if err? test.deepEqual users, [{name: 'foo'}, {name: 'bar'}] test.done() 'find the first': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'SELECT name FROM "user" WHERE id = $1' test.deepEqual params, [3] cb null, {rows: [{name: 'foo'}, {name: 'bar'}]} userTable = mesa .connection(connection) .table('user') userTable.where(id: 3).select('name').first (err, user) -> throw err if err? test.deepEqual user, {name: 'foo'} test.done() 'test for existence': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'SELECT * FROM "user" WHERE id = $1' test.deepEqual params, [3] cb null, {rows: [{name: 'foo'}, {name: 'bar'}]} userTable = mesa .connection(connection) .table('user') userTable.where(id: 3).exists (err, exists) -> throw err if err? test.ok exists test.done() 'everything together': (test) -> test.expect 3 connection = query: (sql, params, cb) -> test.equal sql, 'SELECT user.*, count(project.id) AS project_count FROM "user" JOIN project ON user.id = project.user_id WHERE (id = $1) AND (name = $2) GROUP BY user.id ORDER BY created DESC, name ASC LIMIT $3 OFFSET $4' test.deepEqual params, [3, 'foo', 10, 20] cb null, {rows: [{name: 'foo'}, {name: 'bar'}]} userTable = mesa .connection(connection) .table('user') .select('user.*, count(project.id) AS project_count') .where(id: 3) .where('name = ?', 'foo') .join('JOIN project ON user.id = project.user_id') .group('user.id') .order('created DESC, name ASC') .limit(10) .offset(20) .find (err, users) -> throw err if err? test.deepEqual users, [{name: 'foo'}, {name: 'bar'}] test.done() 'extending': (test) -> test.expect 8 userTable = Object.create mesa userTable.insert = (data, cb) -> @getConnection (err, connection) => return cb err if err? connection.query 'BEGIN;', [], (err) => return cb err if err? # do the original insert, but on the connection we just got # and started the transaction on mesa.insert.call @connection(connection), data, (err, userId) => return cb err if err? test.equal userId, 200 # do other things in the transaction... connection.query 'COMMIT;', [], (err) => return cb err if err? cb null, 500 getConnection = (cb) -> call = 1 cb null, query: (sql, params, cb) -> switch call++ when 1 test.equal sql, 'BEGIN;' test.deepEqual params, [] cb() when 2 test.equal sql, 'INSERT INTO "user"("name", "email") VALUES ($1, $2) RETURNING id' test.deepEqual params, ['foo', 'PI:EMAIL:<EMAIL>END_PI'] cb null, {rows: [{id: 200}]} when 3 test.equal sql, 'COMMIT;' test.deepEqual params, [] cb() userTable .table('user') .connection(getConnection) .attributes(['name', 'email']) .insert {name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}, (err, userId) -> throw err if err? test.equal userId, 500 test.done()
[ { "context": "{ varname }}\", ->\n render(\"{{ user }}\", {user:'Bob'}).should.equal 'Bob'\n\n\n it \"{{ parent.child }}\"", "end": 975, "score": 0.6215587258338928, "start": 972, "tag": "NAME", "value": "Bob" }, { "context": " render(\"{{ user }}\", {user:'Bob'}).should.equal 'B...
node_modules/liquid.coffee/test/lib/liquid/variable_test.coffee
darkoverlordofdata/shmupwarz-ooc
1
describe 'Liquid variables ', -> it "{{ 'string literal' }}", -> render('{{"string literal"}}').should.equal 'string literal' render('{{ "string literal" }}').should.equal 'string literal' render("{{'string literal'}}").should.equal 'string literal' render("{{ 'string literal' }}").should.equal 'string literal' render("{{'string \"literal\"'}}").should.equal 'string "literal"' render("{{ 'string \"literal\"' }}").should.equal 'string "literal"' it "{{ 10 }}", -> render('{{10}}').should.equal '10' render('{{ 10 }}').should.equal '10' it "{{ 5.5 }}", -> render('{{5.5}}').should.equal '5.5' render('{{ 5.5 }}').should.equal '5.5' it "{{ (1..5) }}", -> render('{{(1..5)}}').should.equal '1,2,3,4,5' render('{{ (1..5) }}').should.equal '1,2,3,4,5' it "{{ (a..e) }}", -> render('{{(a..e)}}').should.equal 'a,b,c,d,e' it "{{ varname }}", -> render("{{ user }}", {user:'Bob'}).should.equal 'Bob' it "{{ parent.child }}", -> render("{{ user.name }}", {user:{ name:'Bob' }}).should.equal 'Bob' it "{{ collection[0] }}", -> render("{{ users[0] }}", {users:['Bob']}).should.equal 'Bob' it "{{ collection[0].child }}", -> render("{{ users[0].name }}", {users:[{name:'Bob'}]}).should.equal 'Bob'
50047
describe 'Liquid variables ', -> it "{{ 'string literal' }}", -> render('{{"string literal"}}').should.equal 'string literal' render('{{ "string literal" }}').should.equal 'string literal' render("{{'string literal'}}").should.equal 'string literal' render("{{ 'string literal' }}").should.equal 'string literal' render("{{'string \"literal\"'}}").should.equal 'string "literal"' render("{{ 'string \"literal\"' }}").should.equal 'string "literal"' it "{{ 10 }}", -> render('{{10}}').should.equal '10' render('{{ 10 }}').should.equal '10' it "{{ 5.5 }}", -> render('{{5.5}}').should.equal '5.5' render('{{ 5.5 }}').should.equal '5.5' it "{{ (1..5) }}", -> render('{{(1..5)}}').should.equal '1,2,3,4,5' render('{{ (1..5) }}').should.equal '1,2,3,4,5' it "{{ (a..e) }}", -> render('{{(a..e)}}').should.equal 'a,b,c,d,e' it "{{ varname }}", -> render("{{ user }}", {user:'<NAME>'}).should.equal '<NAME>' it "{{ parent.child }}", -> render("{{ user.name }}", {user:{ name:'<NAME>' }}).should.equal 'Bob' it "{{ collection[0] }}", -> render("{{ users[0] }}", {users:['Bob']}).should.equal '<NAME>' it "{{ collection[0].child }}", -> render("{{ users[0].name }}", {users:[{name:'<NAME>'}]}).should.equal 'Bob'
true
describe 'Liquid variables ', -> it "{{ 'string literal' }}", -> render('{{"string literal"}}').should.equal 'string literal' render('{{ "string literal" }}').should.equal 'string literal' render("{{'string literal'}}").should.equal 'string literal' render("{{ 'string literal' }}").should.equal 'string literal' render("{{'string \"literal\"'}}").should.equal 'string "literal"' render("{{ 'string \"literal\"' }}").should.equal 'string "literal"' it "{{ 10 }}", -> render('{{10}}').should.equal '10' render('{{ 10 }}').should.equal '10' it "{{ 5.5 }}", -> render('{{5.5}}').should.equal '5.5' render('{{ 5.5 }}').should.equal '5.5' it "{{ (1..5) }}", -> render('{{(1..5)}}').should.equal '1,2,3,4,5' render('{{ (1..5) }}').should.equal '1,2,3,4,5' it "{{ (a..e) }}", -> render('{{(a..e)}}').should.equal 'a,b,c,d,e' it "{{ varname }}", -> render("{{ user }}", {user:'PI:NAME:<NAME>END_PI'}).should.equal 'PI:NAME:<NAME>END_PI' it "{{ parent.child }}", -> render("{{ user.name }}", {user:{ name:'PI:NAME:<NAME>END_PI' }}).should.equal 'Bob' it "{{ collection[0] }}", -> render("{{ users[0] }}", {users:['Bob']}).should.equal 'PI:NAME:<NAME>END_PI' it "{{ collection[0].child }}", -> render("{{ users[0].name }}", {users:[{name:'PI:NAME:<NAME>END_PI'}]}).should.equal 'Bob'
[ { "context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib", "end": 79, "score": 0.9998348951339722, "start": 66, "tag": "NAME", "value": "Henri Bergius" } ]
src/widgets/dropdownbutton.coffee
GerHobbelt/hallo
682
# Hallo - a rich text editing jQuery UI widget # (c) 2011 Henri Bergius, IKS Consortium # Hallo may be freely distributed under the MIT license ((jQuery) -> jQuery.widget 'IKS.hallodropdownbutton', button: null options: uuid: '' label: null icon: null editable: null target: '' cssClass: null _create: -> @options.icon ?= "fa-#{@options.label.toLowerCase()}" _init: -> target = jQuery @options.target target.css 'position', 'absolute' target.addClass 'dropdown-menu' target.hide() @button = @_prepareButton() unless @button @button.on 'click', => if target.hasClass 'open' @_hideTarget() return @_showTarget() target.on 'click', => @_hideTarget() @options.editable.element.on 'hallodeactivated', => @_hideTarget() @element.append @button _showTarget: -> target = jQuery @options.target @_updateTargetPosition() target.addClass 'open' target.show() _hideTarget: -> target = jQuery @options.target target.removeClass 'open' target.hide() _updateTargetPosition: -> target = jQuery @options.target {top, left} = @button.position() top += @button.outerHeight() target.css 'top', top target.css 'left', left - 20 _prepareButton: -> id = "#{@options.uuid}-#{@options.label}" classes = [ 'ui-button' 'ui-widget' 'ui-state-default' 'ui-corner-all' 'ui-button-text-only' ] buttonEl = jQuery "<button id=\"#{id}\" class=\"#{classes.join(' ')}\" title=\"#{@options.label}\"> <span class=\"ui-button-text\"> <i class=\"fa #{@options.icon}\"></i> </span> </button>" buttonEl.addClass @options.cssClass if @options.cssClass buttonEl )(jQuery)
65490
# Hallo - a rich text editing jQuery UI widget # (c) 2011 <NAME>, IKS Consortium # Hallo may be freely distributed under the MIT license ((jQuery) -> jQuery.widget 'IKS.hallodropdownbutton', button: null options: uuid: '' label: null icon: null editable: null target: '' cssClass: null _create: -> @options.icon ?= "fa-#{@options.label.toLowerCase()}" _init: -> target = jQuery @options.target target.css 'position', 'absolute' target.addClass 'dropdown-menu' target.hide() @button = @_prepareButton() unless @button @button.on 'click', => if target.hasClass 'open' @_hideTarget() return @_showTarget() target.on 'click', => @_hideTarget() @options.editable.element.on 'hallodeactivated', => @_hideTarget() @element.append @button _showTarget: -> target = jQuery @options.target @_updateTargetPosition() target.addClass 'open' target.show() _hideTarget: -> target = jQuery @options.target target.removeClass 'open' target.hide() _updateTargetPosition: -> target = jQuery @options.target {top, left} = @button.position() top += @button.outerHeight() target.css 'top', top target.css 'left', left - 20 _prepareButton: -> id = "#{@options.uuid}-#{@options.label}" classes = [ 'ui-button' 'ui-widget' 'ui-state-default' 'ui-corner-all' 'ui-button-text-only' ] buttonEl = jQuery "<button id=\"#{id}\" class=\"#{classes.join(' ')}\" title=\"#{@options.label}\"> <span class=\"ui-button-text\"> <i class=\"fa #{@options.icon}\"></i> </span> </button>" buttonEl.addClass @options.cssClass if @options.cssClass buttonEl )(jQuery)
true
# Hallo - a rich text editing jQuery UI widget # (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium # Hallo may be freely distributed under the MIT license ((jQuery) -> jQuery.widget 'IKS.hallodropdownbutton', button: null options: uuid: '' label: null icon: null editable: null target: '' cssClass: null _create: -> @options.icon ?= "fa-#{@options.label.toLowerCase()}" _init: -> target = jQuery @options.target target.css 'position', 'absolute' target.addClass 'dropdown-menu' target.hide() @button = @_prepareButton() unless @button @button.on 'click', => if target.hasClass 'open' @_hideTarget() return @_showTarget() target.on 'click', => @_hideTarget() @options.editable.element.on 'hallodeactivated', => @_hideTarget() @element.append @button _showTarget: -> target = jQuery @options.target @_updateTargetPosition() target.addClass 'open' target.show() _hideTarget: -> target = jQuery @options.target target.removeClass 'open' target.hide() _updateTargetPosition: -> target = jQuery @options.target {top, left} = @button.position() top += @button.outerHeight() target.css 'top', top target.css 'left', left - 20 _prepareButton: -> id = "#{@options.uuid}-#{@options.label}" classes = [ 'ui-button' 'ui-widget' 'ui-state-default' 'ui-corner-all' 'ui-button-text-only' ] buttonEl = jQuery "<button id=\"#{id}\" class=\"#{classes.join(' ')}\" title=\"#{@options.label}\"> <span class=\"ui-button-text\"> <i class=\"fa #{@options.icon}\"></i> </span> </button>" buttonEl.addClass @options.cssClass if @options.cssClass buttonEl )(jQuery)
[ { "context": " ->\n\n post: (req, res) ->\n params =\n Key: uuid.v4()\n Body: fs.createReadStream(req.file.path)\n", "end": 401, "score": 0.5811285972595215, "start": 394, "tag": "KEY", "value": "uuid.v4" } ]
server/src/controllers/images_controller.coffee
codyseibert/jotit
1
models = require '../models/models' Users = models.Users ObjectId = require('mongoose').Types.ObjectId lodash = require 'lodash' uuid = require 'node-uuid' fs = require 'fs' AWS = require 'aws-sdk' config = require '../config/config' AWS.config.region = 'us-west-2' s3bucket = new AWS.S3( params: Bucket: 'jotit' ) module.exports = do -> post: (req, res) -> params = Key: uuid.v4() Body: fs.createReadStream(req.file.path) s3bucket.upload params, (err, data) -> if err res.status 400 res.send err else res.status 200 res.send data.Location
24008
models = require '../models/models' Users = models.Users ObjectId = require('mongoose').Types.ObjectId lodash = require 'lodash' uuid = require 'node-uuid' fs = require 'fs' AWS = require 'aws-sdk' config = require '../config/config' AWS.config.region = 'us-west-2' s3bucket = new AWS.S3( params: Bucket: 'jotit' ) module.exports = do -> post: (req, res) -> params = Key: <KEY>() Body: fs.createReadStream(req.file.path) s3bucket.upload params, (err, data) -> if err res.status 400 res.send err else res.status 200 res.send data.Location
true
models = require '../models/models' Users = models.Users ObjectId = require('mongoose').Types.ObjectId lodash = require 'lodash' uuid = require 'node-uuid' fs = require 'fs' AWS = require 'aws-sdk' config = require '../config/config' AWS.config.region = 'us-west-2' s3bucket = new AWS.S3( params: Bucket: 'jotit' ) module.exports = do -> post: (req, res) -> params = Key: PI:KEY:<KEY>END_PI() Body: fs.createReadStream(req.file.path) s3bucket.upload params, (err, data) -> if err res.status 400 res.send err else res.status 200 res.send data.Location
[ { "context": " source: 0\n time: 0\n\n getResult: (key = 'master') ->\n stat = @stats[key]\n {history, result,", "end": 1704, "score": 0.99538254737854, "start": 1698, "tag": "KEY", "value": "master" }, { "context": "ry.length - 1]\n return result\n\n mark: (key = ...
coffee/benchmark.coffee
ibykow/stargame
0
{max, min} = Math (module ? {}).exports = class Benchmark @period: 300 @getNamedFunctionsOf: (object = {}, except = ['constructor', 'toString']) -> names = [] for name, prop of object when typeof prop is 'function' names.push name unless name in except return names constructor: (@target = {}) -> @stats = @target.stats or {} # Sanitize incoming stats stat.running = false for key, stat of @stats if process?.hrtime @source = 'process.hrtime' @ttime = -> process.hrtime() @tdiff = (t, t1) -> (t1[0] - t[0]) * 1e3 + ((t1[1] - t[1]) / 1e6) else if window?.performance?.now @source = 'window.performance.now' @ttime = -> window.performance.now() else @source = 'Date.now()' @ttime = -> Date.now() @_warn "Using " + @source + ". This isn't going to be very accurate." @wrap @target _fail: (message) -> Error "Benchmark: " + message _info: (message = 'Ping', args...) -> @_log_type message, 'INFO ', args... _log: (message, args...) -> @_log_type message, '', args... _warn: (message, args...) -> @_log_type message, 'WARNING ', args... _log_type: (message, type, args...) -> console.log 'Benchmark ' + type + '(' + (Date.now()) + '): ' + message, args... at: (key) -> @stats[key] ?= count: 0 history: [] index: 0 key: key running: false bench: (callback, args...) -> @mark 'master', callback, args... getBlankResult: -> average: delta: 0 max: 0 min: 0 delta: 0 done: false max: 0 min: 1e16 start: source: 0 time: 0 stop: source: 0 time: 0 getResult: (key = 'master') -> stat = @stats[key] {history, result, running} = @stats[key] if stat? unless result? and (not running or history.length) return @_fail "No results for benchmark '" + key + "'." if running then return history[history.length - 1] return result mark: (key = 'master', callback, args...) -> return @_fail 'Function not provided' unless typeof callback is 'function' stat = @at key stat.count++ return callback args... if stat.running @start key result = callback args... @stop key return result getResultStrings: (result) -> for key in ['delta', 'min', 'max'] result[key].toFixed(2) + '/' + result.average[key].toFixed(2) getStatStrings: (keys...) -> return unless keys.length for key in keys {history, index} = @at key continue unless result = history?[index] key + ': ' + @getResultStrings(result).join ', ' process: (stat) -> return @_fail 'Nothing to process' unless result = stat?.result if result?.processed return @_fail "Cannot process the requested result for benchmark '" + stat.key + "' because it has already been processed." result.processed = true result.delta = @tdiff result.start.source, result.stop.source length = stat.history.length period = Benchmark.period if length head = stat.history[stat.index] nextIndex = stat.index + 1 result.max = max head.max, result.delta result.min = min head.min, result.delta if length is period nextIndex %= period tail = stat.history[nextIndex] newDelta = (result.delta - tail.delta) / period result.average.delta = newDelta + head.average.delta else newSum = head.average.delta * length + result.delta result.average.delta = newSum / (length + 1) result.average.max = max result.average.delta, head.average.max result.average.min = min result.average.delta, head.average.min stat.index = nextIndex else result.max = result.delta result.min = result.delta result.average.delta = result.delta result.average.max = result.delta result.average.min = result.delta stat.history[stat.index] = result return result.delta reset: -> @stats = {} start: (key = 'master') -> stat = @at key return @_fail "'" + key + "' is already running." if stat.running stat.running = true stat.result = @getBlankResult() # Start the timers last to maximize accuracy stat.result.start.time = Date.now() # The highest resolution timer should start last and stop first stat.result.start.source = @ttime() stop: (key = 'master') -> # Grab the time right away to maximize accuracy source = @ttime() time = Date.now() # Sanitize unless (stat = @stats[key]) and stat.running and not stat.result.processed return @_fail "'" + key + "' has not been started." # Process result stat.running = false stat.result.stop.source = source stat.result.stop.time = time @process stat tdiff: (t, t1) -> t1 - t # wrap: Wrap's an object's methods with a call to @mark # @target: the target object # @methodNames: the names of the functions to wrap wrap: (target, names) -> return @_fail 'Cannot wrap unspecified target.' unless target? names ?= Benchmark.getNamedFunctionsOf target return unless names target._benchmarkFunctions ?= {} _mark = @mark.bind @ for name in names # Ignore non-existent functions unless typeof target[name] is 'function' @_warn "Cannot wrap '" + name + "'. It is not a function." continue if target._benchmarkFunctions[name] @_warn "'" + name + "' has already been wrapped." continue # Store the original function and replace it in the target original = target[name] target._benchmarkFunctions[name] = original bound = (n, t, o, a...) -> @mark n, o.bind t, a... bound = bound.bind @, name, target, original target[name] = bound # Unwrap some or all of the target's functions unwrap: (target, methodNames = []) -> return @_fail 'No target was specified for unwrapping.' unless target? if methodNames.length for name in methodNames unless orignal = target._benchmarkFunctions[name] @_warn "Could not unwrap '" + name + "'. Original not found." continue target[name] = target._benchmarkFunctions[name] delete target._benchmarkFunctions[name] else for name of target._benchmarkFunctions target[name] = target._benchmarkFunctions[name] delete target._benchmarkFunctions[name] functionsRemaining = Object.keys(target._benchmarkFunctions)?.length delete target['_benchmarkFunctions'] unless functionsRemaining
203227
{max, min} = Math (module ? {}).exports = class Benchmark @period: 300 @getNamedFunctionsOf: (object = {}, except = ['constructor', 'toString']) -> names = [] for name, prop of object when typeof prop is 'function' names.push name unless name in except return names constructor: (@target = {}) -> @stats = @target.stats or {} # Sanitize incoming stats stat.running = false for key, stat of @stats if process?.hrtime @source = 'process.hrtime' @ttime = -> process.hrtime() @tdiff = (t, t1) -> (t1[0] - t[0]) * 1e3 + ((t1[1] - t[1]) / 1e6) else if window?.performance?.now @source = 'window.performance.now' @ttime = -> window.performance.now() else @source = 'Date.now()' @ttime = -> Date.now() @_warn "Using " + @source + ". This isn't going to be very accurate." @wrap @target _fail: (message) -> Error "Benchmark: " + message _info: (message = 'Ping', args...) -> @_log_type message, 'INFO ', args... _log: (message, args...) -> @_log_type message, '', args... _warn: (message, args...) -> @_log_type message, 'WARNING ', args... _log_type: (message, type, args...) -> console.log 'Benchmark ' + type + '(' + (Date.now()) + '): ' + message, args... at: (key) -> @stats[key] ?= count: 0 history: [] index: 0 key: key running: false bench: (callback, args...) -> @mark 'master', callback, args... getBlankResult: -> average: delta: 0 max: 0 min: 0 delta: 0 done: false max: 0 min: 1e16 start: source: 0 time: 0 stop: source: 0 time: 0 getResult: (key = '<KEY>') -> stat = @stats[key] {history, result, running} = @stats[key] if stat? unless result? and (not running or history.length) return @_fail "No results for benchmark '" + key + "'." if running then return history[history.length - 1] return result mark: (key = '<KEY>', callback, args...) -> return @_fail 'Function not provided' unless typeof callback is 'function' stat = @at key stat.count++ return callback args... if stat.running @start key result = callback args... @stop key return result getResultStrings: (result) -> for key in ['delta', 'min', 'max'] result[key].toFixed(2) + '/' + result.average[key].toFixed(2) getStatStrings: (keys...) -> return unless keys.length for key in keys {history, index} = @at key continue unless result = history?[index] key + ': ' + @getResultStrings(result).join ', ' process: (stat) -> return @_fail 'Nothing to process' unless result = stat?.result if result?.processed return @_fail "Cannot process the requested result for benchmark '" + stat.key + "' because it has already been processed." result.processed = true result.delta = @tdiff result.start.source, result.stop.source length = stat.history.length period = Benchmark.period if length head = stat.history[stat.index] nextIndex = stat.index + 1 result.max = max head.max, result.delta result.min = min head.min, result.delta if length is period nextIndex %= period tail = stat.history[nextIndex] newDelta = (result.delta - tail.delta) / period result.average.delta = newDelta + head.average.delta else newSum = head.average.delta * length + result.delta result.average.delta = newSum / (length + 1) result.average.max = max result.average.delta, head.average.max result.average.min = min result.average.delta, head.average.min stat.index = nextIndex else result.max = result.delta result.min = result.delta result.average.delta = result.delta result.average.max = result.delta result.average.min = result.delta stat.history[stat.index] = result return result.delta reset: -> @stats = {} start: (key = '<KEY>') -> stat = @at key return @_fail "'" + key + "' is already running." if stat.running stat.running = true stat.result = @getBlankResult() # Start the timers last to maximize accuracy stat.result.start.time = Date.now() # The highest resolution timer should start last and stop first stat.result.start.source = @ttime() stop: (key = '<KEY>') -> # Grab the time right away to maximize accuracy source = @ttime() time = Date.now() # Sanitize unless (stat = @stats[key]) and stat.running and not stat.result.processed return @_fail "'" + key + "' has not been started." # Process result stat.running = false stat.result.stop.source = source stat.result.stop.time = time @process stat tdiff: (t, t1) -> t1 - t # wrap: Wrap's an object's methods with a call to @mark # @target: the target object # @methodNames: the names of the functions to wrap wrap: (target, names) -> return @_fail 'Cannot wrap unspecified target.' unless target? names ?= Benchmark.getNamedFunctionsOf target return unless names target._benchmarkFunctions ?= {} _mark = @mark.bind @ for name in names # Ignore non-existent functions unless typeof target[name] is 'function' @_warn "Cannot wrap '" + name + "'. It is not a function." continue if target._benchmarkFunctions[name] @_warn "'" + name + "' has already been wrapped." continue # Store the original function and replace it in the target original = target[name] target._benchmarkFunctions[name] = original bound = (n, t, o, a...) -> @mark n, o.bind t, a... bound = bound.bind @, name, target, original target[name] = bound # Unwrap some or all of the target's functions unwrap: (target, methodNames = []) -> return @_fail 'No target was specified for unwrapping.' unless target? if methodNames.length for name in methodNames unless orignal = target._benchmarkFunctions[name] @_warn "Could not unwrap '" + name + "'. Original not found." continue target[name] = target._benchmarkFunctions[name] delete target._benchmarkFunctions[name] else for name of target._benchmarkFunctions target[name] = target._benchmarkFunctions[name] delete target._benchmarkFunctions[name] functionsRemaining = Object.keys(target._benchmarkFunctions)?.length delete target['_benchmarkFunctions'] unless functionsRemaining
true
{max, min} = Math (module ? {}).exports = class Benchmark @period: 300 @getNamedFunctionsOf: (object = {}, except = ['constructor', 'toString']) -> names = [] for name, prop of object when typeof prop is 'function' names.push name unless name in except return names constructor: (@target = {}) -> @stats = @target.stats or {} # Sanitize incoming stats stat.running = false for key, stat of @stats if process?.hrtime @source = 'process.hrtime' @ttime = -> process.hrtime() @tdiff = (t, t1) -> (t1[0] - t[0]) * 1e3 + ((t1[1] - t[1]) / 1e6) else if window?.performance?.now @source = 'window.performance.now' @ttime = -> window.performance.now() else @source = 'Date.now()' @ttime = -> Date.now() @_warn "Using " + @source + ". This isn't going to be very accurate." @wrap @target _fail: (message) -> Error "Benchmark: " + message _info: (message = 'Ping', args...) -> @_log_type message, 'INFO ', args... _log: (message, args...) -> @_log_type message, '', args... _warn: (message, args...) -> @_log_type message, 'WARNING ', args... _log_type: (message, type, args...) -> console.log 'Benchmark ' + type + '(' + (Date.now()) + '): ' + message, args... at: (key) -> @stats[key] ?= count: 0 history: [] index: 0 key: key running: false bench: (callback, args...) -> @mark 'master', callback, args... getBlankResult: -> average: delta: 0 max: 0 min: 0 delta: 0 done: false max: 0 min: 1e16 start: source: 0 time: 0 stop: source: 0 time: 0 getResult: (key = 'PI:KEY:<KEY>END_PI') -> stat = @stats[key] {history, result, running} = @stats[key] if stat? unless result? and (not running or history.length) return @_fail "No results for benchmark '" + key + "'." if running then return history[history.length - 1] return result mark: (key = 'PI:KEY:<KEY>END_PI', callback, args...) -> return @_fail 'Function not provided' unless typeof callback is 'function' stat = @at key stat.count++ return callback args... if stat.running @start key result = callback args... @stop key return result getResultStrings: (result) -> for key in ['delta', 'min', 'max'] result[key].toFixed(2) + '/' + result.average[key].toFixed(2) getStatStrings: (keys...) -> return unless keys.length for key in keys {history, index} = @at key continue unless result = history?[index] key + ': ' + @getResultStrings(result).join ', ' process: (stat) -> return @_fail 'Nothing to process' unless result = stat?.result if result?.processed return @_fail "Cannot process the requested result for benchmark '" + stat.key + "' because it has already been processed." result.processed = true result.delta = @tdiff result.start.source, result.stop.source length = stat.history.length period = Benchmark.period if length head = stat.history[stat.index] nextIndex = stat.index + 1 result.max = max head.max, result.delta result.min = min head.min, result.delta if length is period nextIndex %= period tail = stat.history[nextIndex] newDelta = (result.delta - tail.delta) / period result.average.delta = newDelta + head.average.delta else newSum = head.average.delta * length + result.delta result.average.delta = newSum / (length + 1) result.average.max = max result.average.delta, head.average.max result.average.min = min result.average.delta, head.average.min stat.index = nextIndex else result.max = result.delta result.min = result.delta result.average.delta = result.delta result.average.max = result.delta result.average.min = result.delta stat.history[stat.index] = result return result.delta reset: -> @stats = {} start: (key = 'PI:KEY:<KEY>END_PI') -> stat = @at key return @_fail "'" + key + "' is already running." if stat.running stat.running = true stat.result = @getBlankResult() # Start the timers last to maximize accuracy stat.result.start.time = Date.now() # The highest resolution timer should start last and stop first stat.result.start.source = @ttime() stop: (key = 'PI:KEY:<KEY>END_PI') -> # Grab the time right away to maximize accuracy source = @ttime() time = Date.now() # Sanitize unless (stat = @stats[key]) and stat.running and not stat.result.processed return @_fail "'" + key + "' has not been started." # Process result stat.running = false stat.result.stop.source = source stat.result.stop.time = time @process stat tdiff: (t, t1) -> t1 - t # wrap: Wrap's an object's methods with a call to @mark # @target: the target object # @methodNames: the names of the functions to wrap wrap: (target, names) -> return @_fail 'Cannot wrap unspecified target.' unless target? names ?= Benchmark.getNamedFunctionsOf target return unless names target._benchmarkFunctions ?= {} _mark = @mark.bind @ for name in names # Ignore non-existent functions unless typeof target[name] is 'function' @_warn "Cannot wrap '" + name + "'. It is not a function." continue if target._benchmarkFunctions[name] @_warn "'" + name + "' has already been wrapped." continue # Store the original function and replace it in the target original = target[name] target._benchmarkFunctions[name] = original bound = (n, t, o, a...) -> @mark n, o.bind t, a... bound = bound.bind @, name, target, original target[name] = bound # Unwrap some or all of the target's functions unwrap: (target, methodNames = []) -> return @_fail 'No target was specified for unwrapping.' unless target? if methodNames.length for name in methodNames unless orignal = target._benchmarkFunctions[name] @_warn "Could not unwrap '" + name + "'. Original not found." continue target[name] = target._benchmarkFunctions[name] delete target._benchmarkFunctions[name] else for name of target._benchmarkFunctions target[name] = target._benchmarkFunctions[name] delete target._benchmarkFunctions[name] functionsRemaining = Object.keys(target._benchmarkFunctions)?.length delete target['_benchmarkFunctions'] unless functionsRemaining
[ { "context": "items =\n 'development':\n 'sitename': 'Adam Stokes'\n 'title': 'steven seagal says hai.'\n ", "end": 674, "score": 0.999410092830658, "start": 663, "tag": "NAME", "value": "Adam Stokes" }, { "context": "emplates\n 'production':\n 'sit...
config.coffee
battlemidget/bummyjab
0
appRoot = require('app-root-path') fs = require('fs') path = require('path') moment = require('moment') handlebars = require('handlebars') class Config constructor: -> @nodeEnv = process.env.NODE_ENV or 'development' @templateDir = "#{appRoot}/templates" @templates = singlePage: fs.readFileSync(appRoot + '/templates/single.hbs').toString() indexPage: fs.readFileSync(appRoot + '/templates/home.hbs').toString() feedPage: fs.readFileSync(appRoot + '/templates/feed.hbs').toString() sitemapPage: fs.readFileSync(appRoot + '/templates/sitemap.hbs').toString() opts: -> items = 'development': 'sitename': 'Adam Stokes' 'title': 'steven seagal says hai.' 'baseUrl': 'http://localhost:3000' 'description': 'ir0n fists' templates: @templates 'production': 'sitename': 'Adam Stokes' 'title': 'steven seagal says hai.' 'baseUrl': 'http://astokes.org' 'description': 'ir0n fists' templates: @templates items[@nodeEnv] module.exports = Config
39966
appRoot = require('app-root-path') fs = require('fs') path = require('path') moment = require('moment') handlebars = require('handlebars') class Config constructor: -> @nodeEnv = process.env.NODE_ENV or 'development' @templateDir = "#{appRoot}/templates" @templates = singlePage: fs.readFileSync(appRoot + '/templates/single.hbs').toString() indexPage: fs.readFileSync(appRoot + '/templates/home.hbs').toString() feedPage: fs.readFileSync(appRoot + '/templates/feed.hbs').toString() sitemapPage: fs.readFileSync(appRoot + '/templates/sitemap.hbs').toString() opts: -> items = 'development': 'sitename': '<NAME>' 'title': 'steven seagal says hai.' 'baseUrl': 'http://localhost:3000' 'description': 'ir0n fists' templates: @templates 'production': 'sitename': '<NAME>' 'title': 'steven seagal says hai.' 'baseUrl': 'http://astokes.org' 'description': 'ir0n fists' templates: @templates items[@nodeEnv] module.exports = Config
true
appRoot = require('app-root-path') fs = require('fs') path = require('path') moment = require('moment') handlebars = require('handlebars') class Config constructor: -> @nodeEnv = process.env.NODE_ENV or 'development' @templateDir = "#{appRoot}/templates" @templates = singlePage: fs.readFileSync(appRoot + '/templates/single.hbs').toString() indexPage: fs.readFileSync(appRoot + '/templates/home.hbs').toString() feedPage: fs.readFileSync(appRoot + '/templates/feed.hbs').toString() sitemapPage: fs.readFileSync(appRoot + '/templates/sitemap.hbs').toString() opts: -> items = 'development': 'sitename': 'PI:NAME:<NAME>END_PI' 'title': 'steven seagal says hai.' 'baseUrl': 'http://localhost:3000' 'description': 'ir0n fists' templates: @templates 'production': 'sitename': 'PI:NAME:<NAME>END_PI' 'title': 'steven seagal says hai.' 'baseUrl': 'http://astokes.org' 'description': 'ir0n fists' templates: @templates items[@nodeEnv] module.exports = Config
[ { "context": "textarea selections handler\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\nclass Selection\n #\n # Basic constructor\n #\n ", "end": 76, "score": 0.999883770942688, "start": 59, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
src/selection.coffee
MadRabbit/osom-area
1
# # The textarea selections handler # # Copyright (C) 2012 Nikolay Nemshilov # class Selection # # Basic constructor # # @param {OsomArea} textarea # @return {Selection} this # constructor: (textarea)-> @textarea = textarea.on blur: -> @selection.save() if @options.keepselection focus: -> @selection.restore() if @options.keepselection return @ # # Sets/reads the current selection offsets # # @param {String|Numeric} the start offset # @param {String|Numeric} the end offset # @return {Array} selection offsets `[start, finish]` # offsets: (start, finish)-> textarea = @textarea._ if !start? # read it start = textarea.selectionStart finish = textarea.selectionEnd else # set it start = parseInt(start) || 0 finish = parseInt(finish) || 0 if finish < start result = start start = finish finish = result result = textarea.value.length start = 0 if start < 0 finish = 0 if finish < 0 start = result if start > result finish = result if finish > result textarea.setSelectionRange(start, finish) return [start, finish] # # Either sets the selection text, or returns # the currently selected text # # @param {String|undefined} text to select or nothing if you wanna read it # @return {String} selection text # text: (text)-> if text? finish = @textarea._.value.indexOf(text) if finish is -1 start = finish = 0 else start = finish + text.length @offsets(start, finish) else start = @offsets() @textarea._.value.substring(start[0], start[1]) # # Calculates the absolute physical offset of the current selection start # # @return {Object} selection position {x: NNN, y: NNN} # position: -> @textarea.mirror.absolute(@offsets()[0]) # # Saves the current selection offsets # save: -> @_stash = @offsets() # # Restores previously saved offsets # restore: -> if @_stash window.setTimeout => @offsets(@_stash[0], @_stash[1]) , 0
47823
# # The textarea selections handler # # Copyright (C) 2012 <NAME> # class Selection # # Basic constructor # # @param {OsomArea} textarea # @return {Selection} this # constructor: (textarea)-> @textarea = textarea.on blur: -> @selection.save() if @options.keepselection focus: -> @selection.restore() if @options.keepselection return @ # # Sets/reads the current selection offsets # # @param {String|Numeric} the start offset # @param {String|Numeric} the end offset # @return {Array} selection offsets `[start, finish]` # offsets: (start, finish)-> textarea = @textarea._ if !start? # read it start = textarea.selectionStart finish = textarea.selectionEnd else # set it start = parseInt(start) || 0 finish = parseInt(finish) || 0 if finish < start result = start start = finish finish = result result = textarea.value.length start = 0 if start < 0 finish = 0 if finish < 0 start = result if start > result finish = result if finish > result textarea.setSelectionRange(start, finish) return [start, finish] # # Either sets the selection text, or returns # the currently selected text # # @param {String|undefined} text to select or nothing if you wanna read it # @return {String} selection text # text: (text)-> if text? finish = @textarea._.value.indexOf(text) if finish is -1 start = finish = 0 else start = finish + text.length @offsets(start, finish) else start = @offsets() @textarea._.value.substring(start[0], start[1]) # # Calculates the absolute physical offset of the current selection start # # @return {Object} selection position {x: NNN, y: NNN} # position: -> @textarea.mirror.absolute(@offsets()[0]) # # Saves the current selection offsets # save: -> @_stash = @offsets() # # Restores previously saved offsets # restore: -> if @_stash window.setTimeout => @offsets(@_stash[0], @_stash[1]) , 0
true
# # The textarea selections handler # # Copyright (C) 2012 PI:NAME:<NAME>END_PI # class Selection # # Basic constructor # # @param {OsomArea} textarea # @return {Selection} this # constructor: (textarea)-> @textarea = textarea.on blur: -> @selection.save() if @options.keepselection focus: -> @selection.restore() if @options.keepselection return @ # # Sets/reads the current selection offsets # # @param {String|Numeric} the start offset # @param {String|Numeric} the end offset # @return {Array} selection offsets `[start, finish]` # offsets: (start, finish)-> textarea = @textarea._ if !start? # read it start = textarea.selectionStart finish = textarea.selectionEnd else # set it start = parseInt(start) || 0 finish = parseInt(finish) || 0 if finish < start result = start start = finish finish = result result = textarea.value.length start = 0 if start < 0 finish = 0 if finish < 0 start = result if start > result finish = result if finish > result textarea.setSelectionRange(start, finish) return [start, finish] # # Either sets the selection text, or returns # the currently selected text # # @param {String|undefined} text to select or nothing if you wanna read it # @return {String} selection text # text: (text)-> if text? finish = @textarea._.value.indexOf(text) if finish is -1 start = finish = 0 else start = finish + text.length @offsets(start, finish) else start = @offsets() @textarea._.value.substring(start[0], start[1]) # # Calculates the absolute physical offset of the current selection start # # @return {Object} selection position {x: NNN, y: NNN} # position: -> @textarea.mirror.absolute(@offsets()[0]) # # Saves the current selection offsets # save: -> @_stash = @offsets() # # Restores previously saved offsets # restore: -> if @_stash window.setTimeout => @offsets(@_stash[0], @_stash[1]) , 0
[ { "context": "me]?\n\n accessToken: (value) ->\n storageKey = \"SC.accessToken\"\n storage = this.storage()\n if value == und", "end": 1459, "score": 0.9803884625434875, "start": 1445, "tag": "KEY", "value": "SC.accessToken" } ]
components/soundcloud/src/sc/connect.coffee
mizukai/sample
91
window.SC = SC.Helper.merge SC || {}, _connectWindow: null connect: (optionsOrCallback) -> if typeof(optionsOrCallback) == "function" options = connected: optionsOrCallback else options = optionsOrCallback dialogOptions = client_id: options.client_id || SC.options.client_id redirect_uri: options.redirect_uri || SC.options.redirect_uri response_type: "code_and_token" scope: options.scope || "non-expiring" display: "popup" window: options.window retainWindow: options.retainWindow if dialogOptions.client_id && dialogOptions.redirect_uri dialog = SC.dialog SC.Dialog.CONNECT, dialogOptions, (params) -> if params.error? throw new Error("SC OAuth2 Error: " + params.error_description) else SC.accessToken(params.access_token) options.connected() if options.connected? options.callback() if options.callback? @_connectWindow = dialog.options.window dialog else throw "Options client_id and redirect_uri must be passed" # legacy from old callback.html connectCallback: -> SC.Dialog._handleDialogReturn(SC._connectWindow) disconnect: -> this.accessToken(null); _trigger: (eventName, argument) -> this.connectCallbacks[eventName](argument) if this.connectCallbacks[eventName]? accessToken: (value) -> storageKey = "SC.accessToken" storage = this.storage() if value == undefined storage.getItem(storageKey) else if value == null storage.removeItem(storageKey) else storage.setItem(storageKey, value) isConnected: -> this.accessToken()?
202294
window.SC = SC.Helper.merge SC || {}, _connectWindow: null connect: (optionsOrCallback) -> if typeof(optionsOrCallback) == "function" options = connected: optionsOrCallback else options = optionsOrCallback dialogOptions = client_id: options.client_id || SC.options.client_id redirect_uri: options.redirect_uri || SC.options.redirect_uri response_type: "code_and_token" scope: options.scope || "non-expiring" display: "popup" window: options.window retainWindow: options.retainWindow if dialogOptions.client_id && dialogOptions.redirect_uri dialog = SC.dialog SC.Dialog.CONNECT, dialogOptions, (params) -> if params.error? throw new Error("SC OAuth2 Error: " + params.error_description) else SC.accessToken(params.access_token) options.connected() if options.connected? options.callback() if options.callback? @_connectWindow = dialog.options.window dialog else throw "Options client_id and redirect_uri must be passed" # legacy from old callback.html connectCallback: -> SC.Dialog._handleDialogReturn(SC._connectWindow) disconnect: -> this.accessToken(null); _trigger: (eventName, argument) -> this.connectCallbacks[eventName](argument) if this.connectCallbacks[eventName]? accessToken: (value) -> storageKey = "<KEY>" storage = this.storage() if value == undefined storage.getItem(storageKey) else if value == null storage.removeItem(storageKey) else storage.setItem(storageKey, value) isConnected: -> this.accessToken()?
true
window.SC = SC.Helper.merge SC || {}, _connectWindow: null connect: (optionsOrCallback) -> if typeof(optionsOrCallback) == "function" options = connected: optionsOrCallback else options = optionsOrCallback dialogOptions = client_id: options.client_id || SC.options.client_id redirect_uri: options.redirect_uri || SC.options.redirect_uri response_type: "code_and_token" scope: options.scope || "non-expiring" display: "popup" window: options.window retainWindow: options.retainWindow if dialogOptions.client_id && dialogOptions.redirect_uri dialog = SC.dialog SC.Dialog.CONNECT, dialogOptions, (params) -> if params.error? throw new Error("SC OAuth2 Error: " + params.error_description) else SC.accessToken(params.access_token) options.connected() if options.connected? options.callback() if options.callback? @_connectWindow = dialog.options.window dialog else throw "Options client_id and redirect_uri must be passed" # legacy from old callback.html connectCallback: -> SC.Dialog._handleDialogReturn(SC._connectWindow) disconnect: -> this.accessToken(null); _trigger: (eventName, argument) -> this.connectCallbacks[eventName](argument) if this.connectCallbacks[eventName]? accessToken: (value) -> storageKey = "PI:KEY:<KEY>END_PI" storage = this.storage() if value == undefined storage.getItem(storageKey) else if value == null storage.removeItem(storageKey) else storage.setItem(storageKey, value) isConnected: -> this.accessToken()?
[ { "context": " of the throttled **fn**\n\n @since 0.1.0\n @author Matheus Kautzmann - <kautzmann5@gmail.com>\n###\nmodule.exports = cla", "end": 520, "score": 0.9998883605003357, "start": 503, "tag": "NAME", "value": "Matheus Kautzmann" }, { "context": "**\n\n @since 0.1.0\n @aut...
src/ScrollProxy.coffee
mkautzmann/scroll-proxy
50
# Require SUtil SUtil = require('./SUtil') ### Main class, containing the scrolling related events and API @option _targetList [HTMLElement] target The anchor of the ScrollProxy instance @option _targetList [ScrollProxy] proxy The instance of ScrollProxy @option _events [String] type The event name of the event @option _events [Function] fn The function that will handle the callback @option _events [Number] timeout The timeout id of the throttled **fn** @since 0.1.0 @author Matheus Kautzmann - <kautzmann5@gmail.com> ### module.exports = class ScrollProxy ### @property [Boolean] Class variable that indicates if ScrollProxy is currently enabled ### @active: no ### @property [Array<Object>] Private Class variable that holds all the elements currently tracked by ScrollProxy ### @_targetList: [] ### @property [String] Class constant that maps to the **scroll** event name ### @SCROLL: 'scroll' ### @property [String] Class constant that maps to the **offsetX** event name ### @OFFSET_X: 'offsetX' ### @property [String] Class constant that maps to the **offsetY** event name ### @OFFSET_Y: 'offsetY' ### @property [String] Class constant that maps to the **top** event name ### @TOP: 'top' ### @property [String] Class constant that maps to the **bottom** event name ### @BOTTOM: 'bottom' ### @property [String] Class constant that maps to the **left** event name ### @LEFT: 'left' ### @property [String] Class constant that maps to the **right** event name ### @RIGHT: 'right' ### @property [String] Class constant that maps to the **visible** event name ### @VISIBLE: 'visible' ### @property [String] Class constant that maps to the **invisible** event name ### @INVISIBLE: 'invisible' ### @property [String] Class constant that maps to the **disable-hover** event name ### @DISABLE_HOVER: 'disable-hover' ### @property [String] Private instance variable that maps to the target's **x** position property ### _targetX: 'scrollLeft' ### @property [String] Private instance variable that maps to the target's **y** position property ### _targetY: 'scrollTop' ### @property [HTMLElement] Private instance variable that indicates the target this ScrollProxy's instance is attached to ### _target: null ### @property [Array<Object>] Private instance variable that holds the events this instance responds to ### _events: [] ### @property [Number] Private instance variable that holds the current delay for scroll throttling ### _scrollDelay: 250 ### @property [Number] Private instance variable that holds the current delay for enabling/disabling hover elements on scroll ### _hoverDelay: 250 ### @property [Number] Private instance variable that holds the current timeout used when blocking hover animations ### _hoverTimeout: null ### @property [Number] Instance variable that holds the current x position of the scroll target ### x: 0 ### @property [Number] Instance variable that holds the current y position of the scroll target ### y: 0 ### @property [Number] Instance variable that holds the current width of the scroll target box ### width: 0 ### @property [Number] Instance variable that holds the current height of the scroll target box ### height: 0 ### @property [Number] scrollWidth Instance variable that holds the current width of the scroll target scroll area ### scrollWidth: 0 ### @property [Number] Instance variable that holds the current height of the scroll target scroll area ### scrollHeight: 0 ### @property [Object] Instance variable that holds the current scroll data (from last scroll action) ### scrollData: {} ### Handles the scroll event when it fires @example Simulating the window firing an event passing the metadata: window.addEventListener('scroll', ScrollProxy.handleScroll, true) @param [Object] e scroll event data @return [Object] Null or the element that catched the event @since 0.1.0 @private ### @_handleScroll: (e) -> len = ScrollProxy._targetList.length if len is 0 then return null # Get the correct target anchor (HTML element) target = e.target.body or e.target return ScrollProxy._getElement(target)?.proxy._performScroll(e) ### Retrieves the current target and proxy for the given HTMLElement @example Checking if the body tag is on _targetList: ScrollProxy._getElement(document.body) @param [HTMLElement] el The element to search for in **_targetList** @return [Object] Null or the target that matched the argument @since 0.1.0 @private ### @_getElement: (el) -> for item in ScrollProxy._targetList if item? and item.target is el return item return null ### Activates the ScrollProxy's functionality, registering the event listener that will listen for scroll events and proxy it to **ScrollProxy.handleScroll** @example Activating ScrollProxy manually, it's done automatically with new: ScrollProxy.activate() @return [Boolean] The current status of ScrollProxy @since 0.1.0 ### @activate: -> if not ScrollProxy.active window.addEventListener( ScrollProxy.SCROLL, ScrollProxy._handleScroll, true ) ScrollProxy.active = yes return ScrollProxy.active ### Deactivates the ScrollProxy's functionality, removing the event listener and stopping any functionality @example Deactivating manually, it's done automatically when unregistering: ScrollProxy.deactivate() @return [Boolean] The current status of ScrollProxy @since 0.1.0 ### @deactivate: -> window.removeEventListener( ScrollProxy.SCROLL, ScrollProxy._handleScroll, true ) return ScrollProxy.active = no ### Cleans the **_targetList**, removing all targets @example To assure ScrollProxy is shut down you could run **clean**: ScrollProxy.clean() @return [Array] Targets removed @since 0.1.0 ### @clean: -> ScrollProxy.deactivate() return ScrollProxy._targetList = [] ### Update this instance rect information, updating x and y positions as well as width, height, scrollWidth and scrollHeight @example Most methods run this function when up-to-date data is required: s = new ScrollProxy() document.body.scrollTop = 20 # s.y continues 0 s.updateViewportInfo() # s.y is 20 now @return [Null] Nothing useful is returned @since 0.1.0 @private ### _updateViewportInfo: -> @x = @_target[@_targetX] @y = @_target[@_targetY] @width = @_target.offsetWidth @height = @_target.offsetHeight @scrollWidth = @_target.scrollWidth @scrollHeight = @_target.scrollHeight return null ### Utility method that Throws error if element given is not child of the **_target** @example Checking a list item inside a ul: s = new ScrollProxy(ul) s._checkElement(li) # does not throw anything, so OK @param [HTMLElement] el The element to check @return [Null] Nothing useful is returned @since 0.1.0 @private ### _checkElement: (el) -> if el not in @_target.children throw new Error('Element must be child of the scroll element') return null ### Remove an event from the list of events @example Don't want to receive scroll feedback anymore: s = new ScrollProxy() evt = s._createEvent('scroll', -> null) s._removeEvent(evt) # OK, event gone @param [Object] The event to remove @return [Array] The new array of events (**_events**) @since 0.1.0 @private ### _removeEvent: (event) -> for item, i in @_events if event is item window.clearTimeout(event.timeout) delete event.fn delete @_events[i] break arr = [] arr.push(item) for item in @_events when item? return @_events = arr ### Checks if the given virtual rect is visible on **_target** viewport @example Check if the rect (0, 0, 50, 50) is visible: s = new ScrollProxy() rect = {x: 0, y:0, w: 50, h: 50} s._isRectVisible(rect) # Visible? @param [Object] rect The rect object to check @option rect [Number] x The top-left x position @option rect [Number] y The top-left y position @option rect [Number] w The width of the rect @option rect [Number] h The height of the rect @return [Boolean] Indicates if visible or not @since 0.1.0 @private ### _isRectVisible: (rect) -> @_updateViewportInfo() xVisible = @x < (rect.x + rect.w) and @x > (rect.x - @width) yVisible = @y < (rect.y + rect.h) and @y > (rect.y - @height) return xVisible and yVisible ### Performs the scroll actions, firing the needed events internally @example The **_handleScroll** usually calls this method: s = new ScrollProxy() s._performScroll(scrollEvt) # OK, related events will be fired @param [Object] The scroll data passed with the event @return [HTMLElement] The current target @since 0.1.0 @private ### _performScroll: (e) -> len = @_events.length if len is 0 then return null @scrollData = e event.fn.call(this, event) for event in @_events return @_target ### Function that performs the scroll throttling to achieve better performance @example One must pass a function to be throttled and a delay: s = new ScrollProxy() func = -> this newFunc = s._throttleScroll(func, 250) newFunc() # func will be called after 250ms, the scrollData will be passed newFunc() # func will not be called, because other call is waiting @param [Function] The function to throttle @param [Number] delay The time function should wait to fire @return [Function] The new throttled function @since 0.1.0 @private ### _throttleScroll: (func, delay) -> running = no return (data) => if running then return running = yes data.timeout = window.setTimeout(=> running = no return SUtil.reportChange(func, this, @scrollData) , (if delay? then delay else @getScrollDelay())) ### Creates a generic event and pushes it in the **_events** array @example Create event with name, callback and optional throttle delay: s = new ScrollProxy() s._createEvent('scroll', -> null, 250) # setting delay of 250ms @param [String] evt The event name to register @param [Function] callback the function to be called when event is fired @param [Function] origin the original function passed, `off` searches for it @param [Number] delay Time to wait in milliseconds @return [Object] The event just registered @since 0.2.0 @private ### _createEvent: (evt, callback, origin, delay) -> fn = @_throttleScroll(callback, delay) return @_events.push({type: evt, fn: fn, origin: origin, timeout: null}) ### Creates a scroll event @example Create scroll event with callback and optional throttle delay: s = new ScrollProxy() s._createScrollEvent('scroll', -> null, 250) # setting delay of 250ms @param [String] evt The event name to register (**scroll**) @param [Function] callback the function to be called when event is fired @param [Function] origin the original function passed, `off` searches for it @param [Number] delay Time to wait in milliseconds @return [Object] The event just registered @since 0.2.0 @private ### _createScrollEvent: (evt, callback, origin = callback, delay) -> return @_createEvent(evt, => @_updateViewportInfo() return SUtil.reportChange(callback, this, @scrollData) , origin, delay) ### Creates a offset event @example Create offset event with callback and optional offset: s = new ScrollProxy() s._createOffsetEvent('offsetX', -> null, 250) # setting offset of 250px @param [String] evt The event name to register, **offsetX** or **offsetY** @param [Function] callback the function to be called when event is fired @param [Number] offset Offset to check for (0 is default) @return [Object] The event just registered @since 0.2.0 @private ### _createOffsetEvent: (evt, callback, offset = 0) -> if evt is ScrollProxy.OFFSET_X return @_createEvent(evt, => if @x is @_target[@_targetX] return else @_updateViewportInfo() if SUtil.isPositiveNumber(offset) and @x < offset then return if SUtil.isNegativeNumber(offset) and @x > Math.abs(offset) then return return SUtil.reportChange(callback, this, @scrollData) , callback) else return @_createEvent(evt, => if @y is @_target[@_targetY] return @_updateViewportInfo() else @_updateViewportInfo() if SUtil.isPositiveNumber(offset) and @y < offset then return if SUtil.isNegativeNumber(offset) and @y > Math.abs(offset) then return return SUtil.reportChange(callback, this, @scrollData) , callback) ### Creates a event to check for horizontal bound collision @example Create horizontal bound event with callback and optional offset: s = new ScrollProxy() s._createHorizontalBoundEvent('left', -> null) # One can also check with a offset inwards, useful for infinite scrolling s._createHorizontalBoundEvent('left', -> null, 250) # fire 250px to left @param [String] evt The event name to register, **left** or **right** @param [Function] callback the function to be called when event is fired @param [Number] offset Offset to check for (0 is defaut) @return [Object] The event just registered @since 0.2.0 @private ### _createHorizontalBoundScrollEvent: (evt, callback, offset = 0) -> if evt is ScrollProxy.LEFT return @_createScrollEvent(evt, => if @x <= Math.abs(offset) return SUtil.reportChange(callback, this, @scrollData) , callback, 0) else return @_createScrollEvent(evt, => if (@scrollWidth - @x) - @width <= Math.abs(offset) return SUtil.reportChange(callback, this, @scrollData) , callback, 0) ### Creates a event to check for vertical bound collision @example Create vertical bound event with callback and optional offset: s = new ScrollProxy() s._createVerticalBoundEvent('top', -> null) # One can also check with a offset inwards, useful for infinite scrolling s._createVerticalBoundEvent('top', -> null, 250) # fire 250px to top @param [String] evt The event name to register, **top** or **bottom** @param [Function] callback the function to be called when event is fired @param [Number] offset Offset to check for @return [Object] The event just registered @since 0.2.0 @private ### _createVerticalBoundScrollEvent: (evt, callback, offset = 0) -> if evt is ScrollProxy.TOP return @_createScrollEvent(evt, => if @y <= Math.abs(offset) return SUtil.reportChange(callback, this, @scrollData) , callback, 0) else return @_createScrollEvent(evt, => if (@scrollHeight - @y) - @height <= Math.abs(offset) return SUtil.reportChange(callback, this, @scrollData) , callback, 0) ### Creates a event to check for element visibility as one scrolls @example Create visibility scroll event with callback and optional offset: s = new ScrollProxy() ul = document.querySelector('.myBeautifulList') s._createVisibilityScrollEvent('visible', -> null, ul) @param [String] evt The event name to register, **visible** or **invisible** @param [Function] callback the function to be called when event is fired @param [Number] offset Offset to check for @return [Object] The event just registered @since 0.2.0 @private ### _createVisibilityScrollEvent: (evt, callback, el) -> @_checkElement(el) if evt is ScrollProxy.VISIBLE return @_createScrollEvent(evt, => if @isElementVisible(el) return SUtil.reportChange(callback, this, @scrollData) , callback) else return @_createScrollEvent(evt, => if not @isElementVisible(el) return SUtil.reportChange(callback, this, @scrollData) , callback) ### The ScrollProxy constructor, use it to create new instances @example Create a new ScrollProxy instance: # Creating a instance in the document.body s = new ScrollProxy() # it defaults to document.body # Creating on a div s = new ScrollProxy(myDiv) # or any HTMLEment # Creating on window s = new ScrollProxy(window) # Remaps to window.document.body @param [HTMLElement] target The element to attach ScrollProxy @return [ScrollProxy] This instance @since 0.2.0 ### constructor: (target = document) -> if target is document target = target.body if target is window target = target.document.body if target instanceof HTMLElement @_target = target else throw new Error('Could not attach to a valid anchor') @_events = [] @register() @_updateViewportInfo() return this ### Sets the scroll delay, any event registered will respect the new value @example Changing the scroll delay mid-flight: s = new ScrollProxy() # Any call will the throttled with 250ms s.on('scroll', -> null) # defaults to 250ms delay s.setScrollDelay(300) # any call now throttles with 300ms @param [Number] ms The delay in milliseconds @return [ScrollProxy] This instance @since 0.1.0 ### setScrollDelay: (ms) -> if SUtil.isPositiveNumber(ms) @_scrollDelay = Math.round(ms) return this ### Returns the current scroll delay @example Getting the current delay: s = new ScrollProxy() s.setScrollDelay(300) # any call now throttles with 300ms s.getScrollDelay() # will be 300 @return [Number] The current value of _scrollDelay @since 0.1.0 ### getScrollDelay: -> @_scrollDelay ### Sets the hover delay. The disable hover function will respect it @example Changing the hover delay mid-flight: s = new ScrollProxy() # Hover animations have 250ms delay on scroll end by default s.disableHoverOnScroll() s.setHoverDelay(300) # now hover delay is 300ms @param [Number] ms The delay in milliseconds @return [ScrollProxy] This instance @since 0.1.0 ### setHoverDelay: (ms) -> if SUtil.isPositiveNumber(ms) @_hoverDelay = Math.round(ms) return this ### Returns the current hover delay @example Getting the current delay: s = new ScrollProxy() s.setHoverDelay(300) # hover animations now have 300ms delay on scroll end s.getHoverDelay() # will be 300 @return [Number] The current value of _hoverDelay @since 0.1.0 ### getHoverDelay: -> @_hoverDelay ### Returns the current target @example Getting the current target: s = new ScrollProxy(myDiv) s.getTarget() # will equal myDiv @return [HTMLElement] The current target @since 0.1.0 ### getTarget: -> @_target ### Returns the rect for an HTMLElement @example Getting body dimensions and position: s = new ScrollProxy(myDiv) s.getRect(document.body) @param [HTMLElement] el The element to get the rect from @return [Object] The rect @since 0.1.0 ### getRect: (el) -> return { x: el.offsetLeft y: el.offsetTop w: el.getBoundingClientRect().width h: el.getBoundingClientRect().height } ### Register events in ScrollProxy @example Registering a new scroll event on body: s = new ScrollProxy() s.on('scroll', -> 'Awesome scrolling!') @param [String] evt The event name to Register @param [Function] func The function to callback once event is fired @param [Object] option A wildcard argument that is passed to the event @event scroll The scroll event that is fired whenever one scrolls @event offsetX The offset event on the X axis that fires once one scrolls past the given horizontal offset @event offsetY The offset event on the Y axis that fires once one scrolls past the given vertical offset @event top The event that fires once one reaches the top of the scroll area or the given offset top @event bottom The event that fires once one reaches the bottom of the scroll area or the given offset bottom @event left The event that fires once one reaches the left bound of the scroll area of the given offset left @event right The event that fires once one reaches the right bound of the scroll area of the given offset right @event visible The event that fires once the given element is visible on the scroll area @event invisible The event that fires once the given element is not visible on the scroll area @return [ScrollProxy] This instance @since 0.1.0 ### on: (evt, func, option) -> if not SUtil.isValidEventName(evt) return this if not SUtil.isFunction(func) return this switch evt when ScrollProxy.SCROLL @_createScrollEvent(evt, func) when ScrollProxy.OFFSET_X, ScrollProxy.OFFSET_Y @_createOffsetEvent(evt, func, option) when ScrollProxy.TOP, ScrollProxy.BOTTOM @_createVerticalBoundScrollEvent(evt, func, option) when ScrollProxy.LEFT, ScrollProxy.RIGHT @_createHorizontalBoundScrollEvent(evt, func, option) when ScrollProxy.VISIBLE, ScrollProxy.INVISIBLE @_createVisibilityScrollEvent(evt, func, option) return this ### Registers events with **on** but just fire the callback the first time @example Register an one time event: s = new ScrollProxy() s.once('top', -> 'I AM ON TOP!') # fires just one time @param [String] evt The event name to register @param [Function] func The function to callback @param [Object] option The wildcard argument that goes with events @return [ScrollProxy] This instance @since 0.2.0 ### once: (evt, func, option) -> oneTimeFunction = => SUtil.reportChange(func, this, @scrollData) @off(evt, oneTimeFunction) return @on(evt, oneTimeFunction, option) ### Removes all events with the specified event name or name and function @example Removing all handlers for one event: s = new ScrollProxy() s.on('scroll', -> 'Free scrolling') s.off('scroll') # no more free scrolling @example Removing just the specific function handler for the event s = new ScrollProxy() func = -> 'Free scrolling' s.on('scroll', func) s.off('scroll', func) @param [String] evt The event name to register @return [ScrollProxy] This instance @since 0.2.0 ### off: (evt, func) -> if not SUtil.isValidEventName(evt) then return this for event, i in @_events if not func? and event? and evt is event.type @_removeEvent(event) else if func? and event? and event.origin is func @_removeEvent(event) return this ### Register this target on ScrollProxy's **_targetList** @example Registering a target (constructor does it automatically): s = new ScrollProxy() s.register() # Throws error because constructor already registered it @example Unregistering first will work: s = new ScrollProxy() s.unregister() # Removing the target s.register() # OK. Target already removed, adding it again @return [ScrollProxy] This instance @since 0.1.0 ### register: -> matchingTarget = ScrollProxy._getElement(@_target) if matchingTarget? then throw new Error('Assign one proxy per target') ScrollProxy._targetList.push({target: @_target, proxy: this}) ScrollProxy.activate() return this ### Unregister this target and remove it from ScrollProxy's **_targetList** @example Unregistering target created automatically by the constructor: s = new ScrollProxy() s.unregister() # ScrollProxy now has no targets, so it deactivates @return [ScrollProxy] This instance @since 0.1.0 ### unregister: -> idx = ScrollProxy._targetList.length if idx > 0 # Reverse loop here to avoid messing with the length cache while idx-- if ScrollProxy._targetList[idx].proxy is this SUtil.removeItemFromArray(ScrollProxy._targetList, idx) break if ScrollProxy._targetList.length is 0 then ScrollProxy.deactivate() return this ### Checks if the element given is visible in the scroll area of the target @example Checking if li is visible within parent ul's scroll area: s = new ScrollProxy(ul) s.isElementVisible(li) # Visible? May be true or false @return [Boolean] Whether it's visible or not @since 0.1.0 ### isElementVisible: (el) -> @_checkElement(el) return @_isRectVisible(@getRect(el)) ### Disables hover animations on scrolling to improve scroll performance @example It must be activated manually to avoid unexpected behavior: s = new ScrollProxy() # defaults to document.body s.disableHoverOnScroll() # Hover animations are now disabled on body @return [ScrollProxy] This instance @since 0.2.0 ### disableHoverOnScroll: -> @_createScrollEvent(ScrollProxy.DISABLE_HOVER, => window.clearTimeout(@_hoverTimeout) @_target.style.pointerEvents = 'none' @_hoverTimeout = window.setTimeout(=> @_target.style.pointerEvents = 'auto' , @getHoverDelay()) , null, 0) return this ### Re-enables hover animations on scrolling @example Once hover animations are disabled, you can re-enable with: s = new ScrollProxy() # defaults to document.body s.disableHoverOnScroll() # Hover animations on scrolling are now disabled s.enableHoverOnScroll() # Hover animations on scrolling are now restored @return [ScrollProxy] This instance @since 0.1.0 ### enableHoverOnScroll: -> @off(ScrollProxy.DISABLE_HOVER) @_target.style.pointerEvents = 'auto' return this
22928
# Require SUtil SUtil = require('./SUtil') ### Main class, containing the scrolling related events and API @option _targetList [HTMLElement] target The anchor of the ScrollProxy instance @option _targetList [ScrollProxy] proxy The instance of ScrollProxy @option _events [String] type The event name of the event @option _events [Function] fn The function that will handle the callback @option _events [Number] timeout The timeout id of the throttled **fn** @since 0.1.0 @author <NAME> - <<EMAIL>> ### module.exports = class ScrollProxy ### @property [Boolean] Class variable that indicates if ScrollProxy is currently enabled ### @active: no ### @property [Array<Object>] Private Class variable that holds all the elements currently tracked by ScrollProxy ### @_targetList: [] ### @property [String] Class constant that maps to the **scroll** event name ### @SCROLL: 'scroll' ### @property [String] Class constant that maps to the **offsetX** event name ### @OFFSET_X: 'offsetX' ### @property [String] Class constant that maps to the **offsetY** event name ### @OFFSET_Y: 'offsetY' ### @property [String] Class constant that maps to the **top** event name ### @TOP: 'top' ### @property [String] Class constant that maps to the **bottom** event name ### @BOTTOM: 'bottom' ### @property [String] Class constant that maps to the **left** event name ### @LEFT: 'left' ### @property [String] Class constant that maps to the **right** event name ### @RIGHT: 'right' ### @property [String] Class constant that maps to the **visible** event name ### @VISIBLE: 'visible' ### @property [String] Class constant that maps to the **invisible** event name ### @INVISIBLE: 'invisible' ### @property [String] Class constant that maps to the **disable-hover** event name ### @DISABLE_HOVER: 'disable-hover' ### @property [String] Private instance variable that maps to the target's **x** position property ### _targetX: 'scrollLeft' ### @property [String] Private instance variable that maps to the target's **y** position property ### _targetY: 'scrollTop' ### @property [HTMLElement] Private instance variable that indicates the target this ScrollProxy's instance is attached to ### _target: null ### @property [Array<Object>] Private instance variable that holds the events this instance responds to ### _events: [] ### @property [Number] Private instance variable that holds the current delay for scroll throttling ### _scrollDelay: 250 ### @property [Number] Private instance variable that holds the current delay for enabling/disabling hover elements on scroll ### _hoverDelay: 250 ### @property [Number] Private instance variable that holds the current timeout used when blocking hover animations ### _hoverTimeout: null ### @property [Number] Instance variable that holds the current x position of the scroll target ### x: 0 ### @property [Number] Instance variable that holds the current y position of the scroll target ### y: 0 ### @property [Number] Instance variable that holds the current width of the scroll target box ### width: 0 ### @property [Number] Instance variable that holds the current height of the scroll target box ### height: 0 ### @property [Number] scrollWidth Instance variable that holds the current width of the scroll target scroll area ### scrollWidth: 0 ### @property [Number] Instance variable that holds the current height of the scroll target scroll area ### scrollHeight: 0 ### @property [Object] Instance variable that holds the current scroll data (from last scroll action) ### scrollData: {} ### Handles the scroll event when it fires @example Simulating the window firing an event passing the metadata: window.addEventListener('scroll', ScrollProxy.handleScroll, true) @param [Object] e scroll event data @return [Object] Null or the element that catched the event @since 0.1.0 @private ### @_handleScroll: (e) -> len = ScrollProxy._targetList.length if len is 0 then return null # Get the correct target anchor (HTML element) target = e.target.body or e.target return ScrollProxy._getElement(target)?.proxy._performScroll(e) ### Retrieves the current target and proxy for the given HTMLElement @example Checking if the body tag is on _targetList: ScrollProxy._getElement(document.body) @param [HTMLElement] el The element to search for in **_targetList** @return [Object] Null or the target that matched the argument @since 0.1.0 @private ### @_getElement: (el) -> for item in ScrollProxy._targetList if item? and item.target is el return item return null ### Activates the ScrollProxy's functionality, registering the event listener that will listen for scroll events and proxy it to **ScrollProxy.handleScroll** @example Activating ScrollProxy manually, it's done automatically with new: ScrollProxy.activate() @return [Boolean] The current status of ScrollProxy @since 0.1.0 ### @activate: -> if not ScrollProxy.active window.addEventListener( ScrollProxy.SCROLL, ScrollProxy._handleScroll, true ) ScrollProxy.active = yes return ScrollProxy.active ### Deactivates the ScrollProxy's functionality, removing the event listener and stopping any functionality @example Deactivating manually, it's done automatically when unregistering: ScrollProxy.deactivate() @return [Boolean] The current status of ScrollProxy @since 0.1.0 ### @deactivate: -> window.removeEventListener( ScrollProxy.SCROLL, ScrollProxy._handleScroll, true ) return ScrollProxy.active = no ### Cleans the **_targetList**, removing all targets @example To assure ScrollProxy is shut down you could run **clean**: ScrollProxy.clean() @return [Array] Targets removed @since 0.1.0 ### @clean: -> ScrollProxy.deactivate() return ScrollProxy._targetList = [] ### Update this instance rect information, updating x and y positions as well as width, height, scrollWidth and scrollHeight @example Most methods run this function when up-to-date data is required: s = new ScrollProxy() document.body.scrollTop = 20 # s.y continues 0 s.updateViewportInfo() # s.y is 20 now @return [Null] Nothing useful is returned @since 0.1.0 @private ### _updateViewportInfo: -> @x = @_target[@_targetX] @y = @_target[@_targetY] @width = @_target.offsetWidth @height = @_target.offsetHeight @scrollWidth = @_target.scrollWidth @scrollHeight = @_target.scrollHeight return null ### Utility method that Throws error if element given is not child of the **_target** @example Checking a list item inside a ul: s = new ScrollProxy(ul) s._checkElement(li) # does not throw anything, so OK @param [HTMLElement] el The element to check @return [Null] Nothing useful is returned @since 0.1.0 @private ### _checkElement: (el) -> if el not in @_target.children throw new Error('Element must be child of the scroll element') return null ### Remove an event from the list of events @example Don't want to receive scroll feedback anymore: s = new ScrollProxy() evt = s._createEvent('scroll', -> null) s._removeEvent(evt) # OK, event gone @param [Object] The event to remove @return [Array] The new array of events (**_events**) @since 0.1.0 @private ### _removeEvent: (event) -> for item, i in @_events if event is item window.clearTimeout(event.timeout) delete event.fn delete @_events[i] break arr = [] arr.push(item) for item in @_events when item? return @_events = arr ### Checks if the given virtual rect is visible on **_target** viewport @example Check if the rect (0, 0, 50, 50) is visible: s = new ScrollProxy() rect = {x: 0, y:0, w: 50, h: 50} s._isRectVisible(rect) # Visible? @param [Object] rect The rect object to check @option rect [Number] x The top-left x position @option rect [Number] y The top-left y position @option rect [Number] w The width of the rect @option rect [Number] h The height of the rect @return [Boolean] Indicates if visible or not @since 0.1.0 @private ### _isRectVisible: (rect) -> @_updateViewportInfo() xVisible = @x < (rect.x + rect.w) and @x > (rect.x - @width) yVisible = @y < (rect.y + rect.h) and @y > (rect.y - @height) return xVisible and yVisible ### Performs the scroll actions, firing the needed events internally @example The **_handleScroll** usually calls this method: s = new ScrollProxy() s._performScroll(scrollEvt) # OK, related events will be fired @param [Object] The scroll data passed with the event @return [HTMLElement] The current target @since 0.1.0 @private ### _performScroll: (e) -> len = @_events.length if len is 0 then return null @scrollData = e event.fn.call(this, event) for event in @_events return @_target ### Function that performs the scroll throttling to achieve better performance @example One must pass a function to be throttled and a delay: s = new ScrollProxy() func = -> this newFunc = s._throttleScroll(func, 250) newFunc() # func will be called after 250ms, the scrollData will be passed newFunc() # func will not be called, because other call is waiting @param [Function] The function to throttle @param [Number] delay The time function should wait to fire @return [Function] The new throttled function @since 0.1.0 @private ### _throttleScroll: (func, delay) -> running = no return (data) => if running then return running = yes data.timeout = window.setTimeout(=> running = no return SUtil.reportChange(func, this, @scrollData) , (if delay? then delay else @getScrollDelay())) ### Creates a generic event and pushes it in the **_events** array @example Create event with name, callback and optional throttle delay: s = new ScrollProxy() s._createEvent('scroll', -> null, 250) # setting delay of 250ms @param [String] evt The event name to register @param [Function] callback the function to be called when event is fired @param [Function] origin the original function passed, `off` searches for it @param [Number] delay Time to wait in milliseconds @return [Object] The event just registered @since 0.2.0 @private ### _createEvent: (evt, callback, origin, delay) -> fn = @_throttleScroll(callback, delay) return @_events.push({type: evt, fn: fn, origin: origin, timeout: null}) ### Creates a scroll event @example Create scroll event with callback and optional throttle delay: s = new ScrollProxy() s._createScrollEvent('scroll', -> null, 250) # setting delay of 250ms @param [String] evt The event name to register (**scroll**) @param [Function] callback the function to be called when event is fired @param [Function] origin the original function passed, `off` searches for it @param [Number] delay Time to wait in milliseconds @return [Object] The event just registered @since 0.2.0 @private ### _createScrollEvent: (evt, callback, origin = callback, delay) -> return @_createEvent(evt, => @_updateViewportInfo() return SUtil.reportChange(callback, this, @scrollData) , origin, delay) ### Creates a offset event @example Create offset event with callback and optional offset: s = new ScrollProxy() s._createOffsetEvent('offsetX', -> null, 250) # setting offset of 250px @param [String] evt The event name to register, **offsetX** or **offsetY** @param [Function] callback the function to be called when event is fired @param [Number] offset Offset to check for (0 is default) @return [Object] The event just registered @since 0.2.0 @private ### _createOffsetEvent: (evt, callback, offset = 0) -> if evt is ScrollProxy.OFFSET_X return @_createEvent(evt, => if @x is @_target[@_targetX] return else @_updateViewportInfo() if SUtil.isPositiveNumber(offset) and @x < offset then return if SUtil.isNegativeNumber(offset) and @x > Math.abs(offset) then return return SUtil.reportChange(callback, this, @scrollData) , callback) else return @_createEvent(evt, => if @y is @_target[@_targetY] return @_updateViewportInfo() else @_updateViewportInfo() if SUtil.isPositiveNumber(offset) and @y < offset then return if SUtil.isNegativeNumber(offset) and @y > Math.abs(offset) then return return SUtil.reportChange(callback, this, @scrollData) , callback) ### Creates a event to check for horizontal bound collision @example Create horizontal bound event with callback and optional offset: s = new ScrollProxy() s._createHorizontalBoundEvent('left', -> null) # One can also check with a offset inwards, useful for infinite scrolling s._createHorizontalBoundEvent('left', -> null, 250) # fire 250px to left @param [String] evt The event name to register, **left** or **right** @param [Function] callback the function to be called when event is fired @param [Number] offset Offset to check for (0 is defaut) @return [Object] The event just registered @since 0.2.0 @private ### _createHorizontalBoundScrollEvent: (evt, callback, offset = 0) -> if evt is ScrollProxy.LEFT return @_createScrollEvent(evt, => if @x <= Math.abs(offset) return SUtil.reportChange(callback, this, @scrollData) , callback, 0) else return @_createScrollEvent(evt, => if (@scrollWidth - @x) - @width <= Math.abs(offset) return SUtil.reportChange(callback, this, @scrollData) , callback, 0) ### Creates a event to check for vertical bound collision @example Create vertical bound event with callback and optional offset: s = new ScrollProxy() s._createVerticalBoundEvent('top', -> null) # One can also check with a offset inwards, useful for infinite scrolling s._createVerticalBoundEvent('top', -> null, 250) # fire 250px to top @param [String] evt The event name to register, **top** or **bottom** @param [Function] callback the function to be called when event is fired @param [Number] offset Offset to check for @return [Object] The event just registered @since 0.2.0 @private ### _createVerticalBoundScrollEvent: (evt, callback, offset = 0) -> if evt is ScrollProxy.TOP return @_createScrollEvent(evt, => if @y <= Math.abs(offset) return SUtil.reportChange(callback, this, @scrollData) , callback, 0) else return @_createScrollEvent(evt, => if (@scrollHeight - @y) - @height <= Math.abs(offset) return SUtil.reportChange(callback, this, @scrollData) , callback, 0) ### Creates a event to check for element visibility as one scrolls @example Create visibility scroll event with callback and optional offset: s = new ScrollProxy() ul = document.querySelector('.myBeautifulList') s._createVisibilityScrollEvent('visible', -> null, ul) @param [String] evt The event name to register, **visible** or **invisible** @param [Function] callback the function to be called when event is fired @param [Number] offset Offset to check for @return [Object] The event just registered @since 0.2.0 @private ### _createVisibilityScrollEvent: (evt, callback, el) -> @_checkElement(el) if evt is ScrollProxy.VISIBLE return @_createScrollEvent(evt, => if @isElementVisible(el) return SUtil.reportChange(callback, this, @scrollData) , callback) else return @_createScrollEvent(evt, => if not @isElementVisible(el) return SUtil.reportChange(callback, this, @scrollData) , callback) ### The ScrollProxy constructor, use it to create new instances @example Create a new ScrollProxy instance: # Creating a instance in the document.body s = new ScrollProxy() # it defaults to document.body # Creating on a div s = new ScrollProxy(myDiv) # or any HTMLEment # Creating on window s = new ScrollProxy(window) # Remaps to window.document.body @param [HTMLElement] target The element to attach ScrollProxy @return [ScrollProxy] This instance @since 0.2.0 ### constructor: (target = document) -> if target is document target = target.body if target is window target = target.document.body if target instanceof HTMLElement @_target = target else throw new Error('Could not attach to a valid anchor') @_events = [] @register() @_updateViewportInfo() return this ### Sets the scroll delay, any event registered will respect the new value @example Changing the scroll delay mid-flight: s = new ScrollProxy() # Any call will the throttled with 250ms s.on('scroll', -> null) # defaults to 250ms delay s.setScrollDelay(300) # any call now throttles with 300ms @param [Number] ms The delay in milliseconds @return [ScrollProxy] This instance @since 0.1.0 ### setScrollDelay: (ms) -> if SUtil.isPositiveNumber(ms) @_scrollDelay = Math.round(ms) return this ### Returns the current scroll delay @example Getting the current delay: s = new ScrollProxy() s.setScrollDelay(300) # any call now throttles with 300ms s.getScrollDelay() # will be 300 @return [Number] The current value of _scrollDelay @since 0.1.0 ### getScrollDelay: -> @_scrollDelay ### Sets the hover delay. The disable hover function will respect it @example Changing the hover delay mid-flight: s = new ScrollProxy() # Hover animations have 250ms delay on scroll end by default s.disableHoverOnScroll() s.setHoverDelay(300) # now hover delay is 300ms @param [Number] ms The delay in milliseconds @return [ScrollProxy] This instance @since 0.1.0 ### setHoverDelay: (ms) -> if SUtil.isPositiveNumber(ms) @_hoverDelay = Math.round(ms) return this ### Returns the current hover delay @example Getting the current delay: s = new ScrollProxy() s.setHoverDelay(300) # hover animations now have 300ms delay on scroll end s.getHoverDelay() # will be 300 @return [Number] The current value of _hoverDelay @since 0.1.0 ### getHoverDelay: -> @_hoverDelay ### Returns the current target @example Getting the current target: s = new ScrollProxy(myDiv) s.getTarget() # will equal myDiv @return [HTMLElement] The current target @since 0.1.0 ### getTarget: -> @_target ### Returns the rect for an HTMLElement @example Getting body dimensions and position: s = new ScrollProxy(myDiv) s.getRect(document.body) @param [HTMLElement] el The element to get the rect from @return [Object] The rect @since 0.1.0 ### getRect: (el) -> return { x: el.offsetLeft y: el.offsetTop w: el.getBoundingClientRect().width h: el.getBoundingClientRect().height } ### Register events in ScrollProxy @example Registering a new scroll event on body: s = new ScrollProxy() s.on('scroll', -> 'Awesome scrolling!') @param [String] evt The event name to Register @param [Function] func The function to callback once event is fired @param [Object] option A wildcard argument that is passed to the event @event scroll The scroll event that is fired whenever one scrolls @event offsetX The offset event on the X axis that fires once one scrolls past the given horizontal offset @event offsetY The offset event on the Y axis that fires once one scrolls past the given vertical offset @event top The event that fires once one reaches the top of the scroll area or the given offset top @event bottom The event that fires once one reaches the bottom of the scroll area or the given offset bottom @event left The event that fires once one reaches the left bound of the scroll area of the given offset left @event right The event that fires once one reaches the right bound of the scroll area of the given offset right @event visible The event that fires once the given element is visible on the scroll area @event invisible The event that fires once the given element is not visible on the scroll area @return [ScrollProxy] This instance @since 0.1.0 ### on: (evt, func, option) -> if not SUtil.isValidEventName(evt) return this if not SUtil.isFunction(func) return this switch evt when ScrollProxy.SCROLL @_createScrollEvent(evt, func) when ScrollProxy.OFFSET_X, ScrollProxy.OFFSET_Y @_createOffsetEvent(evt, func, option) when ScrollProxy.TOP, ScrollProxy.BOTTOM @_createVerticalBoundScrollEvent(evt, func, option) when ScrollProxy.LEFT, ScrollProxy.RIGHT @_createHorizontalBoundScrollEvent(evt, func, option) when ScrollProxy.VISIBLE, ScrollProxy.INVISIBLE @_createVisibilityScrollEvent(evt, func, option) return this ### Registers events with **on** but just fire the callback the first time @example Register an one time event: s = new ScrollProxy() s.once('top', -> 'I AM ON TOP!') # fires just one time @param [String] evt The event name to register @param [Function] func The function to callback @param [Object] option The wildcard argument that goes with events @return [ScrollProxy] This instance @since 0.2.0 ### once: (evt, func, option) -> oneTimeFunction = => SUtil.reportChange(func, this, @scrollData) @off(evt, oneTimeFunction) return @on(evt, oneTimeFunction, option) ### Removes all events with the specified event name or name and function @example Removing all handlers for one event: s = new ScrollProxy() s.on('scroll', -> 'Free scrolling') s.off('scroll') # no more free scrolling @example Removing just the specific function handler for the event s = new ScrollProxy() func = -> 'Free scrolling' s.on('scroll', func) s.off('scroll', func) @param [String] evt The event name to register @return [ScrollProxy] This instance @since 0.2.0 ### off: (evt, func) -> if not SUtil.isValidEventName(evt) then return this for event, i in @_events if not func? and event? and evt is event.type @_removeEvent(event) else if func? and event? and event.origin is func @_removeEvent(event) return this ### Register this target on ScrollProxy's **_targetList** @example Registering a target (constructor does it automatically): s = new ScrollProxy() s.register() # Throws error because constructor already registered it @example Unregistering first will work: s = new ScrollProxy() s.unregister() # Removing the target s.register() # OK. Target already removed, adding it again @return [ScrollProxy] This instance @since 0.1.0 ### register: -> matchingTarget = ScrollProxy._getElement(@_target) if matchingTarget? then throw new Error('Assign one proxy per target') ScrollProxy._targetList.push({target: @_target, proxy: this}) ScrollProxy.activate() return this ### Unregister this target and remove it from ScrollProxy's **_targetList** @example Unregistering target created automatically by the constructor: s = new ScrollProxy() s.unregister() # ScrollProxy now has no targets, so it deactivates @return [ScrollProxy] This instance @since 0.1.0 ### unregister: -> idx = ScrollProxy._targetList.length if idx > 0 # Reverse loop here to avoid messing with the length cache while idx-- if ScrollProxy._targetList[idx].proxy is this SUtil.removeItemFromArray(ScrollProxy._targetList, idx) break if ScrollProxy._targetList.length is 0 then ScrollProxy.deactivate() return this ### Checks if the element given is visible in the scroll area of the target @example Checking if li is visible within parent ul's scroll area: s = new ScrollProxy(ul) s.isElementVisible(li) # Visible? May be true or false @return [Boolean] Whether it's visible or not @since 0.1.0 ### isElementVisible: (el) -> @_checkElement(el) return @_isRectVisible(@getRect(el)) ### Disables hover animations on scrolling to improve scroll performance @example It must be activated manually to avoid unexpected behavior: s = new ScrollProxy() # defaults to document.body s.disableHoverOnScroll() # Hover animations are now disabled on body @return [ScrollProxy] This instance @since 0.2.0 ### disableHoverOnScroll: -> @_createScrollEvent(ScrollProxy.DISABLE_HOVER, => window.clearTimeout(@_hoverTimeout) @_target.style.pointerEvents = 'none' @_hoverTimeout = window.setTimeout(=> @_target.style.pointerEvents = 'auto' , @getHoverDelay()) , null, 0) return this ### Re-enables hover animations on scrolling @example Once hover animations are disabled, you can re-enable with: s = new ScrollProxy() # defaults to document.body s.disableHoverOnScroll() # Hover animations on scrolling are now disabled s.enableHoverOnScroll() # Hover animations on scrolling are now restored @return [ScrollProxy] This instance @since 0.1.0 ### enableHoverOnScroll: -> @off(ScrollProxy.DISABLE_HOVER) @_target.style.pointerEvents = 'auto' return this
true
# Require SUtil SUtil = require('./SUtil') ### Main class, containing the scrolling related events and API @option _targetList [HTMLElement] target The anchor of the ScrollProxy instance @option _targetList [ScrollProxy] proxy The instance of ScrollProxy @option _events [String] type The event name of the event @option _events [Function] fn The function that will handle the callback @option _events [Number] timeout The timeout id of the throttled **fn** @since 0.1.0 @author PI:NAME:<NAME>END_PI - <PI:EMAIL:<EMAIL>END_PI> ### module.exports = class ScrollProxy ### @property [Boolean] Class variable that indicates if ScrollProxy is currently enabled ### @active: no ### @property [Array<Object>] Private Class variable that holds all the elements currently tracked by ScrollProxy ### @_targetList: [] ### @property [String] Class constant that maps to the **scroll** event name ### @SCROLL: 'scroll' ### @property [String] Class constant that maps to the **offsetX** event name ### @OFFSET_X: 'offsetX' ### @property [String] Class constant that maps to the **offsetY** event name ### @OFFSET_Y: 'offsetY' ### @property [String] Class constant that maps to the **top** event name ### @TOP: 'top' ### @property [String] Class constant that maps to the **bottom** event name ### @BOTTOM: 'bottom' ### @property [String] Class constant that maps to the **left** event name ### @LEFT: 'left' ### @property [String] Class constant that maps to the **right** event name ### @RIGHT: 'right' ### @property [String] Class constant that maps to the **visible** event name ### @VISIBLE: 'visible' ### @property [String] Class constant that maps to the **invisible** event name ### @INVISIBLE: 'invisible' ### @property [String] Class constant that maps to the **disable-hover** event name ### @DISABLE_HOVER: 'disable-hover' ### @property [String] Private instance variable that maps to the target's **x** position property ### _targetX: 'scrollLeft' ### @property [String] Private instance variable that maps to the target's **y** position property ### _targetY: 'scrollTop' ### @property [HTMLElement] Private instance variable that indicates the target this ScrollProxy's instance is attached to ### _target: null ### @property [Array<Object>] Private instance variable that holds the events this instance responds to ### _events: [] ### @property [Number] Private instance variable that holds the current delay for scroll throttling ### _scrollDelay: 250 ### @property [Number] Private instance variable that holds the current delay for enabling/disabling hover elements on scroll ### _hoverDelay: 250 ### @property [Number] Private instance variable that holds the current timeout used when blocking hover animations ### _hoverTimeout: null ### @property [Number] Instance variable that holds the current x position of the scroll target ### x: 0 ### @property [Number] Instance variable that holds the current y position of the scroll target ### y: 0 ### @property [Number] Instance variable that holds the current width of the scroll target box ### width: 0 ### @property [Number] Instance variable that holds the current height of the scroll target box ### height: 0 ### @property [Number] scrollWidth Instance variable that holds the current width of the scroll target scroll area ### scrollWidth: 0 ### @property [Number] Instance variable that holds the current height of the scroll target scroll area ### scrollHeight: 0 ### @property [Object] Instance variable that holds the current scroll data (from last scroll action) ### scrollData: {} ### Handles the scroll event when it fires @example Simulating the window firing an event passing the metadata: window.addEventListener('scroll', ScrollProxy.handleScroll, true) @param [Object] e scroll event data @return [Object] Null or the element that catched the event @since 0.1.0 @private ### @_handleScroll: (e) -> len = ScrollProxy._targetList.length if len is 0 then return null # Get the correct target anchor (HTML element) target = e.target.body or e.target return ScrollProxy._getElement(target)?.proxy._performScroll(e) ### Retrieves the current target and proxy for the given HTMLElement @example Checking if the body tag is on _targetList: ScrollProxy._getElement(document.body) @param [HTMLElement] el The element to search for in **_targetList** @return [Object] Null or the target that matched the argument @since 0.1.0 @private ### @_getElement: (el) -> for item in ScrollProxy._targetList if item? and item.target is el return item return null ### Activates the ScrollProxy's functionality, registering the event listener that will listen for scroll events and proxy it to **ScrollProxy.handleScroll** @example Activating ScrollProxy manually, it's done automatically with new: ScrollProxy.activate() @return [Boolean] The current status of ScrollProxy @since 0.1.0 ### @activate: -> if not ScrollProxy.active window.addEventListener( ScrollProxy.SCROLL, ScrollProxy._handleScroll, true ) ScrollProxy.active = yes return ScrollProxy.active ### Deactivates the ScrollProxy's functionality, removing the event listener and stopping any functionality @example Deactivating manually, it's done automatically when unregistering: ScrollProxy.deactivate() @return [Boolean] The current status of ScrollProxy @since 0.1.0 ### @deactivate: -> window.removeEventListener( ScrollProxy.SCROLL, ScrollProxy._handleScroll, true ) return ScrollProxy.active = no ### Cleans the **_targetList**, removing all targets @example To assure ScrollProxy is shut down you could run **clean**: ScrollProxy.clean() @return [Array] Targets removed @since 0.1.0 ### @clean: -> ScrollProxy.deactivate() return ScrollProxy._targetList = [] ### Update this instance rect information, updating x and y positions as well as width, height, scrollWidth and scrollHeight @example Most methods run this function when up-to-date data is required: s = new ScrollProxy() document.body.scrollTop = 20 # s.y continues 0 s.updateViewportInfo() # s.y is 20 now @return [Null] Nothing useful is returned @since 0.1.0 @private ### _updateViewportInfo: -> @x = @_target[@_targetX] @y = @_target[@_targetY] @width = @_target.offsetWidth @height = @_target.offsetHeight @scrollWidth = @_target.scrollWidth @scrollHeight = @_target.scrollHeight return null ### Utility method that Throws error if element given is not child of the **_target** @example Checking a list item inside a ul: s = new ScrollProxy(ul) s._checkElement(li) # does not throw anything, so OK @param [HTMLElement] el The element to check @return [Null] Nothing useful is returned @since 0.1.0 @private ### _checkElement: (el) -> if el not in @_target.children throw new Error('Element must be child of the scroll element') return null ### Remove an event from the list of events @example Don't want to receive scroll feedback anymore: s = new ScrollProxy() evt = s._createEvent('scroll', -> null) s._removeEvent(evt) # OK, event gone @param [Object] The event to remove @return [Array] The new array of events (**_events**) @since 0.1.0 @private ### _removeEvent: (event) -> for item, i in @_events if event is item window.clearTimeout(event.timeout) delete event.fn delete @_events[i] break arr = [] arr.push(item) for item in @_events when item? return @_events = arr ### Checks if the given virtual rect is visible on **_target** viewport @example Check if the rect (0, 0, 50, 50) is visible: s = new ScrollProxy() rect = {x: 0, y:0, w: 50, h: 50} s._isRectVisible(rect) # Visible? @param [Object] rect The rect object to check @option rect [Number] x The top-left x position @option rect [Number] y The top-left y position @option rect [Number] w The width of the rect @option rect [Number] h The height of the rect @return [Boolean] Indicates if visible or not @since 0.1.0 @private ### _isRectVisible: (rect) -> @_updateViewportInfo() xVisible = @x < (rect.x + rect.w) and @x > (rect.x - @width) yVisible = @y < (rect.y + rect.h) and @y > (rect.y - @height) return xVisible and yVisible ### Performs the scroll actions, firing the needed events internally @example The **_handleScroll** usually calls this method: s = new ScrollProxy() s._performScroll(scrollEvt) # OK, related events will be fired @param [Object] The scroll data passed with the event @return [HTMLElement] The current target @since 0.1.0 @private ### _performScroll: (e) -> len = @_events.length if len is 0 then return null @scrollData = e event.fn.call(this, event) for event in @_events return @_target ### Function that performs the scroll throttling to achieve better performance @example One must pass a function to be throttled and a delay: s = new ScrollProxy() func = -> this newFunc = s._throttleScroll(func, 250) newFunc() # func will be called after 250ms, the scrollData will be passed newFunc() # func will not be called, because other call is waiting @param [Function] The function to throttle @param [Number] delay The time function should wait to fire @return [Function] The new throttled function @since 0.1.0 @private ### _throttleScroll: (func, delay) -> running = no return (data) => if running then return running = yes data.timeout = window.setTimeout(=> running = no return SUtil.reportChange(func, this, @scrollData) , (if delay? then delay else @getScrollDelay())) ### Creates a generic event and pushes it in the **_events** array @example Create event with name, callback and optional throttle delay: s = new ScrollProxy() s._createEvent('scroll', -> null, 250) # setting delay of 250ms @param [String] evt The event name to register @param [Function] callback the function to be called when event is fired @param [Function] origin the original function passed, `off` searches for it @param [Number] delay Time to wait in milliseconds @return [Object] The event just registered @since 0.2.0 @private ### _createEvent: (evt, callback, origin, delay) -> fn = @_throttleScroll(callback, delay) return @_events.push({type: evt, fn: fn, origin: origin, timeout: null}) ### Creates a scroll event @example Create scroll event with callback and optional throttle delay: s = new ScrollProxy() s._createScrollEvent('scroll', -> null, 250) # setting delay of 250ms @param [String] evt The event name to register (**scroll**) @param [Function] callback the function to be called when event is fired @param [Function] origin the original function passed, `off` searches for it @param [Number] delay Time to wait in milliseconds @return [Object] The event just registered @since 0.2.0 @private ### _createScrollEvent: (evt, callback, origin = callback, delay) -> return @_createEvent(evt, => @_updateViewportInfo() return SUtil.reportChange(callback, this, @scrollData) , origin, delay) ### Creates a offset event @example Create offset event with callback and optional offset: s = new ScrollProxy() s._createOffsetEvent('offsetX', -> null, 250) # setting offset of 250px @param [String] evt The event name to register, **offsetX** or **offsetY** @param [Function] callback the function to be called when event is fired @param [Number] offset Offset to check for (0 is default) @return [Object] The event just registered @since 0.2.0 @private ### _createOffsetEvent: (evt, callback, offset = 0) -> if evt is ScrollProxy.OFFSET_X return @_createEvent(evt, => if @x is @_target[@_targetX] return else @_updateViewportInfo() if SUtil.isPositiveNumber(offset) and @x < offset then return if SUtil.isNegativeNumber(offset) and @x > Math.abs(offset) then return return SUtil.reportChange(callback, this, @scrollData) , callback) else return @_createEvent(evt, => if @y is @_target[@_targetY] return @_updateViewportInfo() else @_updateViewportInfo() if SUtil.isPositiveNumber(offset) and @y < offset then return if SUtil.isNegativeNumber(offset) and @y > Math.abs(offset) then return return SUtil.reportChange(callback, this, @scrollData) , callback) ### Creates a event to check for horizontal bound collision @example Create horizontal bound event with callback and optional offset: s = new ScrollProxy() s._createHorizontalBoundEvent('left', -> null) # One can also check with a offset inwards, useful for infinite scrolling s._createHorizontalBoundEvent('left', -> null, 250) # fire 250px to left @param [String] evt The event name to register, **left** or **right** @param [Function] callback the function to be called when event is fired @param [Number] offset Offset to check for (0 is defaut) @return [Object] The event just registered @since 0.2.0 @private ### _createHorizontalBoundScrollEvent: (evt, callback, offset = 0) -> if evt is ScrollProxy.LEFT return @_createScrollEvent(evt, => if @x <= Math.abs(offset) return SUtil.reportChange(callback, this, @scrollData) , callback, 0) else return @_createScrollEvent(evt, => if (@scrollWidth - @x) - @width <= Math.abs(offset) return SUtil.reportChange(callback, this, @scrollData) , callback, 0) ### Creates a event to check for vertical bound collision @example Create vertical bound event with callback and optional offset: s = new ScrollProxy() s._createVerticalBoundEvent('top', -> null) # One can also check with a offset inwards, useful for infinite scrolling s._createVerticalBoundEvent('top', -> null, 250) # fire 250px to top @param [String] evt The event name to register, **top** or **bottom** @param [Function] callback the function to be called when event is fired @param [Number] offset Offset to check for @return [Object] The event just registered @since 0.2.0 @private ### _createVerticalBoundScrollEvent: (evt, callback, offset = 0) -> if evt is ScrollProxy.TOP return @_createScrollEvent(evt, => if @y <= Math.abs(offset) return SUtil.reportChange(callback, this, @scrollData) , callback, 0) else return @_createScrollEvent(evt, => if (@scrollHeight - @y) - @height <= Math.abs(offset) return SUtil.reportChange(callback, this, @scrollData) , callback, 0) ### Creates a event to check for element visibility as one scrolls @example Create visibility scroll event with callback and optional offset: s = new ScrollProxy() ul = document.querySelector('.myBeautifulList') s._createVisibilityScrollEvent('visible', -> null, ul) @param [String] evt The event name to register, **visible** or **invisible** @param [Function] callback the function to be called when event is fired @param [Number] offset Offset to check for @return [Object] The event just registered @since 0.2.0 @private ### _createVisibilityScrollEvent: (evt, callback, el) -> @_checkElement(el) if evt is ScrollProxy.VISIBLE return @_createScrollEvent(evt, => if @isElementVisible(el) return SUtil.reportChange(callback, this, @scrollData) , callback) else return @_createScrollEvent(evt, => if not @isElementVisible(el) return SUtil.reportChange(callback, this, @scrollData) , callback) ### The ScrollProxy constructor, use it to create new instances @example Create a new ScrollProxy instance: # Creating a instance in the document.body s = new ScrollProxy() # it defaults to document.body # Creating on a div s = new ScrollProxy(myDiv) # or any HTMLEment # Creating on window s = new ScrollProxy(window) # Remaps to window.document.body @param [HTMLElement] target The element to attach ScrollProxy @return [ScrollProxy] This instance @since 0.2.0 ### constructor: (target = document) -> if target is document target = target.body if target is window target = target.document.body if target instanceof HTMLElement @_target = target else throw new Error('Could not attach to a valid anchor') @_events = [] @register() @_updateViewportInfo() return this ### Sets the scroll delay, any event registered will respect the new value @example Changing the scroll delay mid-flight: s = new ScrollProxy() # Any call will the throttled with 250ms s.on('scroll', -> null) # defaults to 250ms delay s.setScrollDelay(300) # any call now throttles with 300ms @param [Number] ms The delay in milliseconds @return [ScrollProxy] This instance @since 0.1.0 ### setScrollDelay: (ms) -> if SUtil.isPositiveNumber(ms) @_scrollDelay = Math.round(ms) return this ### Returns the current scroll delay @example Getting the current delay: s = new ScrollProxy() s.setScrollDelay(300) # any call now throttles with 300ms s.getScrollDelay() # will be 300 @return [Number] The current value of _scrollDelay @since 0.1.0 ### getScrollDelay: -> @_scrollDelay ### Sets the hover delay. The disable hover function will respect it @example Changing the hover delay mid-flight: s = new ScrollProxy() # Hover animations have 250ms delay on scroll end by default s.disableHoverOnScroll() s.setHoverDelay(300) # now hover delay is 300ms @param [Number] ms The delay in milliseconds @return [ScrollProxy] This instance @since 0.1.0 ### setHoverDelay: (ms) -> if SUtil.isPositiveNumber(ms) @_hoverDelay = Math.round(ms) return this ### Returns the current hover delay @example Getting the current delay: s = new ScrollProxy() s.setHoverDelay(300) # hover animations now have 300ms delay on scroll end s.getHoverDelay() # will be 300 @return [Number] The current value of _hoverDelay @since 0.1.0 ### getHoverDelay: -> @_hoverDelay ### Returns the current target @example Getting the current target: s = new ScrollProxy(myDiv) s.getTarget() # will equal myDiv @return [HTMLElement] The current target @since 0.1.0 ### getTarget: -> @_target ### Returns the rect for an HTMLElement @example Getting body dimensions and position: s = new ScrollProxy(myDiv) s.getRect(document.body) @param [HTMLElement] el The element to get the rect from @return [Object] The rect @since 0.1.0 ### getRect: (el) -> return { x: el.offsetLeft y: el.offsetTop w: el.getBoundingClientRect().width h: el.getBoundingClientRect().height } ### Register events in ScrollProxy @example Registering a new scroll event on body: s = new ScrollProxy() s.on('scroll', -> 'Awesome scrolling!') @param [String] evt The event name to Register @param [Function] func The function to callback once event is fired @param [Object] option A wildcard argument that is passed to the event @event scroll The scroll event that is fired whenever one scrolls @event offsetX The offset event on the X axis that fires once one scrolls past the given horizontal offset @event offsetY The offset event on the Y axis that fires once one scrolls past the given vertical offset @event top The event that fires once one reaches the top of the scroll area or the given offset top @event bottom The event that fires once one reaches the bottom of the scroll area or the given offset bottom @event left The event that fires once one reaches the left bound of the scroll area of the given offset left @event right The event that fires once one reaches the right bound of the scroll area of the given offset right @event visible The event that fires once the given element is visible on the scroll area @event invisible The event that fires once the given element is not visible on the scroll area @return [ScrollProxy] This instance @since 0.1.0 ### on: (evt, func, option) -> if not SUtil.isValidEventName(evt) return this if not SUtil.isFunction(func) return this switch evt when ScrollProxy.SCROLL @_createScrollEvent(evt, func) when ScrollProxy.OFFSET_X, ScrollProxy.OFFSET_Y @_createOffsetEvent(evt, func, option) when ScrollProxy.TOP, ScrollProxy.BOTTOM @_createVerticalBoundScrollEvent(evt, func, option) when ScrollProxy.LEFT, ScrollProxy.RIGHT @_createHorizontalBoundScrollEvent(evt, func, option) when ScrollProxy.VISIBLE, ScrollProxy.INVISIBLE @_createVisibilityScrollEvent(evt, func, option) return this ### Registers events with **on** but just fire the callback the first time @example Register an one time event: s = new ScrollProxy() s.once('top', -> 'I AM ON TOP!') # fires just one time @param [String] evt The event name to register @param [Function] func The function to callback @param [Object] option The wildcard argument that goes with events @return [ScrollProxy] This instance @since 0.2.0 ### once: (evt, func, option) -> oneTimeFunction = => SUtil.reportChange(func, this, @scrollData) @off(evt, oneTimeFunction) return @on(evt, oneTimeFunction, option) ### Removes all events with the specified event name or name and function @example Removing all handlers for one event: s = new ScrollProxy() s.on('scroll', -> 'Free scrolling') s.off('scroll') # no more free scrolling @example Removing just the specific function handler for the event s = new ScrollProxy() func = -> 'Free scrolling' s.on('scroll', func) s.off('scroll', func) @param [String] evt The event name to register @return [ScrollProxy] This instance @since 0.2.0 ### off: (evt, func) -> if not SUtil.isValidEventName(evt) then return this for event, i in @_events if not func? and event? and evt is event.type @_removeEvent(event) else if func? and event? and event.origin is func @_removeEvent(event) return this ### Register this target on ScrollProxy's **_targetList** @example Registering a target (constructor does it automatically): s = new ScrollProxy() s.register() # Throws error because constructor already registered it @example Unregistering first will work: s = new ScrollProxy() s.unregister() # Removing the target s.register() # OK. Target already removed, adding it again @return [ScrollProxy] This instance @since 0.1.0 ### register: -> matchingTarget = ScrollProxy._getElement(@_target) if matchingTarget? then throw new Error('Assign one proxy per target') ScrollProxy._targetList.push({target: @_target, proxy: this}) ScrollProxy.activate() return this ### Unregister this target and remove it from ScrollProxy's **_targetList** @example Unregistering target created automatically by the constructor: s = new ScrollProxy() s.unregister() # ScrollProxy now has no targets, so it deactivates @return [ScrollProxy] This instance @since 0.1.0 ### unregister: -> idx = ScrollProxy._targetList.length if idx > 0 # Reverse loop here to avoid messing with the length cache while idx-- if ScrollProxy._targetList[idx].proxy is this SUtil.removeItemFromArray(ScrollProxy._targetList, idx) break if ScrollProxy._targetList.length is 0 then ScrollProxy.deactivate() return this ### Checks if the element given is visible in the scroll area of the target @example Checking if li is visible within parent ul's scroll area: s = new ScrollProxy(ul) s.isElementVisible(li) # Visible? May be true or false @return [Boolean] Whether it's visible or not @since 0.1.0 ### isElementVisible: (el) -> @_checkElement(el) return @_isRectVisible(@getRect(el)) ### Disables hover animations on scrolling to improve scroll performance @example It must be activated manually to avoid unexpected behavior: s = new ScrollProxy() # defaults to document.body s.disableHoverOnScroll() # Hover animations are now disabled on body @return [ScrollProxy] This instance @since 0.2.0 ### disableHoverOnScroll: -> @_createScrollEvent(ScrollProxy.DISABLE_HOVER, => window.clearTimeout(@_hoverTimeout) @_target.style.pointerEvents = 'none' @_hoverTimeout = window.setTimeout(=> @_target.style.pointerEvents = 'auto' , @getHoverDelay()) , null, 0) return this ### Re-enables hover animations on scrolling @example Once hover animations are disabled, you can re-enable with: s = new ScrollProxy() # defaults to document.body s.disableHoverOnScroll() # Hover animations on scrolling are now disabled s.enableHoverOnScroll() # Hover animations on scrolling are now restored @return [ScrollProxy] This instance @since 0.1.0 ### enableHoverOnScroll: -> @off(ScrollProxy.DISABLE_HOVER) @_target.style.pointerEvents = 'auto' return this